content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Diagnostics.CodeAnalysis; using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Controls; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace OnlyR.VolumeMeter { /// <summary> /// Volume meter custom control using bitmaps on a DrawingVisual. /// See also Themes\Generic.xaml /// </summary> public class VduControl : Control { /// <summary> /// VolumeLevel DP (value range 0 - 100) /// </summary> public static readonly DependencyProperty VolumeLevelProperty = DependencyProperty.Register( "VolumeLevel", typeof(int), typeof(VduControl), new PropertyMetadata(0, OnVolumeChanged)); // change number of levels to add or remove display "blocks" private readonly int _levelsCount = 14; private readonly DrawingVisual _drawingVisual; private Image? _image; private Border? _innerBorder; private SolidColorBrush _backBrush; private SolidColorBrush _lightGreenBrush; private SolidColorBrush _yellowBrush; private SolidColorBrush _redBrush; private List<RenderTargetBitmap?> _bitmaps; static VduControl() { DefaultStyleKeyProperty.OverrideMetadata( typeof(VduControl), new FrameworkPropertyMetadata(typeof(VduControl))); } public VduControl() { Debug.Assert(_levelsCount >= 7, "_levelsCount >= 7"); InitBitmaps(); InitBrushes(); _drawingVisual = new DrawingVisual(); } /// <summary> /// Wraps the VolumeLevel DP (value range 0 - 100) /// </summary> public int VolumeLevel { // wrapper (no additional code in here!) // ReSharper disable once PossibleNullReferenceException get => (int)GetValue(VolumeLevelProperty); set => SetValue(VolumeLevelProperty, value); } public override void OnApplyTemplate() { base.OnApplyTemplate(); if (GetTemplateChild("VolumeImage") is Image image) { _image = image; } if (GetTemplateChild("InnerBorder") is Border border) { _innerBorder = border; } } private static void OnVolumeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is VduControl c) { c.OnVolumeChanged(); } } private void OnVolumeChanged() { Refresh(); } private void Refresh() { if (_image == null) { return; } var numBlocksLit = VolumeLevel * _levelsCount / 100; _image.Source = _bitmaps[numBlocksLit] ?? CreateBitmap(numBlocksLit); } private RenderTargetBitmap? CreateBitmap(int numBlocksLit) { if (_innerBorder == null) { return null; } var bmpHeight = (int)_innerBorder.ActualHeight; var overallBlockHeight = bmpHeight / _levelsCount; bmpHeight = overallBlockHeight * _levelsCount; // normalise var ySpaceBetweenBlocks = Math.Max(overallBlockHeight / 3, 1); var blockHeight = overallBlockHeight - ySpaceBetweenBlocks; var bmpWidth = (int)_innerBorder.ActualWidth; var blockWidth = bmpWidth; _bitmaps[numBlocksLit] = new RenderTargetBitmap(bmpWidth, bmpHeight, 96, 96, PixelFormats.Pbgra32); var numRedBlocks = _levelsCount / 7; var numYellowBlocks = _levelsCount / 4; using (DrawingContext dc = _drawingVisual.RenderOpen()) { dc.DrawRectangle(_backBrush, null, new Rect(0, 0, blockWidth, blockHeight)); for (int n = 0; n < numBlocksLit; ++n) { SolidColorBrush b; if (n >= _levelsCount - numRedBlocks) { b = _redBrush; } else if (n >= _levelsCount - numRedBlocks - numYellowBlocks) { b = _yellowBrush; } else { b = _lightGreenBrush; } dc.DrawRectangle( b, null, new Rect( 0, bmpHeight - ((n + 1) * (blockHeight + ySpaceBetweenBlocks)), blockWidth, blockHeight)); } } _bitmaps[numBlocksLit]?.Render(_drawingVisual); return _bitmaps[numBlocksLit]; } [MemberNotNull(nameof(_backBrush), nameof(_lightGreenBrush), nameof(_yellowBrush), nameof(_redBrush))] private void InitBrushes() { _backBrush = new SolidColorBrush { Color = Colors.Black }; _lightGreenBrush = new SolidColorBrush { Color = Colors.GreenYellow }; _yellowBrush = new SolidColorBrush { Color = Colors.Yellow }; _redBrush = new SolidColorBrush { Color = Colors.Red }; } [MemberNotNull(nameof(_bitmaps))] private void InitBitmaps() { _bitmaps = new List<RenderTargetBitmap?>(); for (int n = 0; n < _levelsCount + 1; ++n) { _bitmaps.Add(null); } } } }
31.266304
111
0.536242
[ "MIT" ]
AntonyCorbett/OnlyR
OnlyR/VolumeMeter/VduControl.cs
5,755
C#
using System.Threading.Tasks; using Microsoft.Extensions.Options; using Orleans.Configuration; using Xunit; using Xunit.Abstractions; using Orleans.Hosting; using Orleans.TestingHost; namespace Tester.AzureUtils.Persistence { /// <summary> /// PersistenceGrainTests using AzureGrainStorage - Requires access to external Azure table storage /// </summary> [TestCategory("Persistence"), TestCategory("Azure")] public class PersistenceGrainTests_AzureTableGrainStorage : Base_PersistenceGrainTests_AzureStore, IClassFixture<PersistenceGrainTests_AzureTableGrainStorage.Fixture> { public class Fixture : BaseAzureTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.InitialSilosCount = 4; builder.Options.UseTestClusterMembership = false; builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<MySiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<ClientBuilderConfigurator>(); } private class MySiloBuilderConfigurator : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder .AddAzureTableGrainStorage("GrainStorageForTest", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); options.DeleteStateOnClear = true; })) .AddAzureTableGrainStorage("AzureStore1", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); })) .AddAzureTableGrainStorage("AzureStore2", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); })) .AddAzureTableGrainStorage("AzureStore3", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConfigureTestDefaults(); })) .AddMemoryGrainStorage("MemoryStore"); } } } public PersistenceGrainTests_AzureTableGrainStorage(ITestOutputHelper output, Fixture fixture) : base(output, fixture) { fixture.EnsurePreconditionsMet(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_AzureTableGrainStorage_Delete() { await base.Grain_AzureStore_Delete(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_AzureTableGrainStorage_Read() { await base.Grain_AzureStore_Read(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_GuidKey_AzureTableGrainStorage_Read_Write() { await base.Grain_GuidKey_AzureStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_LongKey_AzureTableGrainStorage_Read_Write() { await base.Grain_LongKey_AzureStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_LongKeyExtended_AzureTableGrainStorage_Read_Write() { await base.Grain_LongKeyExtended_AzureStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_GuidKeyExtended_AzureTableGrainStorage_Read_Write() { await base.Grain_GuidKeyExtended_AzureStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_Generic_AzureTableGrainStorage_Read_Write() { StorageEmulatorUtilities.EnsureEmulatorIsNotUsed(); await base.Grain_Generic_AzureStore_Read_Write(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_Generic_AzureTableGrainStorage_DiffTypes() { StorageEmulatorUtilities.EnsureEmulatorIsNotUsed(); await base.Grain_Generic_AzureStore_DiffTypes(); } [SkippableFact, TestCategory("Functional")] public async Task Grain_AzureTableGrainStorage_SiloRestart() { await base.Grain_AzureStore_SiloRestart(); } } }
39.608333
170
0.622975
[ "MIT" ]
Arithmomaniac/orleans
test/Extensions/TesterAzureUtils/Persistence/PersistenceGrainTests_AzureTableGrainStorage.cs
4,753
C#
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. using JetBrains.Annotations; namespace MarginTrading.AccountsManagement.Contracts.Api { public class CreateDefaultAccountsRequest { [NotNull] public string TradingConditionId { get; set; } [NotNull] public string ClientId { get; set; } } }
24.1875
65
0.687339
[ "MIT-0" ]
LykkeBusiness/MarginTrading.AccountsManagement
src/MarginTrading.AccountsManagement.Contracts/Api/CreateDefaultAccountsRequest.cs
389
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.AlertsManagement.V20181102PrivatePreview.Inputs { /// <summary> /// Target scope for a given action rule. By default scope will be the subscription. User can also provide list of resource groups or list of resources from the scope subscription as well. /// </summary> public sealed class ScopeArgs : Pulumi.ResourceArgs { /// <summary> /// type of target scope /// </summary> [Input("type")] public Input<string>? Type { get; set; } [Input("values")] private InputList<string>? _values; /// <summary> /// list of ARM IDs of the given scope type which will be the target of the given action rule. /// </summary> public InputList<string> Values { get => _values ?? (_values = new InputList<string>()); set => _values = value; } public ScopeArgs() { } } }
30.780488
192
0.625198
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/AlertsManagement/V20181102PrivatePreview/Inputs/ScopeArgs.cs
1,262
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WebServices.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="WS_SERVICE_SECURITY_IDENTITIES" /> struct.</summary> public static unsafe partial class WS_SERVICE_SECURITY_IDENTITIESTests { /// <summary>Validates that the <see cref="WS_SERVICE_SECURITY_IDENTITIES" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<WS_SERVICE_SECURITY_IDENTITIES>(), Is.EqualTo(sizeof(WS_SERVICE_SECURITY_IDENTITIES))); } /// <summary>Validates that the <see cref="WS_SERVICE_SECURITY_IDENTITIES" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(WS_SERVICE_SECURITY_IDENTITIES).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="WS_SERVICE_SECURITY_IDENTITIES" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(WS_SERVICE_SECURITY_IDENTITIES), Is.EqualTo(16)); } else { Assert.That(sizeof(WS_SERVICE_SECURITY_IDENTITIES), Is.EqualTo(8)); } } } }
39.477273
145
0.666667
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/WebServices/WS_SERVICE_SECURITY_IDENTITIESTests.cs
1,739
C#
using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; namespace AssetBundles { public class BuildScript { public static string overloadedDevelopmentServerURL = ""; static public string CreateAssetBundleDirectory() { // Choose the output path according to the build target. string outputPath = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName()); if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); return outputPath; } public static void BuildAssetBundles() { // Choose the output path according to the build target. string outputPath = CreateAssetBundleDirectory(); var options = BuildAssetBundleOptions.None; bool shouldCheckODR = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS; #if UNITY_TVOS shouldCheckODR |= EditorUserBuildSettings.activeBuildTarget == BuildTarget.tvOS; #endif if (shouldCheckODR) { #if ENABLE_IOS_ON_DEMAND_RESOURCES if (PlayerSettings.iOS.useOnDemandResources) options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif #if ENABLE_IOS_APP_SLICING options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif } //@TODO: use append hash... (Make sure pipeline works correctly with it.) BuildPipeline.BuildAssetBundles(outputPath, options, EditorUserBuildSettings.activeBuildTarget); } public static void WriteServerURL() { string downloadURL; if (string.IsNullOrEmpty(overloadedDevelopmentServerURL) == false) { downloadURL = overloadedDevelopmentServerURL; } else { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } downloadURL = "http://" + localIP + ":7888/"; } string assetBundleManagerResourcesDirectory = "Assets/AssetBundleManager/Resources"; string assetBundleUrlPath = Path.Combine(assetBundleManagerResourcesDirectory, "AssetBundleServerURL.bytes"); Directory.CreateDirectory(assetBundleManagerResourcesDirectory); File.WriteAllText(assetBundleUrlPath, downloadURL); AssetDatabase.Refresh(); } public static void BuildPlayer() { var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", ""); if (outputPath.Length == 0) return; string[] levels = GetLevelsFromBuildSettings(); if (levels.Length == 0) { Debug.Log("Nothing to build."); return; } string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget); if (targetName == null) return; // Build and copy AssetBundles. BuildScript.BuildAssetBundles(); WriteServerURL(); #if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option); #else BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = levels; buildPlayerOptions.locationPathName = outputPath + targetName; buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath(); buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget; buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(buildPlayerOptions); #endif } public static void BuildStandalonePlayer() { var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", ""); if (outputPath.Length == 0) return; string[] levels = GetLevelsFromBuildSettings(); if (levels.Length == 0) { Debug.Log("Nothing to build."); return; } string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget); if (targetName == null) return; // Build and copy AssetBundles. BuildScript.BuildAssetBundles(); BuildScript.CopyAssetBundlesTo(Path.Combine(Application.streamingAssetsPath, Utility.AssetBundlesOutputPath)); AssetDatabase.Refresh(); #if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option); #else BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = levels; buildPlayerOptions.locationPathName = outputPath + targetName; buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath(); buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget; buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(buildPlayerOptions); #endif } public static string GetBuildTargetName(BuildTarget target) { switch (target) { case BuildTarget.Android: return "/test.apk"; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: return "/test.exe"; case BuildTarget.StandaloneOSXIntel: case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: return "/test.app"; case BuildTarget.WebPlayer: case BuildTarget.WebPlayerStreamed: case BuildTarget.WebGL: case BuildTarget.iOS: return ""; // Add more build targets for your own. default: Debug.Log("Target not implemented."); return null; } } static void CopyAssetBundlesTo(string outputPath) { // Clear streaming assets folder. FileUtil.DeleteFileOrDirectory(Application.streamingAssetsPath); Directory.CreateDirectory(outputPath); string outputFolder = Utility.GetPlatformName(); // Setup the source folder for assetbundles. var source = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, Utility.AssetBundlesOutputPath), outputFolder); if (!System.IO.Directory.Exists(source)) Debug.Log("No assetBundle output folder, try to build the assetBundles first."); // Setup the destination folder for assetbundles. var destination = System.IO.Path.Combine(outputPath, outputFolder); if (System.IO.Directory.Exists(destination)) FileUtil.DeleteFileOrDirectory(destination); FileUtil.CopyFileOrDirectory(source, destination); } static string[] GetLevelsFromBuildSettings() { List<string> levels = new List<string>(); for (int i = 0; i < EditorBuildSettings.scenes.Length; ++i) { if (EditorBuildSettings.scenes[i].enabled) levels.Add(EditorBuildSettings.scenes[i].path); } return levels.ToArray(); } static string GetAssetBundleManifestFilePath() { var relativeAssetBundlesOutputPathForPlatform = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName()); return Path.Combine(relativeAssetBundlesOutputPathForPlatform, Utility.GetPlatformName()) + ".manifest"; } } }
40.766055
135
0.621357
[ "MIT" ]
hellogavin/AssetBundleDemo
demo/Assets/AssetBundleManager/Editor/BuildScript.cs
8,887
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using FastRsync.Hash; using FastRsync.Signature; using NUnit.Framework; namespace FastRsync.Tests { class CommonAsserts { public static void ValidateSignature(Stream signatureStream, IHashAlgorithm hashAlgorithm, string baseFileHash, IRollingChecksum rollingAlgorithm) { signatureStream.Seek(0, SeekOrigin.Begin); var sig = new SignatureReader(signatureStream, null).ReadSignature(); Assert.AreEqual(RsyncFormatType.FastRsync, sig.Type); Assert.AreEqual(hashAlgorithm.Name, sig.HashAlgorithm.Name); Assert.AreEqual(hashAlgorithm.Name, sig.Metadata.ChunkHashAlgorithm); Assert.AreEqual(hashAlgorithm.HashLength, sig.HashAlgorithm.HashLength); Assert.AreEqual(rollingAlgorithm.Name, sig.RollingChecksumAlgorithm.Name); Assert.AreEqual(rollingAlgorithm.Name, sig.Metadata.RollingChecksumAlgorithm); Assert.AreEqual("MD5", sig.Metadata.BaseFileHashAlgorithm); Assert.AreEqual(baseFileHash, sig.Metadata.BaseFileHash); } } }
40.366667
154
0.728324
[ "Apache-2.0" ]
GrzegorzBlok/FastRsyncNet
source/FastRsync.Tests/CommonAsserts.cs
1,213
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.RedisIntegration { using Newtonsoft.Json; using Serialization; static class SagaSerializer { internal static string Serialize<T>(T value) => JsonConvert.SerializeObject(value, typeof(T), JsonMessageSerializer.SerializerSettings); internal static T Deserialize<T>(string json) => JsonConvert.DeserializeObject<T>(json, JsonMessageSerializer.DeserializerSettings); } }
40.407407
100
0.727773
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/Persistence/MassTransit.RedisIntegration/SagaSerializer.cs
1,093
C#
using System.Collections.Generic; using Microsoft.Xna.Framework; using MonoGame.Extended; namespace DF.Framework.Particles { public static class TemplateParticles { public static void createPoofEffect( Vector2 position, // Initial position of the particle system int range, // Range in which particles should be spawned, counting from position int amount, // Amount of particles float minVelocity, // Minimum velocity a particle may have float maxVelocity, // Maximum radius a particle may have float friction, // Friction of particles int minRadius, // Minimum radius a particle may have int maxRadius, // Maximum radius a particle may have int framesUntilSmaller, // Frames until particle radius is decreased Color color, // Color of the particle List<Color> colors = null // Optional. List of colors a particle may have, if null, all particles will take color argument ) { particleArgs args = new particleArgs(); args.friction = friction; args.maxFramesUntilSmaller = framesUntilSmaller; while (amount > 0) { amount--; args.velocity = new Vector2(Util.random.NextSingle(minVelocity, maxVelocity) * Util.randomPositiveOrNegative(1, 0.5f), Util.random.NextSingle(minVelocity, maxVelocity) * Util.randomPositiveOrNegative(1,0.5f)); args.position.X = position.X + ( Util.random.Next(0, range) * Util.randomPositiveOrNegative(1, 0.5f)); args.position.Y = position.Y + ( Util.random.Next(0, range) * Util.randomPositiveOrNegative(1, 0.5f)); args.radius = Util.random.Next(minRadius, maxRadius); if (colors is null) { args.color = color; } else { args.color = colors[Util.random.Next(0, colors.Count)]; } ParticleManager.particles.Add(new Particle(args)); } } public struct poofArgs { public poofArgs( Vector2 position, int range, int amount, float minVelocity, float maxVelocity, float friction, int minRadius, int maxRadius, int framesUntilSmaller, Color color, List<Color> colors) { this.position = position; this.range = range; this.amount = amount; this.minVelocity = minVelocity; this.maxVelocity = maxVelocity; this.friction = friction; this.minRadius = minRadius; this.maxRadius = maxRadius; this.framesUntilSmaller = framesUntilSmaller; this.color = color; this.colors = colors; } public Vector2 position; public int range; public int amount; public float minVelocity; public float maxVelocity; public float friction; public int minRadius; public int maxRadius; public int framesUntilSmaller; public Color color; public List<Color> colors; } public static poofArgs deathEffect = new poofArgs(new Vector2(62, 62), 8, 8, 0, 1, 0.7f, 3, 5, 7, Color.MonoGameOrange, null ); } }
40.648148
225
0.455809
[ "MIT" ]
Cuber01/DF
DF/Framework/Particles/TemplateParticles.cs
4,390
C#
using HastaneYonetimRandevuSistemi.Entities.Concrete; namespace HastaneYonetimRandevuSistemi.DataAccess.Concrete.EntityFramework.Mappings { class SecretaryMap : PersonMap<Secretary> { } }
22.444444
83
0.80198
[ "MIT" ]
furkanisitan/CSharp-WinForm-Projects
HastaneYonetimRandevuSistemi/HastaneYonetimRandevuSistemi.DataAccess/Concrete/EntityFramework/Mappings/SecretaryMap.cs
204
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System.Collections.Generic; using System.Numerics; using SixLabors.Fonts.Tables.General.Kern; namespace SixLabors.Fonts.Tables.General { [TableName(TableName)] internal sealed class KerningTable : Table { private const string TableName = "kern"; private readonly KerningSubTable[] kerningSubTable; public KerningTable(KerningSubTable[] kerningSubTable) { this.kerningSubTable = kerningSubTable; } public static KerningTable Load(FontReader reader) { using (BinaryReader binaryReader = reader.GetReaderAtTablePosition(TableName)) { if (binaryReader is null) { // this table is optional. return new KerningTable(new KerningSubTable[0]); } // move to start of table return Load(binaryReader); } } public static KerningTable Load(BinaryReader reader) { // Type | Field | Description // -------|----------|----------------------------------------- // uint16 | version | Table version number(0) // uint16 | nTables | Number of subtables in the kerning table. ushort version = reader.ReadUInt16(); ushort subtableCount = reader.ReadUInt16(); var tables = new List<KerningSubTable>(subtableCount); for (int i = 0; i < subtableCount; i++) { KerningSubTable t = KerningSubTable.Load(reader); // returns null for unknown/supported table format if (t != null) { tables.Add(t); } } return new KerningTable(tables.ToArray()); } public Vector2 GetOffset(ushort left, ushort right) { Vector2 result = Vector2.Zero; foreach (KerningSubTable sub in this.kerningSubTable) { sub.ApplyOffset(left, right, ref result); } return result; } } }
31.842857
116
0.538807
[ "Apache-2.0" ]
Jjagg/Fonts
src/SixLabors.Fonts/Tables/General/KerningTable.cs
2,231
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using UnityEngine; using Verse; using Verse.AI; using Verse.AI.Group; using RimWorld; using RimWorld.Planet; using HarmonyLib; namespace VFESecurity { public abstract class ArtilleryStrikeArrivalAction_AIBase : ArtilleryStrikeArrivalAction { protected abstract bool CanDoArriveAction { get; } protected abstract int MapSize { get; } protected abstract int BaseSize { get; } protected abstract float DestroyChancePerCellInRect { get; } public override void Arrived(List<ActiveArtilleryStrike> artilleryStrikes, int tile) { // Boom if (CanDoArriveAction) { var harmfulStrikes = artilleryStrikes.Where(s => s.shellDef.projectile.damageDef.harmsHealth); if (harmfulStrikes.Any()) { PreStrikeAction(); bool destroyed = false; var mapRect = new CellRect(0, 0, MapSize, MapSize); var baseRect = new CellRect(GenMath.RoundRandom(mapRect.Width / 2f) - GenMath.RoundRandom(BaseSize / 2f), GenMath.RoundRandom(mapRect.Height / 2f) - GenMath.RoundRandom(BaseSize / 2f), BaseSize, BaseSize); var strikeList = harmfulStrikes.ToList(); for (int i = 0; i < strikeList.Count; i++) { var strike = strikeList[i]; for (int j = 0; j < strike.shellCount; j++) StrikeAction(strike, mapRect, baseRect, ref destroyed); } PostStrikeAction(destroyed); } } } protected virtual void PreStrikeAction() { } protected virtual void StrikeAction(ActiveArtilleryStrike strike, CellRect mapRect, CellRect baseRect, ref bool destroyed) { } protected virtual void PostStrikeAction(bool destroyed) { } public override void ExposeData() { Scribe_References.Look(ref worldObject, "worldObject"); Scribe_References.Look(ref sourceMap, "sourceMap"); base.ExposeData(); } protected WorldObject worldObject; protected Map sourceMap; } }
28.230769
225
0.560919
[ "MIT" ]
AndroidQuazar/VanillaFurnitureExpanded-Security
1.2/Source/VFESecurity/ArrivalActions/ArtilleryStrikeArrivalAction_AIBase.cs
2,571
C#
using System.Web.Mvc; namespace AMA.ERegister.WebApi.Areas.AdminPage { public class AdminPageAreaRegistration : AreaRegistration { public override string AreaName { get { return "AdminPage"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "AdminPage_default", "Admin/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "AMA.ERegister.WebApi.Areas.AdminPage.Controllers" } ); } } }
27.88
90
0.535151
[ "MIT" ]
ahmedmatem/ERegister
AMA.ERegister.WebApi/Areas/AdminPage/AdminPageAreaRegistration.cs
699
C#
using System; namespace ProviderBase.Data.Entities { public class DataProviderResultSet : Attribute { public int ResultSetID { get; set; } public string LinkTable { get; set; } public DataProviderResultSet(int resultSet) { this.ResultSetID = resultSet; this.LinkTable = ""; } public DataProviderResultSet(int resultSet, string linkTable) { this.ResultSetID = resultSet; this.LinkTable = linkTable; } } }
22.208333
69
0.589118
[ "MIT" ]
ch604aru/ProviderBase
ProviderBase.Data/Entities/DataProviderResultSet.cs
535
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Tests.Tracing { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Xml; using Microsoft.Azure.Cosmos.ChangeFeed; using Microsoft.Azure.Cosmos.ChangeFeed.Pagination; using Microsoft.Azure.Cosmos.CosmosElements; using Microsoft.Azure.Cosmos.Pagination; using Microsoft.Azure.Cosmos.Query.Core; using Microsoft.Azure.Cosmos.Query.Core.Metrics; using Microsoft.Azure.Cosmos.Query.Core.Monads; using Microsoft.Azure.Cosmos.Query.Core.Pipeline; using Microsoft.Azure.Cosmos.Query.Core.Pipeline.Pagination; using Microsoft.Azure.Cosmos.Query.Core.QueryPlan; using Microsoft.Azure.Cosmos.ReadFeed; using Microsoft.Azure.Cosmos.ReadFeed.Pagination; using Microsoft.Azure.Cosmos.Test.BaselineTest; using Microsoft.Azure.Cosmos.Tests.Pagination; using Microsoft.Azure.Cosmos.Tests.Query.Metrics; using Microsoft.Azure.Cosmos.Tracing; using Microsoft.Azure.Cosmos.Tracing.TraceData; using Microsoft.Azure.Documents; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using static Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum; [TestClass] public sealed class TraceWriterBaselineTests : BaselineTests<TraceWriterBaselineTests.Input, TraceWriterBaselineTests.Output> { private static readonly QueryMetrics MockQueryMetrics = new QueryMetrics( BackendMetricsTests.MockBackendMetrics, IndexUtilizationInfoTests.MockIndexUtilizationInfo, ClientSideMetricsTests.MockClientSideMetrics); private static readonly Dictionary<string, object> DefaultQueryEngineConfiguration = new Dictionary<string, object>() { {"maxSqlQueryInputLength", 30720}, {"maxJoinsPerSqlQuery", 5}, {"maxLogicalAndPerSqlQuery", 200}, {"maxLogicalOrPerSqlQuery", 200}, {"maxUdfRefPerSqlQuery", 2}, {"maxInExpressionItemsCount", 8000}, {"queryMaxInMemorySortDocumentCount", 500}, {"maxQueryRequestTimeoutFraction", 0.90}, {"sqlAllowNonFiniteNumbers", false}, {"sqlAllowAggregateFunctions", true}, {"sqlAllowSubQuery", true}, {"sqlAllowScalarSubQuery", false}, {"allowNewKeywords", true}, {"sqlAllowLike", false}, {"sqlAllowGroupByClause", false}, {"maxSpatialQueryCells", 12}, {"spatialMaxGeometryPointCount", 256}, {"sqlDisableQueryILOptimization", false}, {"sqlDisableFilterPlanOptimization", false} }; private static readonly QueryPartitionProvider queryPartitionProvider = new QueryPartitionProvider(DefaultQueryEngineConfiguration); private static readonly Documents.PartitionKeyDefinition partitionKeyDefinition = new Documents.PartitionKeyDefinition() { Paths = new Collection<string>() { "/pk" }, Kind = Documents.PartitionKind.Hash, Version = Documents.PartitionKeyDefinitionVersion.V2, }; [TestMethod] public void Serialization() { List<Input> inputs = new List<Input>(); int startLineNumber; int endLineNumber; //---------------------------------------------------------------- // Root Trace //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Root Trace With Datum //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTraceWithDatum; using (rootTraceWithDatum = TraceForBaselineTesting.GetRootTrace()) { rootTraceWithDatum.AddDatum("QueryMetrics", new QueryMetricsTraceDatum(MockQueryMetrics)); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace With Datum", rootTraceWithDatum, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Root Trace With One Child //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { using (ITrace childTrace1 = rootTrace.StartChild("Child1")) { } } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace With One Child", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Root Trace With One Child With Datum //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { using (ITrace childTrace1 = rootTrace.StartChild("Child1")) { childTrace1.AddDatum("QueryMetrics", new QueryMetricsTraceDatum(MockQueryMetrics)); } } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace With One Child With Datum", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Root Trace With Two Children //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { using (ITrace childTrace1 = rootTrace.StartChild("Child1")) { } using (ITrace childTrace2 = rootTrace.StartChild("Child2")) { } } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace With Two Children", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Root Trace With Two Children With Info //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { using (ITrace childTrace1 = rootTrace.StartChild("Child1")) { childTrace1.AddDatum("QueryMetrics", new QueryMetricsTraceDatum(MockQueryMetrics)); } using (ITrace childTrace2 = rootTrace.StartChild("Child2")) { childTrace2.AddDatum("QueryMetrics", new QueryMetricsTraceDatum(MockQueryMetrics)); } } endLineNumber = GetLineNumber(); inputs.Add(new Input("Root Trace With Two Children With Info", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Trace With Grandchidren //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { using (ITrace childTrace1 = rootTrace.StartChild( name: "Child1", component: TraceComponent.Unknown, level: TraceLevel.Info)) { using (ITrace child1Child1 = childTrace1.StartChild( name: "Child1Child1", component: TraceComponent.Unknown, level: TraceLevel.Info)) { } using (ITrace child1Child2 = childTrace1.StartChild( name: "Child1Child2", component: TraceComponent.Unknown, level: TraceLevel.Info)) { } } using (ITrace childTrace2 = rootTrace.StartChild( name: "Child2", component: TraceComponent.Unknown, level: TraceLevel.Info)) { using (ITrace child2Child1 = childTrace2.StartChild( name: "Child2Child1", component: TraceComponent.Unknown, level: TraceLevel.Info)) { } using (ITrace child2Child2 = childTrace2.StartChild( name: "Child2Child2", component: TraceComponent.Unknown, level: TraceLevel.Info)) { } using (ITrace child2Child3 = childTrace2.StartChild( name: "Child2Child3", component: TraceComponent.Unknown, level: TraceLevel.Info)) { } } } endLineNumber = GetLineNumber(); inputs.Add(new Input("Trace With Grandchildren", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- this.ExecuteTestSuite(inputs); } [TestMethod] public void TraceData() { List<Input> inputs = new List<Input>(); int startLineNumber; int endLineNumber; //---------------------------------------------------------------- // Point Operation Statistics //---------------------------------------------------------------- { { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { PointOperationStatisticsTraceDatum datum = new PointOperationStatisticsTraceDatum( activityId: Guid.Empty.ToString(), responseTimeUtc: new DateTime(2020, 1, 2, 3, 4, 5, 6), statusCode: System.Net.HttpStatusCode.OK, subStatusCode: Documents.SubStatusCodes.WriteForbidden, requestCharge: 4, errorMessage: null, method: HttpMethod.Post, requestUri: "http://localhost.com", requestSessionToken: nameof(PointOperationStatisticsTraceDatum.RequestSessionToken), responseSessionToken: nameof(PointOperationStatisticsTraceDatum.ResponseSessionToken)); rootTrace.AddDatum("Point Operation Statistics", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Point Operation Statistics", rootTrace, startLineNumber, endLineNumber)); } { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { PointOperationStatisticsTraceDatum datum = new PointOperationStatisticsTraceDatum( activityId: default, responseTimeUtc: default, statusCode: default, subStatusCode: default, requestCharge: default, errorMessage: default, method: default, requestUri: default, requestSessionToken: default, responseSessionToken: default); rootTrace.AddDatum("Point Operation Statistics Default", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Point Operation Statistics Default", rootTrace, startLineNumber, endLineNumber)); } } //---------------------------------------------------------------- //---------------------------------------------------------------- // Query Metrics //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { QueryMetricsTraceDatum datum = new QueryMetricsTraceDatum( new QueryMetrics( BackendMetricsTests.MockBackendMetrics, IndexUtilizationInfoTests.MockIndexUtilizationInfo, ClientSideMetricsTests.MockClientSideMetrics)); rootTrace.AddDatum("Query Metrics", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Query Metrics", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Client Side Request Stats //---------------------------------------------------------------- { { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { ClientSideRequestStatisticsTraceDatum datum = new ClientSideRequestStatisticsTraceDatum(DateTime.MinValue); Uri uri1 = new Uri("http://someUri1.com"); Uri uri2 = new Uri("http://someUri2.com"); datum.ContactedReplicas.Add(uri1); datum.ContactedReplicas.Add(uri2); ClientSideRequestStatisticsTraceDatum.AddressResolutionStatistics mockStatistics = new ClientSideRequestStatisticsTraceDatum.AddressResolutionStatistics( DateTime.MinValue, DateTime.MaxValue, "http://localhost.com"); datum.EndpointToAddressResolutionStatistics["asdf"] = mockStatistics; datum.EndpointToAddressResolutionStatistics["asdf2"] = mockStatistics; datum.FailedReplicas.Add(uri1); datum.FailedReplicas.Add(uri2); datum.RegionsContactedWithName.Add(("local", uri1)); datum.RegionsContactedWithName.Add(("local", uri2)); datum.RequestEndTimeUtc = DateTime.MaxValue; StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics( DateTime.MinValue, DateTime.MaxValue, new Documents.StoreResult( storeResponse: new StoreResponse(), exception: null, partitionKeyRangeId: 42.ToString(), lsn: 1337, quorumAckedLsn: 23, requestCharge: 3.14, currentReplicaSetSize: 4, currentWriteQuorum: 3, isValid: true, storePhysicalAddress: new Uri("http://storephysicaladdress.com"), globalCommittedLSN: 1234, numberOfReadRegions: 13, itemLSN: 15, sessionToken: new SimpleSessionToken(42), usingLocalLSN: true, activityId: Guid.Empty.ToString()), ResourceType.Document, OperationType.Query, uri1); datum.StoreResponseStatisticsList.Add(storeResponseStatistics); rootTrace.AddDatum("Client Side Request Stats", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Client Side Request Stats", rootTrace, startLineNumber, endLineNumber)); } { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { ClientSideRequestStatisticsTraceDatum datum = new ClientSideRequestStatisticsTraceDatum(DateTime.MinValue); datum.ContactedReplicas.Add(default); ClientSideRequestStatisticsTraceDatum.AddressResolutionStatistics mockStatistics = new ClientSideRequestStatisticsTraceDatum.AddressResolutionStatistics( default, default, targetEndpoint: "asdf"); datum.EndpointToAddressResolutionStatistics["asdf"] = default; datum.EndpointToAddressResolutionStatistics["asdf2"] = default; datum.FailedReplicas.Add(default); datum.RegionsContactedWithName.Add(default); datum.RequestEndTimeUtc = default; StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics( requestStartTime: default, requestResponseTime: default, new Documents.StoreResult( storeResponse: new StoreResponse(), exception: default, partitionKeyRangeId: default, lsn: default, quorumAckedLsn: default, requestCharge: default, currentReplicaSetSize: default, currentWriteQuorum: default, isValid: default, storePhysicalAddress: default, globalCommittedLSN: default, numberOfReadRegions: default, itemLSN: default, sessionToken: default, usingLocalLSN: default, activityId: default), resourceType: default, operationType: default, locationEndpoint: default); ; datum.StoreResponseStatisticsList.Add(storeResponseStatistics); rootTrace.AddDatum("Client Side Request Stats Default", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("Client Side Request Stats Default", rootTrace, startLineNumber, endLineNumber)); } } //---------------------------------------------------------------- //---------------------------------------------------------------- // CPU History //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { CpuHistoryTraceDatum datum = new CpuHistoryTraceDatum( new Documents.Rntbd.CpuLoadHistory( new ReadOnlyCollection<Documents.Rntbd.CpuLoad>( new List<Documents.Rntbd.CpuLoad>() { new Documents.Rntbd.CpuLoad(DateTime.MinValue, 42), new Documents.Rntbd.CpuLoad(DateTime.MinValue, 23), }), monitoringInterval: TimeSpan.MaxValue)); rootTrace.AddDatum("CPU History", datum); } endLineNumber = GetLineNumber(); inputs.Add(new Input("CPU History", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- this.ExecuteTestSuite(inputs); } [TestMethod] public async Task ScenariosAsync() { List<Input> inputs = new List<Input>(); int startLineNumber; int endLineNumber; //---------------------------------------------------------------- // ReadFeed //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); int numItems = 100; IDocumentContainer documentContainer = await CreateDocumentContainerAsync(numItems); CrossPartitionReadFeedAsyncEnumerator enumerator = CrossPartitionReadFeedAsyncEnumerator.Create( documentContainer, new CrossFeedRangeState<ReadFeedState>(ReadFeedCrossFeedRangeState.CreateFromBeginning().FeedRangeStates), new ReadFeedPaginationOptions(pageSizeHint: 10), cancellationToken: default); int numChildren = 1; // One extra since we need to read one past the last user page to get the null continuation. TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { while (await enumerator.MoveNextAsync(rootTrace)) { numChildren++; } } Assert.AreEqual(numChildren, rootTrace.Children.Count); endLineNumber = GetLineNumber(); inputs.Add(new Input("ReadFeed", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // ChangeFeed //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); int numItems = 100; IDocumentContainer documentContainer = await CreateDocumentContainerAsync(numItems); CrossPartitionChangeFeedAsyncEnumerator enumerator = CrossPartitionChangeFeedAsyncEnumerator.Create( documentContainer, new CrossFeedRangeState<ChangeFeedState>( ChangeFeedCrossFeedRangeState.CreateFromBeginning().FeedRangeStates), new ChangeFeedPaginationOptions( ChangeFeedMode.Incremental, pageSizeHint: int.MaxValue), cancellationToken: default); int numChildren = 0; TraceForBaselineTesting rootTrace; using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { while (await enumerator.MoveNextAsync(rootTrace)) { numChildren++; if (enumerator.Current.Result.Page is ChangeFeedNotModifiedPage) { break; } } } Assert.AreEqual(numChildren, rootTrace.Children.Count); endLineNumber = GetLineNumber(); inputs.Add(new Input("ChangeFeed", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- //---------------------------------------------------------------- // Query //---------------------------------------------------------------- { startLineNumber = GetLineNumber(); int numItems = 100; IDocumentContainer documentContainer = await CreateDocumentContainerAsync(numItems); IQueryPipelineStage pipelineStage = CreatePipeline(documentContainer, "SELECT * FROM c", pageSize: 10); TraceForBaselineTesting rootTrace; int numChildren = 1; // One extra since we need to read one past the last user page to get the null continuation. using (rootTrace = TraceForBaselineTesting.GetRootTrace()) { while (await pipelineStage.MoveNextAsync(rootTrace)) { numChildren++; } } Assert.AreEqual(numChildren, rootTrace.Children.Count); endLineNumber = GetLineNumber(); inputs.Add(new Input("Query", rootTrace, startLineNumber, endLineNumber)); } //---------------------------------------------------------------- this.ExecuteTestSuite(inputs); } public override Output ExecuteTest(Input input) { CultureInfo originalCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("th-TH", false); try { string text = TraceWriter.TraceToText(input.Trace); string json = TraceWriter.TraceToJson(input.Trace); return new Output(text, JToken.Parse(json).ToString(Newtonsoft.Json.Formatting.Indented)); } finally { CultureInfo.CurrentCulture = originalCulture; } } private static async Task<IDocumentContainer> CreateDocumentContainerAsync( int numItems, FlakyDocumentContainer.FailureConfigs failureConfigs = default) { Documents.PartitionKeyDefinition partitionKeyDefinition = new Documents.PartitionKeyDefinition() { Paths = new System.Collections.ObjectModel.Collection<string>() { "/pk" }, Kind = Documents.PartitionKind.Hash, Version = Documents.PartitionKeyDefinitionVersion.V2, }; IMonadicDocumentContainer monadicDocumentContainer = new InMemoryContainer(partitionKeyDefinition); if (failureConfigs != null) { monadicDocumentContainer = new FlakyDocumentContainer(monadicDocumentContainer, failureConfigs); } DocumentContainer documentContainer = new DocumentContainer(monadicDocumentContainer); for (int i = 0; i < 3; i++) { IReadOnlyList<FeedRangeInternal> ranges = await documentContainer.GetFeedRangesAsync( trace: NoOpTrace.Singleton, cancellationToken: default); foreach (FeedRangeInternal range in ranges) { await documentContainer.SplitAsync(range, cancellationToken: default); } await documentContainer.RefreshProviderAsync(NoOpTrace.Singleton, cancellationToken: default); } for (int i = 0; i < numItems; i++) { // Insert an item CosmosObject item = CosmosObject.Parse($"{{\"pk\" : {i} }}"); while (true) { TryCatch<Record> monadicCreateRecord = await documentContainer.MonadicCreateItemAsync(item, cancellationToken: default); if (monadicCreateRecord.Succeeded) { break; } } } return documentContainer; } private static IQueryPipelineStage CreatePipeline(IDocumentContainer documentContainer, string query, int pageSize = 10, CosmosElement state = null) { TryCatch<IQueryPipelineStage> tryCreatePipeline = PipelineFactory.MonadicCreate( ExecutionEnvironment.Compute, documentContainer, new SqlQuerySpec(query), new List<FeedRangeEpk>() { FeedRangeEpk.FullRange }, partitionKey: null, GetQueryPlan(query), new QueryPaginationOptions(pageSizeHint: 10), maxConcurrency: 10, requestCancellationToken: default, requestContinuationToken: state); tryCreatePipeline.ThrowIfFailed(); return tryCreatePipeline.Result; } private static QueryInfo GetQueryPlan(string query) { TryCatch<PartitionedQueryExecutionInfoInternal> info = queryPartitionProvider.TryGetPartitionedQueryExecutionInfoInternal( new SqlQuerySpec(query), partitionKeyDefinition, requireFormattableOrderByQuery: true, isContinuationExpected: false, allowNonValueAggregateQuery: true, hasLogicalPartitionKey: false, allowDCount: true); info.ThrowIfFailed(); return info.Result.QueryInfo; } private static int GetLineNumber([CallerLineNumber] int lineNumber = 0) { return lineNumber; } public sealed class Input : BaselineTestInput { private static readonly string[] sourceCode = File.ReadAllLines($"Tracing\\{nameof(TraceWriterBaselineTests)}.cs"); internal Input(string description, ITrace trace, int startLineNumber, int endLineNumber) : base(description) { this.Trace = trace ?? throw new ArgumentNullException(nameof(trace)); this.StartLineNumber = startLineNumber; this.EndLineNumber = endLineNumber; } internal ITrace Trace { get; } public int StartLineNumber { get; } public int EndLineNumber { get; } public override void SerializeAsXml(XmlWriter xmlWriter) { xmlWriter.WriteElementString(nameof(this.Description), this.Description); xmlWriter.WriteStartElement("Setup"); ArraySegment<string> codeSnippet = new ArraySegment<string>( sourceCode, this.StartLineNumber, this.EndLineNumber - this.StartLineNumber - 1); string setup; try { setup = Environment.NewLine + string .Join( Environment.NewLine, codeSnippet .Select(x => x != string.Empty ? x.Substring(" ".Length) : string.Empty)) + Environment.NewLine; } catch(Exception ex) { throw ex; } xmlWriter.WriteCData(setup ?? "asdf"); xmlWriter.WriteEndElement(); } } public sealed class Output : BaselineTestOutput { public Output(string text, string json) { this.Text = text ?? throw new ArgumentNullException(nameof(text)); this.Json = json ?? throw new ArgumentNullException(nameof(json)); } public string Text { get; } public string Json { get; } public override void SerializeAsXml(XmlWriter xmlWriter) { xmlWriter.WriteStartElement(nameof(this.Text)); xmlWriter.WriteCData(this.Text); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement(nameof(this.Json)); xmlWriter.WriteCData(this.Json); xmlWriter.WriteEndElement(); } } private sealed class TraceForBaselineTesting : ITrace { private readonly Dictionary<string, object> data; private readonly List<TraceForBaselineTesting> children; public TraceForBaselineTesting( string name, TraceLevel level, TraceComponent component, TraceForBaselineTesting parent) { this.Name = name ?? throw new ArgumentNullException(nameof(name)); this.Level = level; this.Component = component; this.Parent = parent; this.children = new List<TraceForBaselineTesting>(); this.data = new Dictionary<string, object>(); } public string Name { get; } public Guid Id => Guid.Empty; public CallerInfo CallerInfo => new CallerInfo("MemberName", "FilePath", 42); public DateTime StartTime => DateTime.MinValue; public TimeSpan Duration => TimeSpan.Zero; public TraceLevel Level { get; } public TraceComponent Component { get; } public ITrace Parent { get; } public IReadOnlyList<ITrace> Children => this.children; public IReadOnlyDictionary<string, object> Data => this.data; public void AddDatum(string key, TraceDatum traceDatum) { this.data[key] = traceDatum; } public void AddDatum(string key, object value) { this.data[key] = value; } public void Dispose() { } public ITrace StartChild(string name, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { return this.StartChild(name, TraceComponent.Unknown, TraceLevel.Info, memberName, sourceFilePath, sourceLineNumber); } public ITrace StartChild(string name, TraceComponent component, TraceLevel level, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { TraceForBaselineTesting child = new TraceForBaselineTesting(name, level, component, parent: this); this.children.Add(child); return child; } public static TraceForBaselineTesting GetRootTrace() { return new TraceForBaselineTesting("Trace For Baseline Testing", TraceLevel.Info, TraceComponent.Unknown, parent: null); } } } }
44.753231
226
0.483918
[ "MIT" ]
ccurrens/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/Tracing/TraceWriterBaselineTests.cs
38,087
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace TwittSquare.ASP.Model { [Table("followings")] public class Following { [Column("user_id",Order =0)] public long UserId { get; set; } [Column("following_id",Order =1)] public long FollowingId { get; set; } [Column("cash_at")] public DateTime CashAt { get; set; } public Following() { } public Following(long userId,long followingId,DateTime cashAt) { UserId = userId; FollowingId = followingId; CashAt = cashAt; } internal static void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Following>().HasKey(x => new { x.UserId,x.FollowingId }); } } [Table("following_tasks")] public class FollowingTask { [Key] [Column("user_id")] public long UserId { get; set; } [Column("take_all_at")] public DateTime TakeAllAt { get; set; } public FollowingTask() { } public FollowingTask(long userId,DateTime takeAllAt) { UserId = userId; TakeAllAt = takeAllAt; } } }
25.388889
89
0.615609
[ "MIT" ]
MeilCli/TwittSquare
src/TwittSquare.ASP/Model/Following.cs
1,373
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Com.Ctrip.Soa.Caravan.Metric.Null { public class NullEventMetricReporter : IMetricReporter<IEventMetric> { public static NullEventMetricReporter Instance { get; private set; } static NullEventMetricReporter() { Instance = new NullEventMetricReporter(); } private NullEventMetricReporter() { } public void Report(IEventMetric metric) { } } }
22.083333
76
0.662264
[ "Apache-2.0" ]
ctripcorp/caravan.net
Src/Caravan.Metric/Null/NullEventMetricReporter.cs
532
C#
using System; namespace LoopTask4_4 { class Program { static void Main(string[] args) { Console.WriteLine("Ohjelma simuloi kolikon heittoa!"); Console.Write("Kuinka monta kertaa kolikkoa heitetään? "); int counter = int.Parse(Console.ReadLine()); int heads = 0; int tails = 0; Random rnd = new Random(); int rndNumber; for (int i = 0; i < counter; i++) { rndNumber = rnd.Next(2); if (rndNumber == 0) tails++; else heads++; } Console.WriteLine($"Rahaa on heitetty {rndNumber} kertaa."); Console.WriteLine($"Klaavoja tuli {tails} ja kruunuja {heads}."); } } }
27.633333
77
0.472859
[ "MIT" ]
e310905-Saimia/programming-basic-2018
loop-tasks/LoopTask4-4/LoopTask4-4/Program.cs
833
C#
namespace RxBim.Di { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; /// <summary> /// Резолвер сборок /// </summary> public class AssemblyResolver : IDisposable { private readonly IEnumerable<Dll> _dlls; /// <summary> /// ctor /// </summary> /// <param name="assembly">assembly</param> public AssemblyResolver(Assembly assembly) { var dir = Path.GetDirectoryName(assembly.Location); _dlls = GetDlls(dir, SearchOption.TopDirectoryOnly); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve; } /// <inheritdoc /> public void Dispose() { AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve; } private Assembly CurrentDomainOnAssemblyResolve(object o, ResolveEventArgs args) { var dll = _dlls.FirstOrDefault(f => f.IsResolve(args.Name)); if (dll != null) { try { return dll.LoadAssembly(); } catch { // ignored } } return null; } private IEnumerable<Dll> GetDlls(string dllFolder, SearchOption mode) { foreach (var dllFile in Directory.EnumerateFiles(dllFolder, "*.dll", mode)) { yield return new Dll(dllFile); } } private class Dll { public Dll(string dllFile) { DllFile = dllFile; DllName = Path.GetFileNameWithoutExtension(dllFile); } public string DllFile { get; } public string DllName { get; } public bool IsResolve(string dllRequest) { return dllRequest.StartsWith($"{DllName},", StringComparison.OrdinalIgnoreCase); } public Assembly LoadAssembly() { return Assembly.LoadFile(DllFile); } } } }
26.73494
96
0.515998
[ "MIT" ]
AlexNik235/RxBim
src/RxBim.Di/AssemblyResolver.cs
2,235
C#
// Generated on 12/11/2014 19:01:22 using System; using System.Collections.Generic; using System.Linq; using BlueSheep.Common.Protocol.Types; using BlueSheep.Common.IO; using BlueSheep.Engine.Types; namespace BlueSheep.Common.Protocol.Messages { public class CharacterReplayWithRemodelRequestMessage : CharacterReplayRequestMessage { public new const uint ID =6551; public override uint ProtocolID { get { return ID; } } public Types.RemodelingInformation remodel; public CharacterReplayWithRemodelRequestMessage() { } public CharacterReplayWithRemodelRequestMessage(int characterId, Types.RemodelingInformation remodel) : base(characterId) { this.remodel = remodel; } public override void Serialize(BigEndianWriter writer) { base.Serialize(writer); remodel.Serialize(writer); } public override void Deserialize(BigEndianReader reader) { base.Deserialize(reader); remodel = new Types.RemodelingInformation(); remodel.Deserialize(reader); } } }
22.392857
109
0.617225
[ "MIT" ]
Sadikk/BlueSheep
BlueSheep/Common/Protocol/messages/game/character/choice/CharacterReplayWithRemodelRequestMessage.cs
1,254
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Sharpen.Engine.Analysis; using Sharpen.Engine.Extensions; namespace Sharpen.Engine.SharpenSuggestions.CSharp60.NameofExpressions { internal sealed class UseNameofExpressionForThrowingArgumentExceptions : ISharpenSuggestion, ISingleSyntaxTreeAnalyzer { private class KnownArgumentExceptionTypeInfo : KnownTypeInfo { public string ParameterName { get; } public KnownArgumentExceptionTypeInfo(string typeName, string typeNamespace, string parameterName) :base(typeName, typeNamespace) { ParameterName = parameterName; } } private UseNameofExpressionForThrowingArgumentExceptions() { } public string MinimumLanguageVersion { get; } = CSharpLanguageVersions.CSharp60; public ICSharpFeature LanguageFeature { get; } = CSharpFeatures.NameofExpressions.Instance; public string FriendlyName { get; } = "Use nameof expression for throwing argument exceptions"; public SharpenSuggestionType SuggestionType { get; } = SharpenSuggestionType.Recommendation; public static readonly UseNameofExpressionForThrowingArgumentExceptions Instance = new UseNameofExpressionForThrowingArgumentExceptions(); private static readonly KnownArgumentExceptionTypeInfo[] KnownArgumentExceptions = { new KnownArgumentExceptionTypeInfo("ArgumentNullException", "System", "paramName"), new KnownArgumentExceptionTypeInfo("ArgumentException", "System", "paramName"), new KnownArgumentExceptionTypeInfo("ArgumentOutOfRangeException", "System", "paramName"), new KnownArgumentExceptionTypeInfo("InvalidEnumArgumentException", "System.ComponentModel", "argumentName") // TODO-SETTINGS: Allow users to define their own argument exceptions. }; public IEnumerable<AnalysisResult> Analyze(SyntaxTree syntaxTree, SemanticModel semanticModel, SingleSyntaxTreeAnalysisContext analysisContext) { return syntaxTree.GetRoot() .DescendantNodes() .OfType<ThrowStatementSyntax>() .Select(@throw => new { ThrowStatement = @throw, ParameterNameArgument = GetParameterNameArgumentIfThrowThrowsArgumentExceptionWithProperParameterName(@throw) }) .Where(throwWithParameterName => throwWithParameterName.ParameterNameArgument != null) .Select(@throw => new AnalysisResult ( this, analysisContext, syntaxTree.FilePath, @throw.ParameterNameArgument.GetFirstToken(), @throw.ThrowStatement.Expression )); ArgumentSyntax GetParameterNameArgumentIfThrowThrowsArgumentExceptionWithProperParameterName(ThrowStatementSyntax throwStatementSyntax) { // Let's first do fast checks that quickly and cheaply eliminate obvious non-candidates. // We want to use the semantic model only if we are sure that we have candidates that are // very likely throw statements that we are looking for. if (!(throwStatementSyntax.Expression is ObjectCreationExpressionSyntax objectCreationExpression)) return null; if (!KnownArgumentExceptions.Select(exception => exception.TypeName).Any(name => objectCreationExpression.Type.ToString().EndsWith(name, StringComparison.Ordinal))) return null; var argumentsThatCouldBeParameterNames = objectCreationExpression.ArgumentList.Arguments .Where(argument => argument.Expression.IsKind(SyntaxKind.StringLiteralExpression) && ((LiteralExpressionSyntax) argument.Expression).Token.ValueText.CouldBePotentialParameterName() ) .ToList(); if (!argumentsThatCouldBeParameterNames.Any()) return null; var parameterNamesAvailableInScopeOfThrow = throwStatementSyntax.GetParameterNamesVisibleInScope(); var argumentsThatAreParameterNames = argumentsThatCouldBeParameterNames .Where(argument => parameterNamesAvailableInScopeOfThrow.Contains(((LiteralExpressionSyntax) argument.Expression).Token.ValueText)) .ToList(); if (!argumentsThatAreParameterNames.Any()) return null; // If we reach this point it means that we have a throw statement that has a constructor call // that creates an exception whose name pretty much surely fits the name of the argument exceptions and whose // constructor argument, any or more of them, are strings that appear in the surrounding parameters names. // Which means we are in a real case most likely 99% percent sure that we have a fit. Cool :-) // Still, we have to check for those 1% since we could have a something like this: // throw new AlmostArgumentNullException("A message, although the first parameter should be parameter name ;-)", "parameterName"); // For that check, we need semantic analysis. var constructorSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(objectCreationExpression).Symbol; if (constructorSymbol == null) return null; // 1. Check that the created object is 100% one of the argument exceptions. var argumentException = KnownArgumentExceptions .FirstOrDefault(exception => exception.RepresentsType(constructorSymbol.ContainingType)); if (argumentException == null) return null; // 2. Check that the constructor arguments that are strings with enclosing parameter names // are passed as proper constructor parameters. return argumentsThatAreParameterNames.FirstOrDefault(argument => GetParameterNameBehindTheArgument(argument) == argumentException.ParameterName); string GetParameterNameBehindTheArgument(ArgumentSyntax argument) { // If we are lucky and have a named argument ;-) if (argument.NameColon != null) { var parameterNameText = argument.NameColon.Name?.Identifier.ValueText; return parameterNameText ?? string.Empty; } // We were nor lucky. We have a normal positional argument in the list of arguments. var index = ((ArgumentListSyntax)argument.Parent).Arguments.IndexOf(argument); return index < 0 || index >= constructorSymbol.Parameters.Length ? string.Empty : constructorSymbol.Parameters[index].Name; } } } } }
54.283582
151
0.652048
[ "MIT" ]
ironcev/Sharpen
src/Sharpen.Engine/SharpenSuggestions/CSharp60/NameofExpressions/UseNameofExpressionForThrowingArgumentExceptions.cs
7,276
C#
using R5.FFDB.Components.CoreData.Dynamic.Rosters; using R5.FFDB.Components.CoreData.Static.Players.Add.Sources.V1.Models; using R5.FFDB.Core.Entities; using R5.FFDB.Core.Models; using System.Threading.Tasks; namespace R5.FFDB.Components.CoreData.Static.Players.Add.Sources.V1.Mappers { public interface IToCoreMapper : IAsyncMapper<PlayerAddVersioned, PlayerAdd, string> { } public class ToCoreMapper : IToCoreMapper { private IRosterCache _rosterCache { get; } public ToCoreMapper(IRosterCache rosterCache) { _rosterCache = rosterCache; } public async Task<PlayerAdd> MapAsync(PlayerAddVersioned versioned, string nflId) { int? number = null; Position? position = null; RosterStatus? status = null; var playerData = await _rosterCache.GetPlayerDataAsync(nflId); if (playerData.HasValue) { number = playerData.Value.number; position = playerData.Value.position; status = playerData.Value.status; } return new PlayerAdd { NflId = versioned.NflId, EsbId = versioned.EsbId, GsisId = versioned.EsbId, FirstName = versioned.FirstName, LastName = versioned.LastName, Height = versioned.Height, Weight = versioned.Weight, DateOfBirth = versioned.DateOfBirth, College = versioned.College, Number = number, Position = position, Status = status }; } } }
26.211538
89
0.727073
[ "MIT" ]
rushfive/FFDB
Engine/R5.FFDB.Components/CoreData/Static/Players/Add/Sources/V1/Mappers/ToCoreMapper.cs
1,365
C#
using UnityEditor; using UnityEngine; using _Scripts.Enums; namespace _Scripts.Editor { [CustomPropertyDrawer(typeof(EnumFlagsAttribute))] public class EnumFlagsAttributeDrawer : PropertyDrawer { public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label) { _property.intValue = EditorGUI.MaskField( _position, _label, _property.intValue, _property.enumNames ); } } }
26.941176
115
0.720524
[ "MIT" ]
giomelo/SoftBelly
Assets/_Scripts/Editor/EnumFlagsAtribute.cs
460
C#
using System; using System.Collections.Generic; using System.Text; namespace DemoApp.Model { public class MasterPageItem { public string Title { get; set; } public string IconSource { get; set; } public Type TargetType { get; set; } } }
17.3125
46
0.642599
[ "MIT" ]
tony-repo/Xamarin.Forms-App
DemoApp/DemoApp/Model/MasterPageItem.cs
279
C#
using Ams.Core; using System; using System.Collections.Generic; using System.Web.Http; namespace hippos_api.Controllers { /// <summary> /// 菜单控制器 /// </summary> public class MenuController : ControllerBase { /// <summary> /// 菜单列表 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public IHttpActionResult GetMenuList() { //全部菜单 var menus = Db.Context(APP.DB_DEFAULT_CONN_NAME).Sql(string.Format(@"select * from dbo.menutab where 1=1 order by parentid,sort")).QueryMany<Menu>(); //全部meta var metas = Db.Context(APP.DB_DEFAULT_CONN_NAME).Sql(string.Format(@"select * from dbo.menumetatab")).QueryMany<Meta>(); //待返回菜单数据格式 List<Menu> menulist = new List<Menu>(); menulist = CommonMethod.BuildMenuMeta(menus, metas); menulist = CommonMethod.BuildMenuChildren(menus); return Success("success", menulist); } /// <summary> /// 根据角色获取菜单 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public IHttpActionResult GetMenuByRole(M m) { try { if (m != null && m.roles.Count > 0) { string role = m.roles[0]; //全部菜单 var menus = Db.Context(APP.DB_DEFAULT_CONN_NAME).Sql(string.Format(@"select * from dbo.menutab where isnull(isclosed,0) =0 order by parentid,sort")).QueryMany<Menu>(); //全部meta var metas = Db.Context(APP.DB_DEFAULT_CONN_NAME).Sql(string.Format(@"select * from dbo.menumetatab")).QueryMany<Meta>(); //待返回菜单数据格式 List<Menu> menulist = new List<Menu>(); menulist = CommonMethod.BuildMenuMeta(menus, metas); menulist = CommonMethod.BuildMenuChildren(menus); return Success("success", menulist); } else { return Error("未能获取到用户角色!"); } } catch (Exception e) { return Exception(e.Message); } } public class M { public List<string> roles; } } }
32.373333
187
0.50659
[ "MIT" ]
SkyGrass/hippos_api_vm
hippos_api/Controllers/MenuController.cs
2,542
C#
using System; using System.Collections.Generic; using System.Linq; namespace FilesAPI.ViewModels { public class FileDetailsViewModels { public string Id { get; set; } public string HashId { get; set; } public string Name { get; set; } public long Size { get; set; } public string AddedBy { get; set; } public string Description { get; set; } public IEnumerable<string> Tags { get; set; } = Enumerable.Empty<string>(); public string ContentType { get; set; } public int NumberOfDownloads { get; set; } = 0; public DateTime AddedDate { get; set; } public DateTime LastModified { get; set; } } }
29.47619
77
0.696284
[ "MIT" ]
SitholeWB/FilesAPI
FilesAPI/ViewModels/FileDetailsViewModels.cs
621
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace osuTools.Collections { /// <summary> /// 线程安全的列表 /// </summary> /// <typeparam name="T">元素的类型</typeparam> public class ConcurrentList<T>:IList<T> { class ConcurrentListEnumerator:IEnumerator<T> { private readonly ConcurrentList<T> _innerList; private int _cur = -1; public ConcurrentListEnumerator(ConcurrentList<T> list) { _innerList = list; } public bool MoveNext() => ++_cur > _innerList.Count; public void Reset() => _cur = -1; public T Current => _cur == -1 ? throw new InvalidOperationException() : _innerList[_cur]; object IEnumerator.Current => Current; public void Dispose() { } } private T[] _arr; private int _len, _capacity; private readonly object _lockObj = new object(); void EnsureCapacity(int size, bool forced) { lock (_lockObj) { int extentTo = forced ? size : size + _len; if (forced || size + _len > _capacity) { int newCapacity; T[] oldArr = _arr; T[] newArr = new T[newCapacity = forced ? size : _capacity == 0 ? 4 : _capacity * 2]; Array.Copy(oldArr, newArr, _len); _arr = newArr; _capacity = newCapacity; } } } /// <summary> /// 初始化一个ConcurrentList /// </summary> public ConcurrentList() : this(0) { _capacity = 0; } /// <summary> /// 使用指定的初始容量初始化一个ConcurrentList /// </summary> /// <param name="size"></param> public ConcurrentList(int size) { lock (_lockObj) { _arr = new T[size]; _capacity = 0; } } /// <summary> /// 使用指定的<seealso cref="IEnumerable{T}"/>填充ConcurrentList /// </summary> /// <param name="collection"></param> public ConcurrentList(IEnumerable<T> collection) { lock (_lockObj) { if (collection is null) throw new ArgumentNullException(nameof(collection)); var c = collection as T[] ?? collection.ToArray(); _arr = new T[c.Length]; Array.Copy(c.ToArray(), _arr, c.Length); _capacity = c.Length; } } /// <inheritdoc/> public IEnumerator<T> GetEnumerator() => new ConcurrentListEnumerator(this); IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <inheritdoc/> public void Add(T item) { lock (_lockObj) { EnsureCapacity(_len + 1,false); _arr[_len++] = item; } } /// <inheritdoc/> public void Clear() { lock (_lockObj) { _arr = new T[_len]; _len = 0; } } /// <inheritdoc/> public bool Contains(T item) { lock (_lockObj) { IEqualityComparer comparer = EqualityComparer<T>.Default; if (item is IEqualityComparer equalityComparer) { comparer = equalityComparer; } foreach (var obj in _arr) { if (comparer.Equals(obj, item)) return true; } return false; } } int IndexConverter(int oriIndex) { if (oriIndex < 0) { if (_arr.Length - oriIndex < 0) { throw new IndexOutOfRangeException(); } return _arr.Length - oriIndex; } return oriIndex > _arr.Length ? throw new IndexOutOfRangeException() : oriIndex; } /// <inheritdoc/> public void CopyTo(T[] array, int arrayIndex) { lock (_lockObj) { IndexConverter(arrayIndex); if (_len - arrayIndex < 0) throw new IndexOutOfRangeException(); var objs = _arr.Skip(arrayIndex).Take(_len - arrayIndex).ToArray(); Array.Copy(objs, array, _len - arrayIndex); } } /// <inheritdoc/> public bool Remove(T item) { IEqualityComparer comparer = EqualityComparer<T>.Default; if (item is IEqualityComparer equalityComparer) { comparer = equalityComparer; } int delIndex = -1; for(int i = 0; i<_len;i++) { if (comparer.Equals(_arr[i], item)) { delIndex = i; } } if (delIndex == -1) { return false; } RemoveAt(delIndex); return true; } /// <inheritdoc/> public int Count => _len; /// <inheritdoc/> public bool IsReadOnly => false; /// <inheritdoc/> public int IndexOf(T item) { lock (_lockObj) { IEqualityComparer comparer = EqualityComparer<T>.Default; if (item is IEqualityComparer equalityComparer) { comparer = equalityComparer; } for (int i = 0; i < _len; i++) { if (comparer.Equals(_arr[i], item)) { return i; } } return -1; } } /// <inheritdoc/> public void Insert(int index, T item) { lock (_lockObj) { int insertIndex = index; if (insertIndex != _arr.Length - 1) { EnsureCapacity(_len + 2, false); Array.Copy(_arr, insertIndex, _arr, insertIndex + 1, _len - insertIndex); _arr[insertIndex] = item; _len++; } else { Add(item); } } } /// <inheritdoc/> public void RemoveAt(int index) { int delIndex = IndexConverter(index); _arr[delIndex] = default; int startIndex = delIndex + 1; if (delIndex != _arr.Length - 1) { Array.Copy(_arr, startIndex, _arr, delIndex, _arr.Length - delIndex - 1); } _arr[IndexConverter(-1)] = default; _len--; } ///<inheritdoc/>> public T this[int index] { get { lock (_lockObj) { return _arr[IndexConverter(index)]; } } set { lock (_lockObj) { _arr[IndexConverter(index)] = value; } } } } }
28.675472
105
0.425714
[ "MIT" ]
Someone999/OsuTools
osuTools/Collections/ConcurrentList.cs
7,677
C#
using System; using UIKit; using iFactr.UI; namespace iFactr.Touch { public class PlatformDefaults : IPlatformDefaults { public double LargeHorizontalSpacing { get { return 10; } } public double LeftMargin { get { return 15; } } public double RightMargin { get { return 15; } } public double SmallHorizontalSpacing { get { return 4; } } public double BottomMargin { get { return 4; } } public double LargeVerticalSpacing { get { return 10; } } public double SmallVerticalSpacing { get { return 4; } } public double TopMargin { get { return 4; } } public double CellHeight { get { return 44; } } public Font ButtonFont { get { return LabelFont; } } public Font DateTimePickerFont { get { return UIFont.SystemFontOfSize(18).ToFont(); } } public Font HeaderFont { get { return LabelFont; } } public Font LabelFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.PreferredBody : UIFont.BoldSystemFontOfSize(18)).ToFont(); } } public Font MessageBodyFont { get { return SmallFont + 2; } } public Font MessageTitleFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.FromName("HelveticaNeue-Medium", 17) : UIFont.BoldSystemFontOfSize(18)).ToFont(); } } public Font SectionHeaderFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.SystemFontOfSize(13) : UIFont.BoldSystemFontOfSize(17)).ToFont(); } } public Font SectionFooterFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.SystemFontOfSize(13) : UIFont.BoldSystemFontOfSize(17)).ToFont(); } } public Font SelectListFont { get { return UIFont.SystemFontOfSize(18).ToFont(); } } public Font SmallFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.PreferredFootnote : UIFont.SystemFontOfSize(14)).ToFont(); } } public Font TabFont { get { return (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) ? UIFont.SystemFontOfSize(10) : UIFont.BoldSystemFontOfSize(10)).ToFont(); } } public Font TextBoxFont { get { return UIFont.SystemFontOfSize(17).ToFont(); } } public Font ValueFont { get { return LabelFont; } } } }
23.699187
166
0.537907
[ "MIT" ]
BenButzer/iFactr-iOS
iFactr.Touch/MonoView/PlatformDefaults.cs
2,917
C#
namespace BizHawk.Client.MultiHawk { 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() { this.components = new System.ComponentModel.Container(); this.MainformMenu = new MenuStripEx(); this.FileSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.NewSessionMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenSessionMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.SaveSessionMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.SaveSessionAsMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RecentSessionSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.OpenRomMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RecentRomSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.RebootCoresMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.ExitMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ViewSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this._1xMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this._2xMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this._3xMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this._4xMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MovieSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.RecordMovieMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.PlayMovieMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.StopMovieMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RestartMovieMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RecentMovieSubMenu = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.ToggleReadonlyMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.configToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.controllerConfigToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.hotkeyConfigToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.saveConfigToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.WorkspacePanel = new System.Windows.Forms.Panel(); this.MainStatusBar = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.FameStatusBarLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.PlayRecordStatusButton = new System.Windows.Forms.ToolStripDropDownButton(); this.StatusBarMessageLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.RecordMovieContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.PlayMovieContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.LoadLastMovieContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.StopMovieContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RestartMovieContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MainformMenu.SuspendLayout(); this.WorkspacePanel.SuspendLayout(); this.MainStatusBar.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // MainformMenu // this.MainformMenu.ClickThrough = true; this.MainformMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.FileSubMenu, this.ViewSubMenu, this.MovieSubMenu, this.configToolStripMenuItem}); this.MainformMenu.Location = new System.Drawing.Point(0, 0); this.MainformMenu.Name = "MainformMenu"; this.MainformMenu.Size = new System.Drawing.Size(655, 24); this.MainformMenu.TabIndex = 0; this.MainformMenu.Text = "menuStrip1"; // // FileSubMenu // this.FileSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.NewSessionMenuItem, this.OpenSessionMenuItem, this.SaveSessionMenuItem, this.SaveSessionAsMenuItem, this.RecentSessionSubMenu, this.toolStripSeparator7, this.OpenRomMenuItem, this.RecentRomSubMenu, this.toolStripSeparator5, this.RebootCoresMenuItem, this.toolStripSeparator3, this.ExitMenuItem}); this.FileSubMenu.Name = "FileSubMenu"; this.FileSubMenu.Size = new System.Drawing.Size(37, 20); this.FileSubMenu.Text = "&File"; this.FileSubMenu.DropDownOpened += new System.EventHandler(this.FileSubMenu_DropDownOpened); // // NewSessionMenuItem // this.NewSessionMenuItem.Name = "NewSessionMenuItem"; this.NewSessionMenuItem.Size = new System.Drawing.Size(165, 22); this.NewSessionMenuItem.Text = "&New Session"; this.NewSessionMenuItem.Click += new System.EventHandler(this.NewSessionMenuItem_Click); // // OpenSessionMenuItem // this.OpenSessionMenuItem.Name = "OpenSessionMenuItem"; this.OpenSessionMenuItem.Size = new System.Drawing.Size(165, 22); this.OpenSessionMenuItem.Text = "&Open Session"; this.OpenSessionMenuItem.Click += new System.EventHandler(this.OpenSessionMenuItem_Click); // // SaveSessionMenuItem // this.SaveSessionMenuItem.Name = "SaveSessionMenuItem"; this.SaveSessionMenuItem.Size = new System.Drawing.Size(165, 22); this.SaveSessionMenuItem.Text = "&Save Session"; this.SaveSessionMenuItem.Click += new System.EventHandler(this.SaveSessionMenuItem_Click); // // SaveSessionAsMenuItem // this.SaveSessionAsMenuItem.Name = "SaveSessionAsMenuItem"; this.SaveSessionAsMenuItem.Size = new System.Drawing.Size(165, 22); this.SaveSessionAsMenuItem.Text = "Save Session &As..."; this.SaveSessionAsMenuItem.Click += new System.EventHandler(this.SaveSessionAsMenuItem_Click); // // RecentSessionSubMenu // this.RecentSessionSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator6}); this.RecentSessionSubMenu.Name = "RecentSessionSubMenu"; this.RecentSessionSubMenu.Size = new System.Drawing.Size(165, 22); this.RecentSessionSubMenu.Text = "Recent Session"; this.RecentSessionSubMenu.DropDownOpened += new System.EventHandler(this.RecentSessionSubMenu_DropDownOpened); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(57, 6); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(162, 6); // // OpenRomMenuItem // this.OpenRomMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.OpenFile; this.OpenRomMenuItem.Name = "OpenRomMenuItem"; this.OpenRomMenuItem.Size = new System.Drawing.Size(165, 22); this.OpenRomMenuItem.Text = "Open ROM"; this.OpenRomMenuItem.Click += new System.EventHandler(this.OpenRomMenuItem_Click); // // RecentRomSubMenu // this.RecentRomSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator1}); this.RecentRomSubMenu.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Recent; this.RecentRomSubMenu.Name = "RecentRomSubMenu"; this.RecentRomSubMenu.Size = new System.Drawing.Size(165, 22); this.RecentRomSubMenu.Text = "Recent"; this.RecentRomSubMenu.DropDownOpened += new System.EventHandler(this.RecentRomSubMenu_DropDownOpened); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(57, 6); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(162, 6); // // RebootCoresMenuItem // this.RebootCoresMenuItem.Name = "RebootCoresMenuItem"; this.RebootCoresMenuItem.Size = new System.Drawing.Size(165, 22); this.RebootCoresMenuItem.Text = "Reboot Cores"; this.RebootCoresMenuItem.Click += new System.EventHandler(this.RebootCoresMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(162, 6); // // ExitMenuItem // this.ExitMenuItem.Name = "ExitMenuItem"; this.ExitMenuItem.ShortcutKeyDisplayString = "Alt+F4"; this.ExitMenuItem.Size = new System.Drawing.Size(165, 22); this.ExitMenuItem.Text = "E&xit"; this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click); // // ViewSubMenu // this.ViewSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this._1xMenuItem, this._2xMenuItem, this._3xMenuItem, this._4xMenuItem}); this.ViewSubMenu.Enabled = false; this.ViewSubMenu.Name = "ViewSubMenu"; this.ViewSubMenu.Size = new System.Drawing.Size(44, 20); this.ViewSubMenu.Text = "&View"; this.ViewSubMenu.DropDownOpened += new System.EventHandler(this.ViewSubMenu_DropDownOpened); // // _1xMenuItem // this._1xMenuItem.Name = "_1xMenuItem"; this._1xMenuItem.Size = new System.Drawing.Size(85, 22); this._1xMenuItem.Text = "&1x"; this._1xMenuItem.Click += new System.EventHandler(this._1xMenuItem_Click); // // _2xMenuItem // this._2xMenuItem.Name = "_2xMenuItem"; this._2xMenuItem.Size = new System.Drawing.Size(85, 22); this._2xMenuItem.Text = "&2x"; this._2xMenuItem.Click += new System.EventHandler(this._2xMenuItem_Click); // // _3xMenuItem // this._3xMenuItem.Name = "_3xMenuItem"; this._3xMenuItem.Size = new System.Drawing.Size(85, 22); this._3xMenuItem.Text = "&3x"; this._3xMenuItem.Click += new System.EventHandler(this._3xMenuItem_Click); // // _4xMenuItem // this._4xMenuItem.Name = "_4xMenuItem"; this._4xMenuItem.Size = new System.Drawing.Size(85, 22); this._4xMenuItem.Text = "&4x"; this._4xMenuItem.Click += new System.EventHandler(this._4xMenuItem_Click); // // MovieSubMenu // this.MovieSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.RecordMovieMenuItem, this.PlayMovieMenuItem, this.StopMovieMenuItem, this.RestartMovieMenuItem, this.RecentMovieSubMenu, this.toolStripSeparator2, this.ToggleReadonlyMenuItem}); this.MovieSubMenu.Name = "MovieSubMenu"; this.MovieSubMenu.Size = new System.Drawing.Size(52, 20); this.MovieSubMenu.Text = "&Movie"; this.MovieSubMenu.DropDownOpened += new System.EventHandler(this.MovieSubMenu_DropDownOpened); // // RecordMovieMenuItem // this.RecordMovieMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.RecordHS; this.RecordMovieMenuItem.Name = "RecordMovieMenuItem"; this.RecordMovieMenuItem.Size = new System.Drawing.Size(168, 22); this.RecordMovieMenuItem.Text = "Record Movie"; this.RecordMovieMenuItem.Click += new System.EventHandler(this.RecordMovieMenuItem_Click); // // PlayMovieMenuItem // this.PlayMovieMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Play; this.PlayMovieMenuItem.Name = "PlayMovieMenuItem"; this.PlayMovieMenuItem.Size = new System.Drawing.Size(168, 22); this.PlayMovieMenuItem.Text = "Play Movie"; this.PlayMovieMenuItem.Click += new System.EventHandler(this.PlayMovieMenuItem_Click); // // StopMovieMenuItem // this.StopMovieMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Stop; this.StopMovieMenuItem.Name = "StopMovieMenuItem"; this.StopMovieMenuItem.Size = new System.Drawing.Size(168, 22); this.StopMovieMenuItem.Text = "&Stop Movie"; this.StopMovieMenuItem.Click += new System.EventHandler(this.StopMovieMenuItem_Click); // // RestartMovieMenuItem // this.RestartMovieMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.restart; this.RestartMovieMenuItem.Name = "RestartMovieMenuItem"; this.RestartMovieMenuItem.Size = new System.Drawing.Size(168, 22); this.RestartMovieMenuItem.Text = "Restart Movie"; this.RestartMovieMenuItem.Click += new System.EventHandler(this.RestartMovieMenuItem_Click); // // RecentMovieSubMenu // this.RecentMovieSubMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator8}); this.RecentMovieSubMenu.Name = "RecentMovieSubMenu"; this.RecentMovieSubMenu.Size = new System.Drawing.Size(168, 22); this.RecentMovieSubMenu.Text = "Recent"; this.RecentMovieSubMenu.DropDownOpened += new System.EventHandler(this.RecentMovieSubMenu_DropDownOpened); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(57, 6); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(165, 6); // // ToggleReadonlyMenuItem // this.ToggleReadonlyMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.ReadOnly; this.ToggleReadonlyMenuItem.Name = "ToggleReadonlyMenuItem"; this.ToggleReadonlyMenuItem.Size = new System.Drawing.Size(168, 22); this.ToggleReadonlyMenuItem.Text = "Toggle Read-only"; this.ToggleReadonlyMenuItem.Click += new System.EventHandler(this.ToggleReadonlyMenuItem_Click); // // configToolStripMenuItem // this.configToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.controllerConfigToolStripMenuItem, this.hotkeyConfigToolStripMenuItem, this.toolStripSeparator4, this.saveConfigToolStripMenuItem}); this.configToolStripMenuItem.Name = "configToolStripMenuItem"; this.configToolStripMenuItem.Size = new System.Drawing.Size(55, 20); this.configToolStripMenuItem.Text = "&Config"; // // controllerConfigToolStripMenuItem // this.controllerConfigToolStripMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.GameController; this.controllerConfigToolStripMenuItem.Name = "controllerConfigToolStripMenuItem"; this.controllerConfigToolStripMenuItem.Size = new System.Drawing.Size(166, 22); this.controllerConfigToolStripMenuItem.Text = "Controller Config"; this.controllerConfigToolStripMenuItem.Click += new System.EventHandler(this.controllerConfigToolStripMenuItem_Click); // // hotkeyConfigToolStripMenuItem // this.hotkeyConfigToolStripMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.HotKeys; this.hotkeyConfigToolStripMenuItem.Name = "hotkeyConfigToolStripMenuItem"; this.hotkeyConfigToolStripMenuItem.Size = new System.Drawing.Size(166, 22); this.hotkeyConfigToolStripMenuItem.Text = "Hotkey Config"; this.hotkeyConfigToolStripMenuItem.Click += new System.EventHandler(this.hotkeyConfigToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(163, 6); // // saveConfigToolStripMenuItem // this.saveConfigToolStripMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Save; this.saveConfigToolStripMenuItem.Name = "saveConfigToolStripMenuItem"; this.saveConfigToolStripMenuItem.Size = new System.Drawing.Size(166, 22); this.saveConfigToolStripMenuItem.Text = "Save Config"; this.saveConfigToolStripMenuItem.Click += new System.EventHandler(this.saveConfigToolStripMenuItem_Click); // // WorkspacePanel // this.WorkspacePanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.WorkspacePanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.WorkspacePanel.Controls.Add(this.MainStatusBar); this.WorkspacePanel.Location = new System.Drawing.Point(0, 25); this.WorkspacePanel.Name = "WorkspacePanel"; this.WorkspacePanel.Size = new System.Drawing.Size(655, 405); this.WorkspacePanel.TabIndex = 1; // // MainStatusBar // this.MainStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.FameStatusBarLabel, this.PlayRecordStatusButton, this.StatusBarMessageLabel}); this.MainStatusBar.Location = new System.Drawing.Point(0, 379); this.MainStatusBar.Name = "MainStatusBar"; this.MainStatusBar.Size = new System.Drawing.Size(651, 22); this.MainStatusBar.TabIndex = 0; this.MainStatusBar.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(46, 17); this.toolStripStatusLabel1.Text = "Frame: "; // // FameStatusBarLabel // this.FameStatusBarLabel.Name = "FameStatusBarLabel"; this.FameStatusBarLabel.Size = new System.Drawing.Size(13, 17); this.FameStatusBarLabel.Text = "0"; // // PlayRecordStatusButton // this.PlayRecordStatusButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.PlayRecordStatusButton.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Blank; this.PlayRecordStatusButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.PlayRecordStatusButton.Name = "PlayRecordStatusButton"; this.PlayRecordStatusButton.Size = new System.Drawing.Size(29, 20); this.PlayRecordStatusButton.Text = "No movie is active"; // // StatusBarMessageLabel // this.StatusBarMessageLabel.Name = "StatusBarMessageLabel"; this.StatusBarMessageLabel.Size = new System.Drawing.Size(35, 17); this.StatusBarMessageLabel.Text = "Hello"; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.RecordMovieContextMenuItem, this.PlayMovieContextMenuItem, this.RestartMovieContextMenuItem, this.StopMovieContextMenuItem, this.LoadLastMovieContextMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(161, 114); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // RecordMovieContextMenuItem // this.RecordMovieContextMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.RecordHS; this.RecordMovieContextMenuItem.Name = "RecordMovieContextMenuItem"; this.RecordMovieContextMenuItem.Size = new System.Drawing.Size(160, 22); this.RecordMovieContextMenuItem.Text = "Record Movie"; this.RecordMovieContextMenuItem.Click += new System.EventHandler(this.RecordMovieMenuItem_Click); // // PlayMovieContextMenuItem // this.PlayMovieContextMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Play; this.PlayMovieContextMenuItem.Name = "PlayMovieContextMenuItem"; this.PlayMovieContextMenuItem.Size = new System.Drawing.Size(160, 22); this.PlayMovieContextMenuItem.Text = "Play Movie"; this.PlayMovieContextMenuItem.Click += new System.EventHandler(this.PlayMovieMenuItem_Click); // // LoadLastMovieContextMenuItem // this.LoadLastMovieContextMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Recent; this.LoadLastMovieContextMenuItem.Name = "LoadLastMovieContextMenuItem"; this.LoadLastMovieContextMenuItem.Size = new System.Drawing.Size(160, 22); this.LoadLastMovieContextMenuItem.Text = "Load Last Movie"; this.LoadLastMovieContextMenuItem.Click += new System.EventHandler(this.LoadLastMovieMenuItem_Click); // // StopMovieContextMenuItem // this.StopMovieContextMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.Stop; this.StopMovieContextMenuItem.Name = "StopMovieContextMenuItem"; this.StopMovieContextMenuItem.Size = new System.Drawing.Size(160, 22); this.StopMovieContextMenuItem.Text = "Stop Movie"; this.StopMovieContextMenuItem.Click += new System.EventHandler(this.StopMovieMenuItem_Click); // // RestartMovieContextMenuItem // this.RestartMovieContextMenuItem.Image = global::BizHawk.Client.MultiHawk.Properties.Resources.restart; this.RestartMovieContextMenuItem.Name = "RestartMovieContextMenuItem"; this.RestartMovieContextMenuItem.Size = new System.Drawing.Size(160, 22); this.RestartMovieContextMenuItem.Text = "Restart Movie"; this.RestartMovieContextMenuItem.Click += new System.EventHandler(this.RestartMovieMenuItem_Click); // // Mainform // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(655, 431); this.ContextMenuStrip = this.contextMenuStrip1; this.Controls.Add(this.WorkspacePanel); this.Controls.Add(this.MainformMenu); this.MainMenuStrip = this.MainformMenu; this.Name = "Mainform"; this.Text = "MultiHawk"; this.Load += new System.EventHandler(this.Mainform_Load); this.MainformMenu.ResumeLayout(false); this.MainformMenu.PerformLayout(); this.WorkspacePanel.ResumeLayout(false); this.WorkspacePanel.PerformLayout(); this.MainStatusBar.ResumeLayout(false); this.MainStatusBar.PerformLayout(); this.contextMenuStrip1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private MenuStripEx MainformMenu; private System.Windows.Forms.ToolStripMenuItem FileSubMenu; private System.Windows.Forms.ToolStripMenuItem OpenRomMenuItem; private System.Windows.Forms.Panel WorkspacePanel; private System.Windows.Forms.StatusStrip MainStatusBar; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripStatusLabel FameStatusBarLabel; private System.Windows.Forms.ToolStripStatusLabel StatusBarMessageLabel; private System.Windows.Forms.ToolStripMenuItem RecentRomSubMenu; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem MovieSubMenu; private System.Windows.Forms.ToolStripMenuItem RecordMovieMenuItem; private System.Windows.Forms.ToolStripMenuItem PlayMovieMenuItem; private System.Windows.Forms.ToolStripMenuItem StopMovieMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem ToggleReadonlyMenuItem; private System.Windows.Forms.ToolStripDropDownButton PlayRecordStatusButton; private System.Windows.Forms.ToolStripMenuItem configToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem controllerConfigToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hotkeyConfigToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem ExitMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem saveConfigToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem RebootCoresMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenSessionMenuItem; private System.Windows.Forms.ToolStripMenuItem SaveSessionMenuItem; private System.Windows.Forms.ToolStripMenuItem RecentSessionSubMenu; private System.Windows.Forms.ToolStripMenuItem NewSessionMenuItem; private System.Windows.Forms.ToolStripMenuItem SaveSessionAsMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem ViewSubMenu; private System.Windows.Forms.ToolStripMenuItem _1xMenuItem; private System.Windows.Forms.ToolStripMenuItem _2xMenuItem; private System.Windows.Forms.ToolStripMenuItem _3xMenuItem; private System.Windows.Forms.ToolStripMenuItem _4xMenuItem; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem LoadLastMovieContextMenuItem; private System.Windows.Forms.ToolStripMenuItem RecentMovieSubMenu; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripMenuItem RecordMovieContextMenuItem; private System.Windows.Forms.ToolStripMenuItem StopMovieContextMenuItem; private System.Windows.Forms.ToolStripMenuItem PlayMovieContextMenuItem; private System.Windows.Forms.ToolStripMenuItem RestartMovieMenuItem; private System.Windows.Forms.ToolStripMenuItem RestartMovieContextMenuItem; } }
48.26776
154
0.760632
[ "MIT" ]
CognitiaAI/StreetFighterRL
emulator/Bizhawk/BizHawk-master/BizHawk.Client.MultiHawk/Mainform.Designer.cs
26,501
C#
using Microsoft.EntityFrameworkCore; using Stl.Redis; namespace Stl.Fusion.EntityFramework.Redis.Operations; public class RedisOperationLogChangeNotifier<TDbContext> : DbServiceBase<TDbContext>, IOperationCompletionListener where TDbContext : DbContext { public RedisOperationLogChangeTrackingOptions<TDbContext> Options { get; } protected AgentInfo AgentInfo { get; } protected RedisDb RedisDb { get; } protected RedisPub RedisPub { get; } public RedisOperationLogChangeNotifier( RedisOperationLogChangeTrackingOptions<TDbContext> options, IServiceProvider services) : base(services) { Options = options; AgentInfo = services.GetRequiredService<AgentInfo>(); RedisDb = services.GetService<RedisDb<TDbContext>>() ?? services.GetRequiredService<RedisDb>(); RedisPub = RedisDb.GetPub(options.PubSubKey); Log.LogInformation("Using pub/sub key = '{Key}'", RedisPub.FullKey); } public Task OnOperationCompleted(IOperation operation) { if (!StringComparer.Ordinal.Equals(operation.AgentId, AgentInfo.Id.Value)) // Only local commands require notification return Task.CompletedTask; var commandContext = CommandContext.Current; if (commandContext != null) { // It's a command var operationScope = commandContext.Items.Get<DbOperationScope<TDbContext>>(); if (operationScope == null || !operationScope.IsUsed) // But it didn't change anything related to TDbContext return Task.CompletedTask; } // If it wasn't command, we pessimistically assume it changed something using var _ = ExecutionContextExt.SuppressFlow(); Task.Run(Notify); return Task.CompletedTask; } // Protected methods protected virtual async Task Notify() { while (true) { try { await RedisPub.Publish(AgentInfo.Id.Value).ConfigureAwait(false); return; } catch (Exception e) { Log.LogError(e, "Failed to publish to pub/sub key = '{Key}'; retrying", RedisPub.FullKey); await Clocks.CoarseCpuClock.Delay(Options.RetryDelay).ConfigureAwait(false); } } } }
38.745763
126
0.666229
[ "MIT" ]
servicetitan/Stl
src/Stl.Fusion.EntityFramework.Redis/Operations/RedisOperationLogChangeNotifier.cs
2,286
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.InteropServices; using MonoGame.Utilities; #if MONOMAC && PLATFORM_MACOS_LEGACY using MonoMac.OpenAL; #else using OpenTK.Audio.OpenAL; using OpenTK.Audio; using OpenTK; #endif #if ANDROID using System.Globalization; using Android.Content.PM; using Android.Content; using Android.Media; #endif #if IOS using AudioToolbox; using AVFoundation; #endif namespace Microsoft.Xna.Framework.Audio { internal sealed class OpenALSoundController : IDisposable { private static OpenALSoundController _instance = null; private IntPtr _device; private ContextHandle _context; //int outputSource; //int[] buffers; private AlcError _lastOpenALError; private int[] allSourcesArray; #if DESKTOPGL || ANGLE // MacOS & Linux shares a limit of 256. internal const int MAX_NUMBER_OF_SOURCES = 256; #elif MONOMAC // Reference: http://stackoverflow.com/questions/3894044/maximum-number-of-openal-sound-buffers-on-iphone internal const int MAX_NUMBER_OF_SOURCES = 256; #elif IOS // Reference: http://stackoverflow.com/questions/3894044/maximum-number-of-openal-sound-buffers-on-iphone internal const int MAX_NUMBER_OF_SOURCES = 32; #elif ANDROID // Set to the same as OpenAL on iOS internal const int MAX_NUMBER_OF_SOURCES = 32; #endif #if MONOMAC || IOS private const double PREFERRED_MIX_RATE = 44100; #elif ANDROID private const int DEFAULT_FREQUENCY = 48000; private const int DEFAULT_UPDATE_SIZE = 512; private const int DEFAULT_UPDATE_BUFFER_COUNT = 2; #elif DESKTOPGL #pragma warning disable 414 private static AudioContext _acontext; #pragma warning restore 414 private static OggStreamer _oggstreamer; #endif private List<int> availableSourcesCollection; private List<int> inUseSourcesCollection; private List<int> playingSourcesCollection; private List<int> purgeMe; private bool _bSoundAvailable = false; private Exception _SoundInitException; // Here to bubble back up to the developer bool _isDisposed; /// <summary> /// Sets up the hardware resources used by the controller. /// </summary> private OpenALSoundController() { if (!OpenSoundController()) { return; } // We have hardware here and it is ready _bSoundAvailable = true; allSourcesArray = new int[MAX_NUMBER_OF_SOURCES]; AL.GenSources(allSourcesArray); availableSourcesCollection = new List<int>(allSourcesArray); inUseSourcesCollection = new List<int>(); playingSourcesCollection = new List<int>(); purgeMe = new List<int>(); } ~OpenALSoundController() { Dispose(false); } /// <summary> /// Open the sound device, sets up an audio context, and makes the new context /// the current context. Note that this method will stop the playback of /// music that was running prior to the game start. If any error occurs, then /// the state of the controller is reset. /// </summary> /// <returns>True if the sound controller was setup, and false if not.</returns> private bool OpenSoundController() { #if MONOMAC alcMacOSXMixerOutputRate(PREFERRED_MIX_RATE); #endif try { _device = Alc.OpenDevice(string.Empty); } catch (Exception ex) { _SoundInitException = ex; return (false); } if (CheckALError("Could not open AL device")) { return(false); } if (_device != IntPtr.Zero) { #if ANDROID // Attach activity event handlers so we can pause and resume all playing sounds AndroidGameActivity.Paused += Activity_Paused; AndroidGameActivity.Resumed += Activity_Resumed; // Query the device for the ideal frequency and update buffer size so // we can get the low latency sound path. /* The recommended sequence is: Check for feature "android.hardware.audio.low_latency" using code such as this: import android.content.pm.PackageManager; ... PackageManager pm = getContext().getPackageManager(); boolean claimsFeature = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY); Check for API level 17 or higher, to confirm use of android.media.AudioManager.getProperty(). Get the native or optimal output sample rate and buffer size for this device's primary output stream, using code such as this: import android.media.AudioManager; ... AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); String sampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)); String framesPerBuffer = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)); Note that sampleRate and framesPerBuffer are Strings. First check for null and then convert to int using Integer.parseInt(). Now use OpenSL ES to create an AudioPlayer with PCM buffer queue data locator. See http://stackoverflow.com/questions/14842803/low-latency-audio-playback-on-android */ int frequency = DEFAULT_FREQUENCY; int updateSize = DEFAULT_UPDATE_SIZE; int updateBuffers = DEFAULT_UPDATE_BUFFER_COUNT; if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr1) { Android.Util.Log.Debug("OAL", Game.Activity.PackageManager.HasSystemFeature(PackageManager.FeatureAudioLowLatency) ? "Supports low latency audio playback." : "Does not support low latency audio playback."); var audioManager = Game.Activity.GetSystemService(Context.AudioService) as AudioManager; if (audioManager != null) { var result = audioManager.GetProperty(AudioManager.PropertyOutputSampleRate); if (!string.IsNullOrEmpty(result)) frequency = int.Parse(result, CultureInfo.InvariantCulture); result = audioManager.GetProperty(AudioManager.PropertyOutputFramesPerBuffer); if (!string.IsNullOrEmpty(result)) updateSize = int.Parse(result, CultureInfo.InvariantCulture); } // If 4.4 or higher, then we don't need to double buffer on the application side. // See http://stackoverflow.com/a/15006327 // Use the explicit value rather than a constant as the 4.2 SDK (the build SDK) does not define a constant for 4.4. if ((int)Android.OS.Build.VERSION.SdkInt >= 19) { updateBuffers = 1; } } else { Android.Util.Log.Debug("OAL", "Android 4.2 or higher required for low latency audio playback."); } Android.Util.Log.Debug("OAL", "Using sample rate " + frequency + "Hz and " + updateBuffers + " buffers of " + updateSize + " frames."); // These are missing and non-standard ALC constants const int AlcFrequency = 0x1007; const int AlcUpdateSize = 0x1014; const int AlcUpdateBuffers = 0x1015; int[] attribute = new[] { AlcFrequency, frequency, AlcUpdateSize, updateSize, AlcUpdateBuffers, updateBuffers, 0 }; #elif IOS EventHandler<AVAudioSessionInterruptionEventArgs> handler = delegate(object sender, AVAudioSessionInterruptionEventArgs e) { switch (e.InterruptionType) { case AVAudioSessionInterruptionType.Began: AVAudioSession.SharedInstance().SetActive(false); Alc.MakeContextCurrent(ContextHandle.Zero); Alc.SuspendContext(_context); break; case AVAudioSessionInterruptionType.Ended: AVAudioSession.SharedInstance().SetActive(true); Alc.MakeContextCurrent(_context); Alc.ProcessContext(_context); break; } }; AVAudioSession.Notifications.ObserveInterruption(handler); int[] attribute = new int[0]; #elif !DESKTOPGL int[] attribute = new int[0]; #endif #if DESKTOPGL _acontext = new AudioContext(); _context = Alc.GetCurrentContext(); _oggstreamer = new OggStreamer(); #else _context = Alc.CreateContext(_device, attribute); #endif if (CheckALError("Could not create AL context")) { CleanUpOpenAL(); return(false); } if (_context != ContextHandle.Zero) { Alc.MakeContextCurrent(_context); if (CheckALError("Could not make AL context current")) { CleanUpOpenAL(); return(false); } return (true); } } return (false); } public static OpenALSoundController GetInstance { get { if (_instance == null) _instance = new OpenALSoundController(); return _instance; } } public static void DestroyInstance() { if (_instance != null) { _instance.Dispose(); _instance = null; } } /// <summary> /// Checks the error state of the OpenAL driver. If a value that is not AlcError.NoError /// is returned, then the operation message and the error code is output to the console. /// </summary> /// <param name="operation">the operation message</param> /// <returns>true if an error occurs, and false if not.</returns> public bool CheckALError (string operation) { _lastOpenALError = Alc.GetError (_device); if (_lastOpenALError == AlcError.NoError) { return(false); } string errorFmt = "OpenAL Error: {0}"; Console.WriteLine (String.Format ("{0} - {1}", operation, //string.Format (errorFmt, Alc.GetString (_device, _lastOpenALError)))); string.Format (errorFmt, _lastOpenALError))); return (true); } /// <summary> /// Destroys the AL context and closes the device, when they exist. /// </summary> private void CleanUpOpenAL() { Alc.MakeContextCurrent(ContextHandle.Zero); #if DESKTOPGL if (_acontext != null) { _acontext.Dispose(); _acontext = null; } #else if (_context != ContextHandle.Zero) { Alc.DestroyContext (_context); _context = ContextHandle.Zero; } if (_device != IntPtr.Zero) { Alc.CloseDevice (_device); _device = IntPtr.Zero; } #endif _bSoundAvailable = false; } /// <summary> /// Dispose of the OpenALSoundCOntroller. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose of the OpenALSoundCOntroller. /// </summary> /// <param name="disposing">If true, the managed resources are to be disposed.</param> void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { if (_bSoundAvailable) { #if DESKTOPGL if(_oggstreamer != null) _oggstreamer.Dispose(); #endif for (int i = 0; i < allSourcesArray.Length; i++) AL.DeleteSource(allSourcesArray[i]); CleanUpOpenAL(); } } _isDisposed = true; } } /// <summary> /// Reserves the given sound buffer. If there are no available sources then false is /// returned, otherwise true will be returned and the sound buffer can be played. If /// the controller was not able to setup the hardware, then false will be returned. /// </summary> /// <param name="soundBuffer">The sound buffer you want to play</param> /// <returns>True if the buffer can be played, and false if not.</returns> public int ReserveSource() { if (!CheckInitState()) { throw new InstancePlayLimitException(); } int sourceNumber; if (availableSourcesCollection.Count == 0) { throw new InstancePlayLimitException(); } sourceNumber = availableSourcesCollection.First (); inUseSourcesCollection.Add(sourceNumber); availableSourcesCollection.Remove (sourceNumber); return sourceNumber; } public void RecycleSource(int sourceId) { if (!CheckInitState()) { return; } inUseSourcesCollection.Remove(sourceId); availableSourcesCollection.Add(sourceId); } public void PlaySound(SoundEffectInstance inst) { if (!CheckInitState()) { return; } lock (playingSourcesCollection) { playingSourcesCollection.Add(inst.SourceId); } AL.SourcePlay(inst.SourceId); } public void FreeSource(SoundEffectInstance inst) { lock (playingSourcesCollection) { playingSourcesCollection.Remove(inst.SourceId); } RecycleSource(inst.SourceId); inst.SourceId = 0; inst.HasSourceId = false; inst.SoundState = SoundState.Stopped; } /// <summary> /// Checks if the AL controller was initialized properly. If there was an /// exception thrown during the OpenAL init, then that exception is thrown /// inside of NoAudioHardwareException. /// </summary> /// <returns>True if the controller was initialized, false if not.</returns> internal bool CheckInitState() { if (!_bSoundAvailable) { if (_SoundInitException != null) { Exception e = _SoundInitException; _SoundInitException = null; throw new NoAudioHardwareException("No audio hardware available.", e); } return (false); } return (true); } public double SourceCurrentPosition (int sourceId) { if (!CheckInitState()) { return(0.0); } int pos; AL.GetSource (sourceId, ALGetSourcei.SampleOffset, out pos); return pos; } /// <summary> /// Called repeatedly, this method cleans up the state of the management lists. This method /// will also lock on the playingSourcesCollection. Sources that are stopped will be recycled /// using the RecycleSource method. /// </summary> public void Update() { if (!_bSoundAvailable) { //OK to ignore this here because the game can run without sound. return; } ALSourceState state; lock (playingSourcesCollection) { for (int i = playingSourcesCollection.Count - 1; i >= 0; --i) { int sourceId = playingSourcesCollection[i]; state = AL.GetSourceState(sourceId); if (state == ALSourceState.Stopped) { purgeMe.Add(sourceId); playingSourcesCollection.RemoveAt(i); } } } lock (purgeMe) { foreach (int sourceId in purgeMe) { AL.Source(sourceId, ALSourcei.Buffer, 0); inUseSourcesCollection.Remove(sourceId); availableSourcesCollection.Add(sourceId); } purgeMe.Clear(); } } #if ANDROID const string Lib = "openal32.dll"; const CallingConvention Style = CallingConvention.Cdecl; [DllImport(Lib, EntryPoint = "alcDevicePauseSOFT", ExactSpelling = true, CallingConvention = Style)] unsafe static extern void alcDevicePauseSOFT(IntPtr device); [DllImport(Lib, EntryPoint = "alcDeviceResumeSOFT", ExactSpelling = true, CallingConvention = Style)] unsafe static extern void alcDeviceResumeSOFT(IntPtr device); void Activity_Paused(object sender, EventArgs e) { // Pause all currently playing sounds. The internal pause count in OALSoundBuffer // will take care of sounds that were already paused. // lock (playingSourcesCollection) // { // foreach (var source in playingSourcesCollection) // source.Pause(); // } alcDevicePauseSOFT(_device); } void Activity_Resumed(object sender, EventArgs e) { // Resume all sounds that were playing when the activity was paused. The internal // pause count in OALSoundBuffer will take care of sounds that were previously paused. // lock (playingSourcesCollection) // { // foreach (var source in playingSourcesCollection) // source.Resume(); // } alcDeviceResumeSOFT(_device); } #endif #if MONOMAC public const string OpenALLibrary = "/System/Library/Frameworks/OpenAL.framework/OpenAL"; [DllImport(OpenALLibrary, EntryPoint = "alcMacOSXMixerOutputRate")] static extern void alcMacOSXMixerOutputRate (double rate); // caution #endif } }
36.08427
226
0.557943
[ "MIT" ]
ZZHGit/MonoGame
MonoGame.Framework/Audio/OpenALSoundController.cs
19,269
C#
/* * Copyright 2005 dotlucene.net * * 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.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Collections.Generic; using System.ComponentModel; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; using Dropout.Icons; namespace Dropout { /// <summary> /// Summary description for Form1. /// </summary> public class frmMain : System.Windows.Forms.Form { private string pathIndex; private IndexWriter indexWriter; private string[] patterns; private SystemImageList imageListDocuments; bool explorerMenu = false; bool portablePaths = true; private IndexSearcher searcher = null; private string[] searchDirs; private string[] searchExclude; private string appPath; private string appDir; private string appName; private string searchTermsPath; Dictionary<string, long> dateStamps; Dictionary<string, long> newDateStamps; BackgroundWorker indexWorker; BackgroundWorker searchWorker; AutoCompleteStringCollection searchTerms = new AutoCompleteStringCollection(); int indexCounter = 0; int indexMaxFileSize = 20; int zipMaxSize = 5; int resultsMax = 200; int fileCount; string status = ""; // statistics private long bytesTotal = 0; private int countTotal = 0; private int countSkipped = 0; int countNew = 0; int countChanged = 0; private System.Windows.Forms.Label labelStatus; private System.Windows.Forms.ListView listViewResults; private System.Windows.Forms.ColumnHeader columnHeaderIcon; private System.Windows.Forms.ColumnHeader columnHeaderName; private System.Windows.Forms.ColumnHeader columnHeaderFolder; private System.Windows.Forms.ColumnHeader columnHeaderScore; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private ColumnHeader colHeaderModified; private TabControl tabControl1; private TabPage tabPage1; private TextBox textBoxQuery; private Button buttonSearch; private TabPage tabPage2; private Label label4; private Button buttonSearch1; private Label label3; private TextBox textBoxContent; private Label label2; private TextBox textBoxName; private Label label1; private Label label5; private DateTimePicker dateTimePickerTo; private DateTimePicker dateTimePickerFrom; private ToolTip toolTip1; private PictureBox pictureBox1; private PictureBox pictureBox2; private Label labelSearch; private Button buttonRefreshIndex; private PictureBox pictureBox3; private TextBox textBoxType; private PictureBox pictureBoxCredits; private ContextMenuStrip contextMenuStrip1; private ToolStripMenuItem openFileToolStripMenuItem; private ToolStripMenuItem openContainingFolderToolStripMenuItem; private Button buttonToday; private System.ComponentModel.IContainer components; public frmMain() { // // Required for Windows Form Designer support // InitializeComponent(); imageListDocuments = new SystemImageList(SystemImageListSize.SmallIcons); SystemImageListHelper.SetListViewImageList(listViewResults, imageListDocuments, false); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain)); this.labelStatus = new System.Windows.Forms.Label(); this.listViewResults = new System.Windows.Forms.ListView(); this.columnHeaderIcon = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderScore = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colHeaderModified = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderFolder = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.openFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openContainingFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.textBoxQuery = new System.Windows.Forms.TextBox(); this.buttonSearch = new System.Windows.Forms.Button(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.textBoxType = new System.Windows.Forms.TextBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker(); this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker(); this.label4 = new System.Windows.Forms.Label(); this.buttonSearch1 = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.textBoxContent = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.textBoxName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.labelSearch = new System.Windows.Forms.Label(); this.buttonRefreshIndex = new System.Windows.Forms.Button(); this.pictureBoxCredits = new System.Windows.Forms.PictureBox(); this.buttonToday = new System.Windows.Forms.Button(); this.contextMenuStrip1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCredits)).BeginInit(); this.SuspendLayout(); // // labelStatus // this.labelStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelStatus.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelStatus.Location = new System.Drawing.Point(128, 442); this.labelStatus.Name = "labelStatus"; this.labelStatus.Size = new System.Drawing.Size(546, 19); this.labelStatus.TabIndex = 0; // // listViewResults // this.listViewResults.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listViewResults.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderIcon, this.columnHeaderName, this.columnHeaderScore, this.colHeaderModified, this.columnHeaderFolder}); this.listViewResults.ContextMenuStrip = this.contextMenuStrip1; this.listViewResults.FullRowSelect = true; this.listViewResults.Location = new System.Drawing.Point(12, 212); this.listViewResults.Name = "listViewResults"; this.listViewResults.Size = new System.Drawing.Size(660, 192); this.listViewResults.TabIndex = 2; this.listViewResults.UseCompatibleStateImageBehavior = false; this.listViewResults.View = System.Windows.Forms.View.Details; this.listViewResults.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listViewResults_ColumnClick); this.listViewResults.DoubleClick += new System.EventHandler(this.listViewResults_DoubleClick); this.listViewResults.MouseUp += new System.Windows.Forms.MouseEventHandler(this.listViewResults_MouseUp); // // columnHeaderIcon // this.columnHeaderIcon.Text = ""; this.columnHeaderIcon.Width = 22; // // columnHeaderName // this.columnHeaderName.Text = "Name"; this.columnHeaderName.Width = 243; // // columnHeaderScore // this.columnHeaderScore.Text = "Score"; // // colHeaderModified // this.colHeaderModified.Text = "Modified"; this.colHeaderModified.Width = 150; // // columnHeaderFolder // this.columnHeaderFolder.Text = "Folder"; this.columnHeaderFolder.Width = 400; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openFileToolStripMenuItem, this.openContainingFolderToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(202, 48); // // openFileToolStripMenuItem // this.openFileToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.openFileToolStripMenuItem.Name = "openFileToolStripMenuItem"; this.openFileToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.openFileToolStripMenuItem.Text = "Open File"; this.openFileToolStripMenuItem.Click += new System.EventHandler(this.openFileToolStripMenuItem_Click); // // openContainingFolderToolStripMenuItem // this.openContainingFolderToolStripMenuItem.Name = "openContainingFolderToolStripMenuItem"; this.openContainingFolderToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.openContainingFolderToolStripMenuItem.Text = "Open Containing Folder"; this.openContainingFolderToolStripMenuItem.Click += new System.EventHandler(this.openContainingFolderToolStripMenuItem_Click); // // folderBrowserDialog1 // this.folderBrowserDialog1.ShowNewFolderButton = false; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(662, 198); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.pictureBox2); this.tabPage1.Controls.Add(this.pictureBox1); this.tabPage1.Controls.Add(this.textBoxQuery); this.tabPage1.Controls.Add(this.buttonSearch); this.tabPage1.Location = new System.Drawing.Point(4, 25); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(654, 169); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Search"; this.tabPage1.UseVisualStyleBackColor = true; // // pictureBox2 // this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox2.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(488, 80); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(27, 28); this.pictureBox2.TabIndex = 14; this.pictureBox2.TabStop = false; this.toolTip1.SetToolTip(this.pictureBox2, resources.GetString("pictureBox2.ToolTip")); this.pictureBox2.Click += new System.EventHandler(this.pictureBox2_Click); // // pictureBox1 // this.pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.Top; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(261, 11); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(135, 62); this.pictureBox1.TabIndex = 13; this.pictureBox1.TabStop = false; // // textBoxQuery // this.textBoxQuery.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxQuery.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.textBoxQuery.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; this.textBoxQuery.Location = new System.Drawing.Point(161, 81); this.textBoxQuery.Name = "textBoxQuery"; this.textBoxQuery.Size = new System.Drawing.Size(321, 22); this.textBoxQuery.TabIndex = 0; this.textBoxQuery.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxQuery_KeyDown); // // buttonSearch // this.buttonSearch.Anchor = System.Windows.Forms.AnchorStyles.Top; this.buttonSearch.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonSearch.Location = new System.Drawing.Point(249, 116); this.buttonSearch.Name = "buttonSearch"; this.buttonSearch.Size = new System.Drawing.Size(160, 24); this.buttonSearch.TabIndex = 1; this.buttonSearch.Text = "Search"; this.buttonSearch.Click += new System.EventHandler(this.buttonSearch_Click); // // tabPage2 // this.tabPage2.Controls.Add(this.buttonToday); this.tabPage2.Controls.Add(this.textBoxType); this.tabPage2.Controls.Add(this.pictureBox3); this.tabPage2.Controls.Add(this.dateTimePickerTo); this.tabPage2.Controls.Add(this.dateTimePickerFrom); this.tabPage2.Controls.Add(this.label4); this.tabPage2.Controls.Add(this.buttonSearch1); this.tabPage2.Controls.Add(this.label3); this.tabPage2.Controls.Add(this.textBoxContent); this.tabPage2.Controls.Add(this.label2); this.tabPage2.Controls.Add(this.textBoxName); this.tabPage2.Controls.Add(this.label1); this.tabPage2.Controls.Add(this.label5); this.tabPage2.Location = new System.Drawing.Point(4, 25); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(654, 169); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Advanced"; this.tabPage2.UseVisualStyleBackColor = true; // // textBoxType // this.textBoxType.Location = new System.Drawing.Point(75, 133); this.textBoxType.Name = "textBoxType"; this.textBoxType.Size = new System.Drawing.Size(194, 22); this.textBoxType.TabIndex = 5; this.toolTip1.SetToolTip(this.textBoxType, "pdf, doc, docx\r\nxls, xlsx"); this.textBoxType.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxQuery_KeyDown); // // pictureBox3 // this.pictureBox3.Anchor = System.Windows.Forms.AnchorStyles.Top; this.pictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox3.Image"))); this.pictureBox3.Location = new System.Drawing.Point(261, 11); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(135, 62); this.pictureBox3.TabIndex = 23; this.pictureBox3.TabStop = false; // // dateTimePickerTo // this.dateTimePickerTo.CustomFormat = ""; this.dateTimePickerTo.Location = new System.Drawing.Point(526, 133); this.dateTimePickerTo.MaxDate = new System.DateTime(2100, 12, 31, 0, 0, 0, 0); this.dateTimePickerTo.MinDate = new System.DateTime(1990, 1, 1, 0, 0, 0, 0); this.dateTimePickerTo.Name = "dateTimePickerTo"; this.dateTimePickerTo.Size = new System.Drawing.Size(100, 22); this.dateTimePickerTo.TabIndex = 9; // // dateTimePickerFrom // this.dateTimePickerFrom.CustomFormat = ""; this.dateTimePickerFrom.Location = new System.Drawing.Point(338, 133); this.dateTimePickerFrom.MaxDate = new System.DateTime(2100, 12, 31, 0, 0, 0, 0); this.dateTimePickerFrom.MinDate = new System.DateTime(1900, 1, 1, 0, 0, 0, 0); this.dateTimePickerFrom.Name = "dateTimePickerFrom"; this.dateTimePickerFrom.Size = new System.Drawing.Size(100, 22); this.dateTimePickerFrom.TabIndex = 7; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(275, 137); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(60, 16); this.label4.TabIndex = 6; this.label4.Text = "Modified:"; // // buttonSearch1 // this.buttonSearch1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonSearch1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonSearch1.Location = new System.Drawing.Point(466, 72); this.buttonSearch1.Name = "buttonSearch1"; this.buttonSearch1.Size = new System.Drawing.Size(160, 54); this.buttonSearch1.TabIndex = 10; this.buttonSearch1.Text = "Search"; this.buttonSearch1.Click += new System.EventHandler(this.buttonSearch_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(17, 74); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(57, 16); this.label3.TabIndex = 0; this.label3.Text = "Content:"; // // textBoxContent // this.textBoxContent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxContent.Location = new System.Drawing.Point(75, 74); this.textBoxContent.Name = "textBoxContent"; this.textBoxContent.Size = new System.Drawing.Size(385, 22); this.textBoxContent.TabIndex = 1; this.textBoxContent.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxQuery_KeyDown); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(17, 102); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(46, 16); this.label2.TabIndex = 2; this.label2.Text = "Name:"; // // textBoxName // this.textBoxName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxName.Location = new System.Drawing.Point(75, 102); this.textBoxName.Name = "textBoxName"; this.textBoxName.Size = new System.Drawing.Size(385, 22); this.textBoxName.TabIndex = 3; this.textBoxName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxQuery_KeyDown); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(17, 130); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(39, 16); this.label1.TabIndex = 4; this.label1.Text = "Type:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(503, 136); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(21, 16); this.label5.TabIndex = 8; this.label5.Text = "To"; // // toolTip1 // this.toolTip1.AutomaticDelay = 100; this.toolTip1.AutoPopDelay = 10000; this.toolTip1.InitialDelay = 100; this.toolTip1.IsBalloon = true; this.toolTip1.ReshowDelay = 20; this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.toolTip1.ToolTipTitle = "Examples"; // // labelSearch // this.labelSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelSearch.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelSearch.Location = new System.Drawing.Point(12, 414); this.labelSearch.Name = "labelSearch"; this.labelSearch.Size = new System.Drawing.Size(654, 20); this.labelSearch.TabIndex = 3; // // buttonRefreshIndex // this.buttonRefreshIndex.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonRefreshIndex.Location = new System.Drawing.Point(12, 437); this.buttonRefreshIndex.Name = "buttonRefreshIndex"; this.buttonRefreshIndex.Size = new System.Drawing.Size(110, 25); this.buttonRefreshIndex.TabIndex = 4; this.buttonRefreshIndex.Text = "Refresh Index"; this.buttonRefreshIndex.UseVisualStyleBackColor = true; this.buttonRefreshIndex.Click += new System.EventHandler(this.buttonRefreshIndex_Click); // // pictureBoxCredits // this.pictureBoxCredits.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pictureBoxCredits.Cursor = System.Windows.Forms.Cursors.Hand; this.pictureBoxCredits.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxCredits.Image"))); this.pictureBoxCredits.Location = new System.Drawing.Point(647, 5); this.pictureBoxCredits.Name = "pictureBoxCredits"; this.pictureBoxCredits.Size = new System.Drawing.Size(25, 25); this.pictureBoxCredits.TabIndex = 5; this.pictureBoxCredits.TabStop = false; this.pictureBoxCredits.Click += new System.EventHandler(this.pictureBoxCredits_Click); // // buttonToday // this.buttonToday.Location = new System.Drawing.Point(444, 133); this.buttonToday.Name = "buttonToday"; this.buttonToday.Size = new System.Drawing.Size(57, 23); this.buttonToday.TabIndex = 24; this.buttonToday.Text = "Today"; this.buttonToday.UseVisualStyleBackColor = true; this.buttonToday.Click += new System.EventHandler(this.buttonToday_Click); // // frmMain // this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.ClientSize = new System.Drawing.Size(686, 466); this.Controls.Add(this.pictureBoxCredits); this.Controls.Add(this.buttonRefreshIndex); this.Controls.Add(this.labelSearch); this.Controls.Add(this.tabControl1); this.Controls.Add(this.listViewResults); this.Controls.Add(this.labelStatus); this.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(702, 480); this.Name = "frmMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Dropout"; this.Activated += new System.EventHandler(this.Form1_Activated); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.contextMenuStrip1.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCredits)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.DoEvents(); Application.Run(new frmMain()); } private void Form1_Load(object sender, System.EventArgs e) { appPath = typeof(frmMain).Assembly.Location; appDir = Path.GetDirectoryName( appPath ); appName = Path.GetFileNameWithoutExtension(appPath); string iniPath = Path.Combine(appDir, appName + ".ini"); if (File.Exists(iniPath)) { IniFile ini = new IniFile(iniPath); string tempPatterns = ini.IniReadValue("Location", "Search Patterns"); if (string.IsNullOrEmpty(tempPatterns) == false) { patterns = tempPatterns.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); } string tempSearchDir = ini.IniReadValue("Location", "Search Directory"); if (string.IsNullOrEmpty(tempSearchDir) == false) { List<string> dirs = new List<string>(); foreach(string dir in tempSearchDir.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { dirs.Add(Path.Combine(appDir, dir)); } searchDirs = dirs.ToArray(); } string tempSearchExclude = ini.IniReadValue("Location", "Paths To Skip"); if (string.IsNullOrEmpty(tempSearchExclude) == false) { List<string> excludes = new List<string>(); foreach (string exclude in tempSearchExclude.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { excludes.Add(exclude.ToLower()); } searchExclude = excludes.ToArray(); } pathIndex = ini.IniReadValue("Location", "Search Index"); if (string.IsNullOrEmpty(pathIndex) == false) pathIndex = Path.Combine(appDir, pathIndex); string maxSize = ini.IniReadValue("Index", "Max Size"); if (!string.IsNullOrEmpty(maxSize)) indexMaxFileSize = int.Parse(maxSize); maxSize = ini.IniReadValue("Index", "Zip Max Size"); if (!string.IsNullOrEmpty(maxSize)) zipMaxSize = int.Parse(maxSize); try { string max = ini.IniReadValue("Results", "Max Result"); if (!string.IsNullOrEmpty(max)) resultsMax = int.Parse(max); } catch { MessageBox.Show("The Max Result setting has an invalid value", "Max Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } try { string explorer = ini.IniReadValue("Options", "Explorer Menu"); if (!string.IsNullOrEmpty(explorer)) explorerMenu = bool.Parse(explorer); } catch { MessageBox.Show("The Explorer Menu setting has an invalid value, should be true or false", "Explorer Menu", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } try { string portable = ini.IniReadValue("Options", "Portable Paths"); if (!string.IsNullOrEmpty(portable)) portablePaths = bool.Parse(portable); } catch { MessageBox.Show("The Portable Paths setting has an invalid value, should be true or false", "Portable Paths", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } // Set defaults if( patterns == null) patterns = new string[] { "*.*" }; if( searchDirs == null ) searchDirs = new string[] { appDir }; if (searchExclude == null) searchExclude = new string[] { "c:\\$Recycle.Bin" }; if (string.IsNullOrEmpty(pathIndex)) pathIndex = Path.Combine(appDir, "SearchIndex"); searchTermsPath = Path.Combine(pathIndex, "searchhistory"); dateTimePickerFrom.MaxDate = DateTime.Today; dateTimePickerFrom.Format = DateTimePickerFormat.Short; dateTimePickerFrom.Value = dateTimePickerFrom.MinDate; dateTimePickerTo.Format = DateTimePickerFormat.Short; dateTimePickerTo.Value = DateTime.Today.AddDays(1); Timer t = new Timer(); t.Interval = 1000; t.Tick += delegate(object sender1, EventArgs e1) { if (indexCounter > 10) indexCounter = 0; if (indexWorker != null && indexWorker.IsBusy) labelStatus.Text = status + "".PadRight(indexCounter++, '.'); }; t.Start(); Index(); searchTerms = LoadSearchTerms(); textBoxQuery.AutoCompleteCustomSource = searchTerms; } void Index() { fileCount = 0; indexWorker = new BackgroundWorker(); indexWorker.WorkerReportsProgress = true; indexWorker.WorkerSupportsCancellation = true; //watcher.EnableRaisingEvents = false; indexWorker.DoWork += delegate(object sender, DoWorkEventArgs e) { dateStamps = new Dictionary<string, long>(); newDateStamps = new Dictionary<string, long>(); // First load all of the datestamps to check if the file is modified if (checkIndex()) { IndexReader indexReader = IndexReader.Open(this.pathIndex, true); // Check to see if we are in relative or absolute path mode for (int i = 0; i < indexReader.NumDocs(); i++) { if (indexReader.IsDeleted(i) == false) { Document doc = indexReader.Document(i); string path = doc.Get("path"); long ticks = long.Parse(doc.Get("ticks")); if (dateStamps.ContainsKey(path)) { dateStamps[path] = Math.Max(dateStamps[path], ticks); } else dateStamps.Add(path, ticks); } } indexReader.Close(); } // Try to open the Index for writing int attempts = 0; while (attempts < 5) { if (checkIndex()) { try { indexWriter = new IndexWriter(FSDirectory.GetDirectory(pathIndex), new StandardAnalyzer(), false); attempts = 5; } catch (Lucene.Net.Store.LockObtainFailedException ex) { attempts++; if (System.IO.Directory.Exists(pathIndex)) System.IO.Directory.Delete(pathIndex, true); } } else { indexWriter = new IndexWriter(FSDirectory.GetDirectory(pathIndex), new StandardAnalyzer(), true); attempts = 5; } } // Hide the file File.SetAttributes(pathIndex, FileAttributes.Hidden); bytesTotal = 0; countTotal = 0; countSkipped = 0; countNew = 0; countChanged = 0; bool cancel = false; DateTime start = DateTime.Now; foreach (string searchDir in searchDirs) { if (System.IO.Directory.Exists(searchDir)) { DirectoryInfo di = new DirectoryInfo(searchDir); // Add folder cancel = addFolder(searchDir, di); // Exit if cancel has been pressed if (cancel) break; } } if (cancel) { string summary = String.Format("Cancelled. Indexed {0} files ({1} bytes). Skipped {2} files.", countTotal, bytesTotal, countSkipped); summary += String.Format(" Took {0}", (DateTime.Now - start)); indexWorker.ReportProgress(0, summary); e.Cancel = true; } else { int deleted = 0; // Loop through all the files and delete if it doesn't exist foreach (string file in dateStamps.Keys) { if (newDateStamps.ContainsKey(file) == false) { deleted++; indexWriter.DeleteDocuments(new Term("path", file)); } } string summary = String.Format("{0} files ({1} mb). New {2}. Changed {3}, Skipped {4}. Removed {5}. {6}", countTotal, (bytesTotal / 1000000).ToString("N0"), countNew, countChanged, countSkipped, deleted, DateTime.Now - start); indexWorker.ReportProgress(0, summary); } indexWriter.Optimize(); indexWriter.Close(); }; indexWorker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) { if( e.ProgressPercentage == 0 ) status = e.UserState.ToString(); else status = string.Format("Files indexed {0}. {1}", countTotal, e.UserState.ToString()); this.labelStatus.Text = status; indexCounter = 0; }; indexWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { //watcher.EnableRaisingEvents = true; }; indexWorker.RunWorkerAsync(); } /// <summary> /// Indexes a folder. /// </summary> /// <param name="directory"></param> private bool addFolder(string searchDir, DirectoryInfo directory) { // Don't index the indexes..... if (directory.FullName == pathIndex) return false; // Don't index excluded files foreach (string exclude in searchExclude) { if (directory.FullName.ToLower().Contains(exclude)) return false; } int filesIndexed = 0; // find all matching files foreach (string pattern in patterns) { FileInfo[] fis = null; try { fis = directory.GetFiles(pattern); } catch (Exception) { return false; } foreach (FileInfo fi in fis) { // skip temporary office files if (fi.Name.StartsWith("~") || fi.Name.StartsWith(".")) continue; if (indexWorker.CancellationPending) return true; fileCount++; try { string path = fi.FullName; string relPath = path; // Remove the full path if (portablePaths) { relPath = path.Replace(searchDir, ""); // Remove the starting slash if (relPath.StartsWith(@"\")) relPath = relPath.Substring(1); } newDateStamps.Add(relPath, fi.LastWriteTime.Ticks); // Check to see of doc has changed if (dateStamps.ContainsKey(relPath) == false) { addOfficeDocument(path, relPath, false); filesIndexed++; } else if (dateStamps[relPath] < fi.LastWriteTime.Ticks) { // Delete the existing document addOfficeDocument(path, relPath, true); filesIndexed++; } // update statistics this.countTotal++; this.bytesTotal += fi.Length; // show added file indexWorker.ReportProgress(fileCount, Path.GetFileName(fi.FullName)); } catch (Exception) { // parsing and indexing wasn't successful, skipping that file this.countSkipped++; indexWorker.ReportProgress(fileCount, "Skipped:" + Path.GetFileName(fi.FullName)); } } } // Only commit if things have been indexed if(filesIndexed > 0) indexWriter.Commit(); // add subfolders foreach (DirectoryInfo di in directory.GetDirectories()) { bool cancel = addFolder(searchDir, di); if (cancel) return true; } return false; } /// <summary> /// Parses and indexes an IFilter parseable file. /// </summary> /// <param name="path"></param> private void addOfficeDocument(string path, string relPath, bool exists) { string filename = Path.GetFileNameWithoutExtension(path); string extension = Path.GetExtension(path); FileInfo fi = new FileInfo(path); Document doc = new Document(); string text = ""; try { if (extension.ToLower() == ".zip" && fi.Length < zipMaxSize * 1000000) text = Parser.Parse(path); else if (fi.Length < indexMaxFileSize * 1000000) text = Parser.Parse(path); } catch (Exception) { // Ignore error, add with not content } doc.Add(new Field("modified", fi.LastWriteTime.ToString("yyyyMMddHHmmss"), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("ticks", fi.LastWriteTime.Ticks.ToString(), Field.Store.YES, Field.Index.NO)); doc.Add(new Field("type", extension.Substring(1), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("name", filename, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("path", relPath, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("content", text, Field.Store.NO, Field.Index.ANALYZED)); if (exists) { indexWriter.UpdateDocument(new Term("path", relPath), doc); countChanged++; } else { indexWriter.AddDocument(doc); countNew++; } } private void buttonSearch_Click(object sender, System.EventArgs e) { Search(); } private bool checkIndex() { try { searcher = new IndexSearcher(pathIndex, true); searcher.Close(); return true; } catch (IOException) { return false; } } private void Search() { buttonSearch.Enabled = false; DateTime start = DateTime.Now; int hitCount = 0; searchWorker = new BackgroundWorker(); searchWorker.WorkerReportsProgress = true; searchWorker.WorkerSupportsCancellation = true; string queryText = ""; string queryHistory = ""; if (tabControl1.SelectedIndex == 0) { // Parse the query, "content" is the default field to search if (this.textBoxQuery.Text.Trim() == String.Empty) return; queryText ="(" + textBoxQuery.Text + ")"; // Also search the path if the query isn't qualified if (queryText.Contains(":") == false) queryText += " OR name:" + queryText; queryHistory = textBoxQuery.Text; } else { queryText = ""; if (textBoxContent.Text.Trim() != "") queryText = "content:" + textBoxContent.Text + " AND"; if (textBoxName.Text.Trim() != "") queryText += " name:" + textBoxName.Text + " AND"; if (textBoxType.Text != "") { string types = ""; foreach (string type in textBoxType.Text.Split(',')) { types += " type:" + type + " OR"; } if (types != "") { // Remove last OR types = types.Substring(0, types.Length - 2); queryText += " (" + types + ") AND"; } } queryText += " modified:[" + dateTimePickerFrom.Value.ToString("yyyyMMdd") + " TO " + dateTimePickerTo.Value.ToString("yyyyMMdd") + "]"; } queryText = queryText.Trim(); this.listViewResults.Items.Clear(); searchWorker.DoWork += delegate(object sender, DoWorkEventArgs e) { try { searcher = new IndexSearcher(this.pathIndex, true); } catch (IOException ex) { throw new Exception("The index doesn't exist or is damaged. Please rebuild the index.", ex); } Query query; try { QueryParser parser = new QueryParser("content", new StandardAnalyzer()); query = parser.Parse(queryText); } catch (Exception ex) { throw new ArgumentException("Invalid query: " + ex.Message, "Query", ex); } // Search Hits hits = searcher.Search(query); hitCount = hits.Length(); // Optionally limit the result count // int resultsCount = smallerOf(20, hits.Length()); for (int i = 0; i < hits.Length(); i++) { // get the document from index Document doc = hits.Doc(i); // create a new row with the result data string type = doc.Get("type"); string filename = doc.Get("name") + "." + doc.Get("type"); string path = doc.Get("path"); DateTime modified = DateTime.ParseExact(doc.Get("modified"), "yyyyMMddHHmmss", null); string folder = ""; try { folder = Path.GetDirectoryName(path); } catch (Exception) { // Couldn't get directory name... } ListViewItem item = new ListViewItem(new string[] { null, filename, (hits.Score(i) * 100).ToString("N0"), modified.ToShortDateString() + " " + modified.ToShortTimeString(), folder }); item.Tag = path; try { item.ImageIndex = imageListDocuments.IconIndex(filename); } catch (Exception) { // Couldn't get icon... } searchWorker.ReportProgress(0, item); } searcher.Close(); }; searchWorker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) { this.listViewResults.Items.Add((ListViewItem)e.UserState); }; searchWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { this.labelSearch.Text = e.Error.Message; } else { if (queryHistory != "" && hitCount > 0 && searchTerms.Contains(queryHistory) == false) searchTerms.Add(queryHistory); this.labelSearch.Text = String.Format("Search took {0}. Found {1} items.", (DateTime.Now - start), hitCount); } buttonSearch.Enabled = true; }; searchWorker.RunWorkerAsync(); } private void listViewResults_DoubleClick(object sender, System.EventArgs e) { if (this.listViewResults.SelectedItems.Count != 1) return; string path = (string) this.listViewResults.SelectedItems[0].Tag; OpenFile(path); } private void openFileToolStripMenuItem_Click(object sender, EventArgs e) { if (listViewResults.SelectedItems.Count > 0) { foreach (ListViewItem item in listViewResults.SelectedItems) { string path = (string)item.Tag; OpenFile(path); } } } private void openContainingFolderToolStripMenuItem_Click(object sender, EventArgs e) { if (listViewResults.SelectedItems.Count > 0) { foreach (ListViewItem item in listViewResults.SelectedItems) { string path = (string)item.Tag; path = Path.GetDirectoryName(path); OpenDirectory(path); } } } void OpenFile(string path) { // Loop through each search directory and see if the file exists foreach (string searchDir in searchDirs) { // Remove starting slash in old index files if (path.StartsWith(@"\")) path = path.Substring(1); string fullPath = Path.Combine(searchDir, path); if (File.Exists(fullPath)) { Process.Start(fullPath); return; } } // Didn't find it so return a message MessageBox.Show("The file no longer exists, rebuild the index", "Deleted or Moved", MessageBoxButtons.OK, MessageBoxIcon.Error); } void OpenDirectory(string path) { // Loop through each search directory and see if the file exists foreach (string searchDir in searchDirs) { // Remove starting slash in old index files if (path.StartsWith(@"\")) path = path.Substring(1); string fullPath = Path.Combine(searchDir, path); if (System.IO.Directory.Exists(fullPath)) { Process.Start(fullPath); return; } } // Didn't find it so return a message MessageBox.Show("The directory no longer exists, rebuild the index", "Deleted or Moved", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void textBoxQuery_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.Enter) Search(); } private void buttonClean_Click(object sender, System.EventArgs e) { System.IO.Directory.Delete(this.pathIndex, true); checkIndex(); } private void pictureBox2_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("http://lucene.apache.org/java/2_4_0/queryparsersyntax.html"); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { SaveSearchTerms(searchTerms); if (indexWorker != null && indexWorker.IsBusy) { e.Cancel = true; indexWorker.CancelAsync(); status = "Waiting for index to cancel"; labelStatus.Text = status; Timer t = new Timer(); t.Interval = 100; t.Tick += delegate(object sender1, EventArgs e1) { if (!(indexWorker != null && indexWorker.IsBusy)) { t.Stop(); this.Close(); } }; t.Start(); } } private void buttonRefreshIndex_Click(object sender, EventArgs e) { Index(); } bool start = true; private void Form1_Activated(object sender, EventArgs e) { if (start) { textBoxQuery.Focus(); start = false; } } private void pictureBoxCredits_Click(object sender, EventArgs e) { string message = "Application based on Dan Letecky's Desktop Search\n"; message += " http://www.codeproject.com/KB/office/desktopsearch1.aspx\n"; message += "\n"; message += "IFilter implementation from alex_zero\n"; message += " http://www.codeproject.com/KB/cs/IFilterReader.aspx"; MessageBox.Show(message, "Credits", MessageBoxButtons.OK, MessageBoxIcon.Information); } private AutoCompleteStringCollection LoadSearchTerms() { AutoCompleteStringCollection result = new AutoCompleteStringCollection(); if (File.Exists(searchTermsPath)) { try { using (var fileReader = new StreamReader(searchTermsPath)) { string line; while ((line = fileReader.ReadLine()) != null) { result.Add(line); } } } catch (Exception) { MessageBox.Show("Unable to load search history", "History", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } return result; } private void SaveSearchTerms(AutoCompleteStringCollection items) { try { using (StreamWriter writer = new StreamWriter(searchTermsPath)) { foreach (string item in items) { writer.WriteLine(item); } } } catch (Exception) { MessageBox.Show("Unable to save search history", "History", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void listViewResults_MouseUp(object sender, MouseEventArgs e) { if (explorerMenu == false || e.Button != System.Windows.Forms.MouseButtons.Right) { return; } ListViewHitTestInfo hitTest = listViewResults.HitTest(e.X, e.Y); if (hitTest.Item == null) { return; } string path = (string)hitTest.Item.Tag; // Loop through each search directory and see if the file exists foreach (string searchDir in searchDirs) { string fullPath = Path.Combine(searchDir, path); if (File.Exists(fullPath)) { FileInfo fi = new FileInfo(fullPath); Peter.ShellContextMenu contextMenu = new Peter.ShellContextMenu(); Point contextMenuLocation = listViewResults.PointToScreen(new Point(e.X, e.Y)); contextMenu.ShowContextMenu(new FileInfo[] { fi }, contextMenuLocation); return; } } } private void listViewResults_ColumnClick(object sender, ColumnClickEventArgs e) { ListViewItemComparer.ColumnDataType columnDataType = ListViewItemComparer.ColumnDataType.Generic; if (e.Column == colHeaderModified.Index) { columnDataType = ListViewItemComparer.ColumnDataType.DateTime; } else if (e.Column == columnHeaderScore.Index) { columnDataType = ListViewItemComparer.ColumnDataType.Number; } else { columnDataType = ListViewItemComparer.ColumnDataType.Generic; } if (listViewResults.ListViewItemSorter == null) { listViewResults.ListViewItemSorter = new ListViewItemComparer( listViewResults.Columns.Count, e.Column, ListSortDirection.Ascending, columnDataType); // when you set ListViewItemSorter, sorting happens automatically } else { ((ListViewItemComparer)listViewResults.ListViewItemSorter).SetColumnAndType(e.Column, columnDataType); listViewResults.Sort(); // must explicitly sort in this case } } private void buttonToday_Click(object sender, EventArgs e) { dateTimePickerFrom.Value = DateTime.Today; } } }
40.753584
246
0.55539
[ "Apache-2.0" ]
Remotion/dropout_search
frmMain.cs
59,704
C#
using System.Web; using System.Web.Mvc; namespace Web.MVC.Full { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.928571
80
0.649057
[ "MIT" ]
RohithKumbharkar/raven-identity
Web.MVC.Full/App_Start/FilterConfig.cs
267
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class PathfindingEnumFlagAttributeWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Pathfinding.EnumFlagAttribute); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { Pathfinding.EnumFlagAttribute gen_ret = new Pathfinding.EnumFlagAttribute(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Pathfinding.EnumFlagAttribute constructor!"); } } }
20.835294
107
0.606437
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/PathfindingEnumFlagAttributeWrap.cs
1,773
C#
using System; using Microsoft.Extensions.Caching.Memory; namespace GovUk.Education.ExploreEducationStatistics.Data.Model.Repository { public class DataServiceMemoryCache<TItem> { private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions()); public TItem GetOrCreate(object key, Func<ICacheEntry, TItem> factory) { return _cache.GetOrCreate(key, factory); } public TItem GetOrDefault(object key) { return _cache.Get<TItem>(key); } public TItem Set(object key, TItem item) { return _cache.Set(key, item); } public TItem Set(object key, TItem item, TimeSpan absoluteExpirationRelativeToNow) { return _cache.Set(key, item, absoluteExpirationRelativeToNow); } } }
28.233333
90
0.643447
[ "MIT" ]
dfe-analytical-services/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Data.Model/Repository/DataServiceMemoryCache.cs
849
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; using Pulumi.Utilities; namespace Pulumi.Yandex { public static class GetFunctionScalingPolicy { public static Task<GetFunctionScalingPolicyResult> InvokeAsync(GetFunctionScalingPolicyArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetFunctionScalingPolicyResult>("yandex:index/getFunctionScalingPolicy:getFunctionScalingPolicy", args ?? new GetFunctionScalingPolicyArgs(), options.WithVersion()); public static Output<GetFunctionScalingPolicyResult> Invoke(GetFunctionScalingPolicyInvokeArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.Invoke<GetFunctionScalingPolicyResult>("yandex:index/getFunctionScalingPolicy:getFunctionScalingPolicy", args ?? new GetFunctionScalingPolicyInvokeArgs(), options.WithVersion()); } public sealed class GetFunctionScalingPolicyArgs : Pulumi.InvokeArgs { [Input("functionId", required: true)] public string FunctionId { get; set; } = null!; [Input("policies")] private List<Inputs.GetFunctionScalingPolicyPolicyArgs>? _policies; public List<Inputs.GetFunctionScalingPolicyPolicyArgs> Policies { get => _policies ?? (_policies = new List<Inputs.GetFunctionScalingPolicyPolicyArgs>()); set => _policies = value; } public GetFunctionScalingPolicyArgs() { } } public sealed class GetFunctionScalingPolicyInvokeArgs : Pulumi.InvokeArgs { [Input("functionId", required: true)] public Input<string> FunctionId { get; set; } = null!; [Input("policies")] private InputList<Inputs.GetFunctionScalingPolicyPolicyInputArgs>? _policies; public InputList<Inputs.GetFunctionScalingPolicyPolicyInputArgs> Policies { get => _policies ?? (_policies = new InputList<Inputs.GetFunctionScalingPolicyPolicyInputArgs>()); set => _policies = value; } public GetFunctionScalingPolicyInvokeArgs() { } } [OutputType] public sealed class GetFunctionScalingPolicyResult { public readonly string FunctionId; /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; public readonly ImmutableArray<Outputs.GetFunctionScalingPolicyPolicyResult> Policies; [OutputConstructor] private GetFunctionScalingPolicyResult( string functionId, string id, ImmutableArray<Outputs.GetFunctionScalingPolicyPolicyResult> policies) { FunctionId = functionId; Id = id; Policies = policies; } } }
36.678571
220
0.689387
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-yandex
sdk/dotnet/GetFunctionScalingPolicy.cs
3,081
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using Azure.ResourceManager; namespace Azure.ResourceManager.AppService.Models { /// <summary> Response for a migration of app content request. </summary> public partial class StorageMigrationResponse : ProxyOnlyResource { /// <summary> Initializes a new instance of StorageMigrationResponse. </summary> public StorageMigrationResponse() { } /// <summary> Initializes a new instance of StorageMigrationResponse. </summary> /// <param name="id"> The id. </param> /// <param name="name"> The name. </param> /// <param name="type"> The type. </param> /// <param name="kind"> Kind of resource. </param> /// <param name="operationId"> When server starts the migration process, it will return an operation ID identifying that particular migration operation. </param> internal StorageMigrationResponse(ResourceIdentifier id, string name, ResourceType type, string kind, string operationId) : base(id, name, type, kind) { OperationId = operationId; } /// <summary> When server starts the migration process, it will return an operation ID identifying that particular migration operation. </summary> public string OperationId { get; } } }
40.514286
169
0.676305
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Generated/Models/StorageMigrationResponse.cs
1,418
C#
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace MobileRepairMT.Configuration { public class RolesConfiguration : IEntityTypeConfiguration<IdentityRole> { public void Configure(EntityTypeBuilder<IdentityRole> builder) { builder.HasData ( new IdentityRole { Name = "User", NormalizedName = "USER" }, new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" } ); } } }
26.296296
76
0.51831
[ "MIT" ]
PSButlerII/MobileRepairVMT
eCommerceStarterCode/Configuration/RolesConfiguration.cs
712
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MeowDSIO { public partial class DSBinaryWriter : BinaryWriter { private static Encoding ShiftJISEncoding = Encoding.GetEncoding("shift_jis"); // Now with 100% less 0DD0ADDE public static readonly byte[] PLACEHOLDER_32BIT = new byte[] { 0xDE, 0xAD, 0xD0, 0x0D }; public string FileName { get; private set; } public long Position { get => BaseStream.Position; set => BaseStream.Position = value; } public long Length => BaseStream.Length; public void Goto(long absoluteOffset) => BaseStream.Seek(absoluteOffset, SeekOrigin.Begin); public void Jump(long relativeOffset) => BaseStream.Seek(relativeOffset, SeekOrigin.Current); private Stack<long> StepStack = new Stack<long>(); private Stack<PaddedRegion> PaddedRegionStack = new Stack<PaddedRegion>(); private Dictionary<string, long> MarkerDict = new Dictionary<string, long>(); public bool BigEndian = false; public char StrEscapeChar = (char)0; public void StepIn(long offset) { StepStack.Push(Position); Goto(offset); } public void StepOut() { if (StepStack.Count == 0) throw new InvalidOperationException("You cannot step out unless StepIn() was previously called on an offset."); Goto(StepStack.Pop()); } public void StepIntoPaddedRegion(long length, byte padding) { PaddedRegionStack.Push(new PaddedRegion(Position, length, padding)); } public void StepOutOfPaddedRegion() { if (PaddedRegionStack.Count == 0) throw new InvalidOperationException("You cannot step out of padded region unless inside of one " + $"as a result of previously calling {nameof(StepIntoPaddedRegion)}()."); var deepestPaddedRegion = PaddedRegionStack.Pop(); deepestPaddedRegion.AdvanceWriterToEnd(this); } public void DoAt(long offset, Action doAction) { StepIn(offset); doAction(); StepOut(); } public long Placeholder(string markerName = null) { var label = Label(markerName); Write(PLACEHOLDER_32BIT); return label; } public long Label(string markerName = null) { var labelOffset = Position; if (markerName != null) { MarkerDict.Add(markerName, labelOffset); } return labelOffset; } public void Goto(string markerName) { if (markerName == null) throw new ArgumentNullException(nameof(markerName)); if (MarkerDict.ContainsKey(markerName)) { Position = MarkerDict[markerName]; } else { throw new ArgumentException("No DSBinaryWriter Marker was registered " + $"with the name '{markerName}'.", nameof(markerName)); } } public void Replace(string markerName, int replaceMarkerVal) { StepIn(MarkerDict[markerName]); Write(replaceMarkerVal); StepOut(); } public void PointToHere(string markerName) { Replace(markerName, (int)Position); } } }
30.649573
127
0.585611
[ "MIT" ]
Meowmaritus/DSFBX
MeowDSIO/MeowDSIO/DSBinaryWriter.Utils.cs
3,588
C#
using Cake.Common; using Cake.Common.Build; using Cake.Common.IO; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Frosting; namespace Build { [TaskName("PushLocally")] [IsDependentOn(typeof(BuildAndPackTask))] public sealed class PushLocallyTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { foreach (var path in context.GetFiles(System.IO.Path.Combine(context.PackagesFolder.FullPath, "*.nupkg"))) { var settings = new ProcessSettings() .UseWorkingDirectory(".") .WithArguments(builder => builder .Append("push") .AppendSwitchQuoted("-source", Constants.LocalNugetDirectory) .AppendQuoted(path.FullPath)); context.StartProcess(context.Tools.Resolve("nuget.exe"), settings); } base.Run(context); } public override bool ShouldRun(BuildContext context) { if (!context.BuildSystem().IsLocalBuild) { context.Log.Information($"Skipped {nameof(PushLocallyTask)}, since task is not running on a developer machine."); return false; } if (!context.DirectoryExists(Constants.LocalNugetDirectory)) { context.Log.Information($"Skipped {nameof(PushLocallyTask)}, since there is no local directory ({Constants.LocalNugetDirectory}) to push nuget packages to."); return false; } if (!context.FileExists(context.Tools.Resolve("nuget.exe"))) { context.Log.Information($"Skipped {nameof(PushLocallyTask)}, since there is no nuget.exe registered with cake"); return false; } if (context.GetFiles(System.IO.Path.Combine(context.PackagesFolder.FullPath, "*.nupkg")).Count == 0) { context.Log.Information($"Skipped {nameof(PushLocallyTask)}, since there is no nupkg file in {context.PackagesFolder.FullPath}"); return false; } return base.ShouldRun(context); } } }
36.225806
174
0.590828
[ "MIT" ]
Insire/Monstercat.Net
build/Tasks/PushLocallyTask.cs
2,246
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Controle_Veiculos2.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.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; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] [global::System.Configuration.DefaultSettingValueAttribute("Data Source=|DataDirectory|\\Sistema.sdf")] public string SistemaConnectionString { get { return ((string)(this["SistemaConnectionString"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] [global::System.Configuration.DefaultSettingValueAttribute("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\SistemaBuggy.mdb;Per" + "sist Security Info=True")] public string SistemaBuggyConnectionString { get { return ((string)(this["SistemaBuggyConnectionString"])); } } } }
46.979167
153
0.637694
[ "MIT" ]
sthefanysoares/Controle_Veiculos
Controle_Veiculos2/Properties/Settings.Designer.cs
2,257
C#
namespace HardwareStore.Data.Models { using Microsoft.AspNet.Identity.EntityFramework; public class Role : IdentityRole<int, UserRole> { public Role() { } public Role(string name) { Name = name; } } }
17.4375
52
0.541219
[ "MIT" ]
TodorStamenov/HardwareStore
HardwareStore.Data/Models/Role.cs
281
C#
using System.Collections.Generic; using System.Text.Json; namespace ByteDev.PostmanEcho.Json { internal static class JsonPropertyExtensions { public static string GetPropertyString(this JsonProperty source) { if (source.Value.ValueKind == JsonValueKind.Null || source.Value.ValueKind == JsonValueKind.Undefined) return null; if (source.Value.ValueKind == JsonValueKind.String) return source.Value.GetString(); return source.Value.GetRawText(); } public static bool GetPropertyBool(this JsonProperty source) { if (source.Value.ValueKind != JsonValueKind.True) return false; return source.Value.GetBoolean(); } public static IDictionary<string, string> GetPropertyDictionary(this JsonProperty source) { if (source.Value.ValueKind == JsonValueKind.Null || source.Value.ValueKind == JsonValueKind.Undefined) return new Dictionary<string, string>(); return source.Value.GetJsonAs<Dictionary<string, string>>(); } } }
32.027027
97
0.616034
[ "MIT" ]
ByteDev/ByteDev.PostmanEcho
src/ByteDev.PostmanEcho/Json/JsonPropertyExtensions.cs
1,187
C#
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Dapper; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; namespace AJ3.Core.Data { public abstract class DbFactoryBase { private readonly IConfiguration _config; internal string DbConnectionString => _config.GetConnectionString("SQLDBConnectionString"); public DbFactoryBase(IConfiguration config) { _config = config; } internal IDbConnection DbConnection => new SqlConnection(DbConnectionString); public virtual async Task<IEnumerable<T>> DbQueryAsync<T>(string sql, object parameters = null, CommandType commandType = CommandType.StoredProcedure) { using var dbCon = DbConnection; return parameters == null ? await dbCon.QueryAsync<T>(sql, commandType) : await dbCon.QueryAsync<T>(sql, parameters, commandType: commandType); } public virtual async Task<T> DbQuerySingleAsync<T>(string sql, object parameters, CommandType commandType = CommandType.StoredProcedure) { using var dbCon = DbConnection; return await dbCon.QueryFirstOrDefaultAsync<T>(sql, parameters, commandType: commandType); } public virtual async Task<bool> DbExecuteAsync<T>(string sql, object parameters, CommandType commandType = CommandType.StoredProcedure) { using var dbCon = DbConnection; return await dbCon.ExecuteAsync(sql, parameters, commandType: commandType) > 0; } public virtual async Task<bool> DbExecuteScalarAsync(string sql, object parameters) { using var dbCon = DbConnection; return await dbCon.ExecuteScalarAsync<bool>(sql, parameters); } public virtual async Task<T> DbExecuteScalarDynamicAsync<T>(string sql, object parameters = null) { using var dbCon = DbConnection; return parameters == null ? await dbCon.ExecuteScalarAsync<T>(sql) : await dbCon.ExecuteScalarAsync<T>(sql, parameters); } public virtual async Task<(IEnumerable<T> Data, TRecordCount RecordCount)> DbQueryMultipleAsync<T, TRecordCount>(string sql, object parameters = null,CommandType commandType= CommandType.StoredProcedure) { IEnumerable<T> data; TRecordCount totalRecords; using (var dbCon = DbConnection) { using var results = await dbCon.QueryMultipleAsync(sql, parameters,commandType:commandType); data = await results.ReadAsync<T>(); totalRecords = await results.ReadFirstOrDefaultAsync<TRecordCount>(); } return (data, totalRecords); } public virtual async Task<(TData1 Data1,TData2 Data2 ,TData3 Data3)> DbQueryMultipleAsync<TData1,TData2, TData3>(string sql, object parameters = null,CommandType commandType= CommandType.StoredProcedure) { TData1 data1; TData2 data2; TData3 data3; using (var dbCon = DbConnection) { using var results = await dbCon.QueryMultipleAsync(sql, parameters,commandType:commandType); data1 = await results.ReadSingleAsync<TData1>(); data2 = await results.ReadSingleAsync<TData2>(); data3 = await results.ReadSingleAsync<TData3>(); } return (data1,data2, data3); } public virtual async Task<(TData1 Data1,TData2 Data2 ,IEnumerable<TData3> Data3,IEnumerable<TData4> Data4)> DbQueryMultipleAsync<TData1,TData2, TData3,TData4>(string sql, object parameters = null,CommandType commandType= CommandType.StoredProcedure) { TData1 data1; TData2 data2; IEnumerable<TData3> data3; IEnumerable<TData4> data4; using (var dbCon = DbConnection) { using var results = await dbCon.QueryMultipleAsync(sql, parameters,commandType:commandType); data1 = await results.ReadSingleAsync<TData1>(); data2 = await results.ReadSingleAsync<TData2>(); data3 = await results.ReadAsync<TData3>(); data4 = await results.ReadAsync<TData4>(); } return (data1,data2, data3,data4); } public virtual async Task<(TResponse Result, T Data)> DbExecuteSpMultipleAsync<TResponse, T>(string sql, object parameters = null) { T data; TResponse response; using (var dbCon = DbConnection) { using var results = await dbCon.QueryMultipleAsync(sql, parameters, commandType: CommandType.StoredProcedure); response = await results.ReadSingleAsync<TResponse>(); data = await results.ReadSingleAsync<T>(); } return (response, data); } } }
42.279661
257
0.641411
[ "MIT" ]
DennisPitallano/DSSMS
AJ3/AJ3.Core/Data/DbFactoryBase.cs
4,991
C#
// // Authors: // Marek Habersack (mhabersack@novell.com) // // (C) 2010 Novell, Inc http://novell.com/ // // // 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.IO; using System.Web.Util; using StandAloneRunnerSupport; using StandAloneTests; using NUnit.Framework; using StandAloneTests.RequestValidator.Generated; namespace StandAloneTests.RequestValidator { class RequestValidatorCallSet { List <Dictionary <string, object>> callSets; public List <Dictionary <string, object>> CallSets { get { if (callSets == null) callSets = new List <Dictionary <string, object>> (); return callSets; } } public string Name { get; protected set; } protected void RegisterCallSet (Dictionary <string, object> callSet) { if (callSet == null || callSet.Count == 0) return; CallSets.Add (callSet); } public bool ContainsCallSet (Dictionary <string, object> callSet) { foreach (var dict in CallSets) if (DictionariesEqual (dict, callSet)) return true; return false; } bool DictionariesEqual (Dictionary <string, object> first, Dictionary <string, object> second) { if (first == null ^ second == null) return false; if (first.Count != second.Count) return false; object left, right; foreach (string s in first.Keys) { if (s == "calledFrom") continue; if (!second.TryGetValue (s, out left)) return false; right = first [s]; if (left == null ^ right == null) return false; if (left == null) continue; if (!left.Equals (right)) return false; } return true; } } static class RequestValidatorCallSetContainer { public static List <RequestValidatorCallSet> CallSets { get; private set; } static RequestValidatorCallSetContainer () { CallSets = new List <RequestValidatorCallSet> (); } public static RequestValidatorCallSet GetCallSet (string name) { foreach (RequestValidatorCallSet cs in CallSets) if (String.Compare (cs.Name, name, StringComparison.Ordinal) == 0) return cs; return null; } public static void Register (RequestValidatorCallSet callSet) { CallSets.Add (callSet); } } [TestCase ("RequestValidator", "4.0 extensible request validation tests.")] public sealed class RequestValidatorTests : ITestCase { public string PhysicalPath { get { return Path.Combine (Consts.BasePhysicalDir, "RequestValidator"); } } public string VirtualPath { get { return "/"; } } public bool SetUp (List <TestRunItem> runItems) { GeneratedCallSets.Register (); runItems.Add (new TestRunItem ("Default.aspx", Default_Aspx)); runItems.Add (new TestRunItem ("Default.aspx?key=invalid<script>value</script>", Default_Aspx_Script)); return true; } string SummarizeCallSet (Dictionary <string, object> callSet) { return String.Format (@" URL: {0} Context present: {1} Value: {2} Request validation source: {3} Collection key: {4} Validation failure index: {5} Return value: {6} ", callSet ["rawUrl"], callSet ["context"], callSet ["value"], (int)callSet ["requestValidationSource"], callSet ["collectionKey"], callSet ["validationFailureIndex"], callSet ["returnValue"]); } void Default_Aspx (string result, TestRunItem runItem) { if (runItem == null) throw new ArgumentNullException ("runItem"); CompareCallSets (runItem, "000"); } void Default_Aspx_Script (string result, TestRunItem runItem) { if (runItem == null) throw new ArgumentNullException ("runItem"); CompareCallSets (runItem, "001"); } void CompareCallSets (TestRunItem runItem, string name) { var dict = runItem.TestRunData as List <Dictionary <string, object>>; if (dict == null || dict.Count == 0) Assert.Fail ("No call data recorded."); RequestValidatorCallSet cs = RequestValidatorCallSetContainer.GetCallSet (name); if (cs == null) Assert.Fail ("Call set \"{0}\" not found.", name); foreach (Dictionary <string, object> calls in dict) { if (!cs.ContainsCallSet (calls)) Assert.Fail ("{0}: call sequence not found:{1}{2}", name, Environment.NewLine, SummarizeCallSet (calls)); } } } }
26.124402
110
0.673443
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.Web/Test/standalone-tests/RequestValidator.cs
5,460
C#
using System; using SemVer.Net.Core.Helpers; namespace SemVer.Net.Core { public struct SemanticVersion : IEquatable<SemanticVersion>, IComparable<SemanticVersion> { public SemanticVersion(string versionString) { int major, minor, patch; PreReleaseIdentifier? preRelease; VersionMetadata? metadata; if (!VersionHelpers.TryParseVersion(versionString, out major,out minor,out patch, out preRelease, out metadata)) { throw new ArgumentException($"Cannot parse semantic version '{versionString}'"); } Major = major; Minor = minor; Patch = patch; PreRelease = preRelease; Metadata = metadata; } public SemanticVersion(int major, int minor, int patch, PreReleaseIdentifier? preRelease = null, VersionMetadata? metadata = null) { Major = major; Minor = minor; Patch = patch; if(preRelease.HasValue && preRelease.Value == default(PreReleaseIdentifier)) { throw new ArgumentException("Pre release identifier cannot be empty"); } PreRelease = preRelease; if(metadata.HasValue && metadata.Value == default(VersionMetadata)) { throw new ArgumentException("Metadata cannot be empty"); } Metadata = metadata; } public int Major { get; } public int Minor { get; } public int Patch { get; } public PreReleaseIdentifier? PreRelease { get; } public VersionMetadata? Metadata { get; } public static bool operator == (SemanticVersion operand1, SemanticVersion operand2) { return operand1.Equals(operand2); } public static bool operator != (SemanticVersion operand1, SemanticVersion operand2) { return !operand1.Equals(operand2); } public static bool operator > (SemanticVersion operand1, SemanticVersion operand2) { return operand1.CompareTo(operand2) == 1; } public static bool operator < (SemanticVersion operand1, SemanticVersion operand2) { return operand1.CompareTo(operand2) == -1; } public static bool operator >= (SemanticVersion operand1, SemanticVersion operand2) { return operand1.CompareTo(operand2) >= 0; } public static bool operator <= (SemanticVersion operand1, SemanticVersion operand2) { return operand1.CompareTo(operand2) <= 0; } public static implicit operator string(SemanticVersion version) { return version.ToString(); } public static implicit operator SemanticVersion(string versionString) { return new SemanticVersion(versionString); } public override string ToString() { return PreRelease.HasValue? $"{Major}.{Minor}.{Patch}-{PreRelease.ToString()}": $"{Major}.{Minor}.{Patch}"; } public override int GetHashCode() { return Major + Minor + Patch + (PreRelease.HasValue? PreRelease.GetHashCode(): 0); } public override bool Equals(object obj) { return obj is SemanticVersion ? Equals((SemanticVersion)obj) : false; } public bool Equals(SemanticVersion other) { return this.Major == other.Major && this.Minor == other.Minor && this.Patch == other.Patch && (this.PreRelease.HasValue ? other.PreRelease.HasValue && this.PreRelease.Value.Equals(other.PreRelease.Value) : !other.PreRelease.HasValue); } public int CompareTo(SemanticVersion other) { return this.Major > other.Major? 1: this.Major < other.Major? -1: this.Minor > other.Minor? 1: this.Minor < other.Minor? -1: this.Patch > other.Patch? 1: this.Patch < other.Patch? -1: (this.PreRelease.HasValue && !other.PreRelease.HasValue)? -1: (!this.PreRelease.HasValue && other.PreRelease.HasValue)? 1: (!this.PreRelease.HasValue && !other.PreRelease.HasValue)? 0: this.PreRelease.Value.CompareTo(other.PreRelease.Value); } } }
27.881119
96
0.65237
[ "MIT" ]
SemVer-Net/SemVerNet
src/SemVer.Net.Core/SemanticVersion.cs
3,989
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ItemFactory { class Program { static void Main(string[] args) { } } }
14.625
39
0.645299
[ "MIT" ]
ayushkhemka/NoSQL_database
ItemFactory/Program.cs
236
C#
using MTConnect.Observations; using MTConnect.Streams; using MTConnect.Clients.Rest; //var agentUrl = "https://smstestbed.nist.gov/vds/"; //var agentUrl = "https://smstestbed.nist.gov/vds/GFAgie01"; var agentUrl = "localhost:5000"; //var agentUrl = "localhost:5006"; //var agentUrl = "mtconnect.trakhound.com"; var client = new MTConnect.Clients.Rest.MTConnectClient(agentUrl); client.Interval = 500; client.Heartbeat = 10000; //client.CurrentOnly = true; client.OnProbeReceived += (s, doc) => { Console.WriteLine($"ProbeReceived : {doc.GetDataItems().Count()} DataItems"); }; client.OnCurrentReceived += ObservationsReceived; client.OnSampleReceived += ObservationsReceived; client.Start(); void ObservationsReceived(object sender, IStreamsResponseDocument document) { Console.WriteLine($"{document.GetObservations().Count()} : ObservationsReceived"); //if (document.Streams != null) //{ // foreach (var deviceStream in document.Streams) // { // Console.WriteLine($"{deviceStream.Name} : {deviceStream.Uuid}"); // Console.WriteLine("----------"); // if (deviceStream.ComponentStreams != null) // { // foreach (var componentStream in deviceStream.ComponentStreams) // { // Console.WriteLine($"{componentStream.ComponentType} : {componentStream.ComponentId} : {componentStream.Name}"); // Console.WriteLine($"{componentStream.Observations.Count()} Observations"); // Console.WriteLine("----------"); // //foreach (var observation in componentStream.SampleValues) // //{ // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} = {observation.CDATA} @ {observation.Timestamp.ToString("o")}"); // //} // //foreach (var observation in componentStream.SampleDataSets) // //{ // // foreach (var entry in observation.Entries) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {entry.Key} = {entry.Value} @ {observation.Timestamp.ToString("o")}"); // // } // //} // //foreach (var observation in componentStream.SampleTables) // //{ // // foreach (var entry in observation.Entries) // // { // // foreach (var cell in entry.Cells) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {entry.Key} : {cell.Key} = {cell.Value} @ {observation.Timestamp.ToString("o")}"); // // } // // } // //} // //foreach (var observation in componentStream.SampleTimeSeries) // //{ // // foreach (var sample in observation.Samples) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {sample} @ {observation.Timestamp.ToString("o")}"); // // } // //} // //foreach (var observation in componentStream.EventValues) // //{ // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} = {observation.CDATA} @ {observation.Timestamp.ToString("o")}"); // //} // //foreach (var observation in componentStream.EventDataSets) // //{ // // foreach (var entry in observation.Entries) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {entry.Key} = {entry.Value} @ {observation.Timestamp.ToString("o")}"); // // } // //} // //foreach (var observation in componentStream.EventTables) // //{ // // foreach (var entry in observation.Entries) // // { // // foreach (var cell in entry.Cells) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {entry.Key} : {cell.Key} = {cell.Value} @ {observation.Timestamp.ToString("o")}"); // // } // // } // //} // //foreach (var observation in componentStream.Conditions) // //{ // // foreach (var value in observation.Values) // // { // // Console.WriteLine($"{observation.Representation} : {observation.DataItemId} : {value.Key} = {value.Value} @ {observation.Timestamp.ToString("o")}"); // // } // //} // Console.WriteLine(); // } // } // } //} } Console.ReadLine();
44.635593
196
0.49326
[ "Apache-2.0" ]
TrakHound/MTConnect
testing/Client-Test-01/Program - Copy (2).cs
5,269
C#
using products_api.Misc; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace products_api.Models { [Table("Network")] public class Network : BaseModel { [Required] public string Name { get; set; } = string.Empty; public int Position { get; set; } = DefaultValues.Position; // Detail table public virtual IEnumerable<NetworkBand> NetworkBands { get; set; } } }
26.333333
74
0.679325
[ "MIT" ]
saqibrazzaq/SalesSystem
src/services/products-api/Models/Network.cs
476
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 frauddetector-2019-11-15.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.FraudDetector.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.FraudDetector.Model.Internal.MarshallTransformations { /// <summary> /// GetEntityTypes Request Marshaller /// </summary> public class GetEntityTypesRequestMarshaller : IMarshaller<IRequest, GetEntityTypesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetEntityTypesRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetEntityTypesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.FraudDetector"); string target = "AWSHawksNestServiceFacade.GetEntityTypes"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-11-15"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetMaxResults()) { context.Writer.WritePropertyName("maxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("nextToken"); context.Writer.Write(publicRequest.NextToken); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetEntityTypesRequestMarshaller _instance = new GetEntityTypesRequestMarshaller(); internal static GetEntityTypesRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetEntityTypesRequestMarshaller Instance { get { return _instance; } } } }
36.316239
144
0.597788
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/FraudDetector/Generated/Model/Internal/MarshallTransformations/GetEntityTypesRequestMarshaller.cs
4,249
C#
using System; namespace WebApi.Shared { [Serializable] public class LoginResult { public string AccessToken { get; set; } } }
13.818182
47
0.625
[ "MIT" ]
VitaliyFilippov2012/Vehicle-logbook
Server_Asp.Net/FinanceCarManager/WebApi/Shared/LoginResult.cs
154
C#
using CoreRCON; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace FactorioIP { class RConSocket : EndpointFrameSocket { Queue<PackedFrame> sendbuf = new Queue<PackedFrame>(); string host; UInt16 port; string password; RCON rcon; bool rconAlive; public Action<UnpackedFrame> OnReceive { get; set; } public Action<RConSocket> OnConnect { get; set; } public Action<RConSocket> OnDisconnect { get; set; } public RConSocket(string host, UInt16 port, string password, Action<RConSocket> OnConnect = null, Action<RConSocket> OnDisconnect = null ) { this.host = host; this.port = port; this.password = password; this.OnConnect = OnConnect; this.OnDisconnect = OnDisconnect; StartupTask(); } async void StartupTask() { while (rcon == null) { try { rcon = new RCON(host, port, password); } catch (System.AggregateException) { Console.WriteLine($"{Name} failed to connect"); } if (rcon != null) { rcon.OnDisconnected += onDisconnected; //rcon.SendCommandAsync("/RoutingReset").Wait(); ID = Int32.Parse(await rcon.SendCommandAsync("/RoutingGetID")); var json = new JavaScriptSerializer(); string mapstr = await rcon.SendCommandAsync($"/RoutingGetMap"); mapstr = mapstr.TrimEnd('\0', '\n'); var split = mapstr.IndexOf(':'); var len = UInt32.Parse(mapstr.Substring(0,split)); mapstr = mapstr.Substring(split+1); if (mapstr.Length != len) { throw new Exception("Map Truncated"); } using (var ms = new System.IO.MemoryStream(Convert.FromBase64String(mapstr))) using (var gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) using (var sr = new System.IO.StreamReader(gz)) { var mapjson = sr.ReadToEnd(); var map = json.Deserialize<IEnumerable<Dictionary<string, string>>>(mapjson); var siglist = map.Select(d => new SignalMap.SignalID { type = (string)d["type"], name = (string)d["name"] }); this.Map = new SignalMap(siglist); } rconAlive = true; ReceiveTask(); SendTask(); OnConnect?.Invoke(this); } else { // wait 30s Task.Delay(30000).Wait(); } } } void onDisconnected() { // declare it dead... rconAlive = false; OnDisconnect?.Invoke(this); rcon = null; StartupTask(); } public void EnqueueSend(UnpackedFrame packet) { if (rconAlive) { var pframe = packet.Pack(Map); // don't bother sending an empty frame (usually no map, or no map overlap)... if (pframe.payload.Length == 2) return; sendbuf.Enqueue(pframe); } } public SignalMap Map { get; private set; } public VarInt ID { get; private set; } public string Name => $"RCON:{host}:{port}:{ID:X8}"; public override string ToString() => Name; async void ReceiveTask() { while (rconAlive) { await Task.Delay(20); var packets = new ArraySegment<byte>(await rcon.SendCommandAsync(Encoding.UTF8.GetBytes("/RoutingTXBuff\0"))); VarInt size; while (packets.Count() > 2) { (size, packets) = VarInt.Take(packets); var packet = new ArraySegment<byte>(packets.Array, packets.Offset, size); var packetframe = new PackedFrame(packet, Map).Unpack(); packetframe.origin = this; OnReceive?.Invoke(packetframe); packets = new ArraySegment<byte>(packets.Array, packets.Offset + size, packets.Count - size); } } } async void SendTask() { while (rconAlive) { if (sendbuf.Count > 0) { var payload = sendbuf.Dequeue(); var bytes = Encoding.UTF8.GetBytes("/RoutingRX ").Concat(payload.Encode()).Concat(new byte[] { 0 }).ToArray(); try { await rcon.SendCommandAsync(bytes); } catch (System.Net.Sockets.SocketException) { onDisconnected(); //throw; } } else { //TODO: better way to wait for new packets? await Task.Delay(1); } } } public bool CanRoute(VarInt dst) { return rconAlive && dst == ID; } } }
31.139037
146
0.466598
[ "MIT" ]
justarandomgeek/FactorioIP
FactorioIP/RConSocket.cs
5,825
C#
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using WebAPI.BLL.Entities; namespace WebAPI.DAL.Configuration { public class AnnouncementConfig : EntityTypeConfiguration<Announcement> { public AnnouncementConfig() { HasKey(a => a.Id); Property(a => a.Title) .IsRequired() .HasMaxLength(150); Property(a => a.Description) .HasMaxLength(255); } } }
22.111111
75
0.60469
[ "MIT" ]
AlexanderVieira/WebApiSocialNetwork-Ioc-Identity
WebAPI.DAL/Configuration/AnnouncementConfig.cs
599
C#
// Copyright (c) Mark Nichols. All Rights Reserved. // Licensed under the MIT License. using Azure.Deployments.Core.Json; using Bicep.Core.Features; using Bicep.Core.Registry.Oci; using Bicep.Core.UnitTests.Registry; using FluentAssertions; using FluentAssertions.Execution; using FluentAssertions.Primitives; using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace Bicep.Core.UnitTests.Assertions { public static class MockRegistryBlobClientExtensions { public static MockRegistryAssertions Should(this MockRegistryBlobClient client) => new MockRegistryAssertions(client); } public class MockRegistryAssertions : ReferenceTypeAssertions<MockRegistryBlobClient, MockRegistryAssertions> { public MockRegistryAssertions(MockRegistryBlobClient client) : base(client) { } protected override string Identifier => nameof(MockRegistryBlobClient); public AndConstraint<MockRegistryAssertions> HaveModule(string tag, Stream expectedModuleContent) { using(new AssertionScope()) { this.Subject.ManifestTags.Should().ContainKey(tag, $"tag '{tag}' should exist"); string manifestDigest = this.Subject.ManifestTags[tag]; this.Subject.Manifests.Should().ContainKey(manifestDigest, $"tag '{tag}' resolves to digest '{manifestDigest}' that should exist"); var manifestBytes = this.Subject.Manifests[manifestDigest]; using var manifestStream = MockRegistryBlobClient.WriteStream(manifestBytes); var manifest = OciSerialization.Deserialize<OciManifest>(manifestStream); var config = manifest.Config; config.MediaType.Should().Be("application/vnd.ms.bicep.module.config.v1+json", "config media type should be correct"); config.Size.Should().Be(0, "config should be empty"); this.Subject.Blobs.Should().ContainKey(config.Digest, "config digest should exist"); var configBytes = this.Subject.Blobs[config.Digest]; configBytes.Should().BeEmpty("config should be empty"); manifest.Layers.Should().HaveCount(1, "modules should have a single layer"); var layer = manifest.Layers.Single(); layer.MediaType.Should().Be("application/vnd.ms.bicep.module.layer.v1+json", "layer media type should be correct"); this.Subject.Blobs.Should().ContainKey(layer.Digest); var layerBytes = this.Subject.Blobs[layer.Digest]; ((long)layerBytes.Length).Should().Be(layer.Size); var actual = MockRegistryBlobClient.WriteStream(layerBytes).FromJsonStream<JToken>(); var expected = expectedModuleContent.FromJsonStream<JToken>(); actual.Should().DeepEqual(expected, "module content should match"); } return new(this); } public AndConstraint<MockRegistryAssertions> OnlyHaveModule(string tag, Stream expectedModuleContent) { using(new AssertionScope()) { this.Subject.Should().HaveModule(tag, expectedModuleContent); // we should only have an empty config blob and the module layer this.Subject.Blobs.Should().HaveCount(2); // there should be one manifest for one module this.Subject.Manifests.Should().HaveCount(1); // there should only be one tag this.Subject.ManifestTags.Should().HaveCount(1); } return new(this); } } }
40.086957
147
0.650759
[ "MIT" ]
marknic/BicepXray
src/Bicep.Core.UnitTests/Assertions/MockRegistryAssertions.cs
3,688
C#
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Steeltoe.Common.Reflection; using System; namespace Steeltoe.CloudFoundry.Connector.SqlServer { /// <summary> /// Assemblies and types used for interacting with Microsoft SQL Server /// </summary> public static class SqlServerTypeLocator { /// <summary> /// Gets SqlConnection from a SQL Server Library /// </summary> /// <exception cref="ConnectorException">When type is not found</exception> public static Type SqlConnection => ReflectionHelpers.FindTypeOrThrow(Assemblies, ConnectionTypeNames, "SqlConnection", "a Microsoft SQL Server ADO.NET assembly"); /// <summary> /// Gets the list of supported SQL Server Client assemblies /// </summary> public static string[] Assemblies { get; internal set; } = new string[] { "System.Data.SqlClient" }; /// <summary> /// Gets the list of SQL Server types that implement IDbConnection /// </summary> public static string[] ConnectionTypeNames { get; internal set; } = new string[] { "System.Data.SqlClient.SqlConnection" }; } }
41.829268
171
0.692711
[ "Apache-2.0" ]
FrancisChung/steeltoe
src/Connectors/src/ConnectorBase/Relational/SqlServer/SqlServerTypeLocator.cs
1,717
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediaconvert-2017-08-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.MediaConvert.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConvert.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteJobTemplate operation /// </summary> public class DeleteJobTemplateResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteJobTemplateResponse response = new DeleteJobTemplateResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return new BadRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return new ConflictException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return new ForbiddenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { return new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException")) { return new TooManyRequestsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonMediaConvertException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DeleteJobTemplateResponseUnmarshaller _instance = new DeleteJobTemplateResponseUnmarshaller(); internal static DeleteJobTemplateResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteJobTemplateResponseUnmarshaller Instance { get { return _instance; } } } }
42.972727
172
0.679501
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/MediaConvert/Generated/Model/Internal/MarshallTransformations/DeleteJobTemplateResponseUnmarshaller.cs
4,727
C#
using System; using System.Security.Cryptography; using WebSocketBridge.Server.Helpers; namespace WebSocketBridge.Server.SingleNode { public class RandomTokenGenerator : IRandomTokenGenerator, IDisposable { private readonly RNGCryptoServiceProvider _cryptoServiceProvider = new RNGCryptoServiceProvider(); public void Dispose() { _cryptoServiceProvider.Dispose(); GC.SuppressFinalize(this); } public string GenerateUrlSafeToken(int tokenSize) { if (tokenSize <= 0) throw new ArgumentOutOfRangeException(nameof(tokenSize)); var bytes = new byte[tokenSize]; _cryptoServiceProvider.GetBytes(bytes); return bytes.ToUrlSafeBase64(); } } }
28.428571
106
0.659548
[ "Apache-2.0" ]
ramondeklein/websocketbridge
WebSocketBridge.Server/SingleNode/RandomTokenGenerator.cs
798
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Mtd.OrderMaker.Server.Entity; namespace Mtd.OrderMaker.Server.Entity.Migrations { [DbContext(typeof(IdentityDbContext))] [Migration("20190409095812_CustomUserData")] partial class CustomUserData { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-rtm-35687"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Mtd.OrderMaker.Server.Areas.Identity.Data.WebAppUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); 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<string>("Title"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Mtd.OrderMaker.Server.Areas.Identity.Data.WebAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Mtd.OrderMaker.Server.Areas.Identity.Data.WebAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Mtd.OrderMaker.Server.Areas.Identity.Data.WebAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Mtd.OrderMaker.Server.Areas.Identity.Data.WebAppUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.62069
95
0.47359
[ "MIT" ]
olegbruev/Mtd.Cpq.Manager
Areas/Identity/Data/Migrations/20190409095812_CustomUserData.Designer.cs
7,802
C#
using SeeMensaWindows.Common.DataModel; using System; using System.Collections.Generic; using Windows.Data.Xml.Dom; using Windows.UI.Notifications; namespace SeeMensaWindows.Common.LiveTile { /// <summary> /// Manager class for simple live tiles. /// </summary> public class LiveTileManager { /// <summary> /// The wide tile type. /// </summary> public TileTemplateType WideTileType { get; set; } /// <summary> /// Tje sqiare tile type. /// </summary> public TileTemplateType SquareTileType { get; set; } /// <summary> /// The data of the active live tiles. /// </summary> public List<LiveTileData> Tiles {get; set; } /// <summary> /// Initializes a new instance of the LiveTileManager. /// </summary> /// <param name="wideTemplate">The wide tile type.</param> /// <param name="squareTemplate">The square tile type.</param> /// <param name="notificationQueueEnabled">Indicates whether the queue is enabled or not.</param> public LiveTileManager(TileTemplateType wideTemplate, TileTemplateType squareTemplate, bool notificationQueueEnabled) { Tiles = new List<LiveTileData>(8); WideTileType = wideTemplate; SquareTileType = squareTemplate; TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(notificationQueueEnabled); } /// <summary> /// Updates the live tiles. /// </summary> public void Update() { var updater = TileUpdateManager.CreateTileUpdaterForApplication(); updater.Clear(); if (Tiles.Count > 0) { for (int i = 0; i < Tiles.Count && i < 5; ++i) { TileNotification otherTile = CreateTileNotification(Tiles[i]); updater.Update(otherTile); } } } /// <summary> /// Creates a new tile notification. /// </summary> /// <param name="index">The index of the Tile.</param> /// <returns></returns> private TileNotification CreateTileNotification(LiveTileData tileData) { XmlDocument wideTile = TileUpdateManager.GetTemplateContent(WideTileType); SetTileData(wideTile, tileData); XmlDocument squareTile = TileUpdateManager.GetTemplateContent(SquareTileType); SetTileData(squareTile, tileData); IXmlNode visualSquare = wideTile.ImportNode(squareTile.GetElementsByTagName("binding").Item(0), true); wideTile.GetElementsByTagName("visual").Item(0).AppendChild(visualSquare); TileNotification tile = new TileNotification(wideTile); tile.Tag = tileData.Header; return tile; } /// <summary> /// Sets the xml data for a live tile. /// </summary> /// <param name="tileXml">The xml tile.</param> /// <param name="tileData">The tile data.</param> private void SetTileData(XmlDocument tileXml, LiveTileData tileData) { XmlNodeList text = tileXml.GetElementsByTagName("text"); text.Item(0).AppendChild(tileXml.CreateTextNode(tileData.Header)); text.Item(1).AppendChild(tileXml.CreateTextNode(tileData.Text)); XmlNodeList images = tileXml.GetElementsByTagName("image"); XmlElement image = (XmlElement)images.Item(0); if (image != null && !String.IsNullOrWhiteSpace(tileData.ImageSource)) { image.SetAttribute("src", tileData.ImageSource); } } } }
37.75
125
0.594172
[ "MIT" ]
b3nk4n/seemensa-windows-app
SeeMensaWindows.Common/LiveTile/LiveTileManager.cs
3,777
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Api.Models; using Microsoft.AspNetCore.Authorization; using System.Runtime.CompilerServices; namespace Api.Controllers { [Route("api/[controller]")] [ApiController] public class HomeworkController : ControllerBase { private readonly ConfluencesContext _context; public HomeworkController(ConfluencesContext context) { _context = context; } // GET: api/Homework [HttpGet] public async Task<ActionResult<IEnumerable<Homework>>> GetHomework() { return await _context.Homework .AsNoTracking() .Include(h => h.Session) .ThenInclude(h => h.SchoolClassRoom) .Include(h => h.HomeworkType) .Include(h => h.Teacher) .Include(h => h.HomeworkStudents) .ToListAsync(); } // GET: api/homework/sessionhomework?sessionId=1&homeworkTypeId=1 [Route("SessionHomework")] [HttpGet] public async Task<ActionResult<IEnumerable<Homework>>> GetSessionHomework(int sessionId, int homeworkTypeId) { return await _context.Homework .AsNoTracking() .Include(h => h.Session) .ThenInclude(h => h.SchoolClassRoom) .Include(h => h.HomeworkType) .Include(h => h.Teacher) .Where(h => h.SessionId == sessionId && h.HomeworkTypeId == homeworkTypeId) .ToListAsync(); } // GET: api/homework/sessionhomework?sessionId=1&homeworkTypeId=1 [Route("SessionHomeworkAll")] [HttpGet] public async Task<ActionResult<IEnumerable<Homework>>> GetSessionHomeworkWithoutType(int sessionId) { return await _context.Homework .AsNoTracking() .Include(h => h.Session) .ThenInclude(h => h.SchoolClassRoom) .Include(h => h.HomeworkType) .Include(h => h.Teacher) .Where(h => h.SessionId == sessionId) .ToListAsync(); } // GET: api/Homework/5 [HttpGet("{id}")] public async Task<ActionResult<Homework>> GetHomework(int id) { var homework = await _context.Homework .Include(h => h.Session) .ThenInclude(h => h.SchoolClassRoom) .Include(h => h.HomeworkType) .Include(h => h.Teacher) .Include(h => h.HomeworkStudents) .ThenInclude(h => h.Student) .Where(h => h.HomeworkId == id) .SingleOrDefaultAsync(); if (homework == null) { return NotFound(); } return homework; } [Authorize(Policy = "Teacher")] // PUT: api/Homework/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutHomework(int id, Homework homework) { if (id != homework.HomeworkId) { return BadRequest(); } _context.Entry(homework).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!HomeworkExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } [Authorize(Policy = "Teacher")] // POST: api/Homework // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<Homework>> PostHomework(Homework homework) { _context.Homework.Add(homework); await _context.SaveChangesAsync(); return CreatedAtAction("GetHomework", new { id = homework.HomeworkId }, homework); } [Authorize(Policy = "Teacher")] // DELETE: api/Homework/5 [HttpDelete("{id}")] public async Task<ActionResult<Homework>> DeleteHomework(int id) { var homework = await _context.Homework.FindAsync(id); if (homework == null) { return NotFound(); } _context.Homework.Remove(homework); await _context.SaveChangesAsync(); return homework; } private bool HomeworkExists(int id) { return _context.Homework.Any(e => e.HomeworkId == id); } } }
36.603774
117
0.481271
[ "Apache-2.0" ]
Schlagadiguenflu/confluences-teletravail
src/Api/Controllers/HomeworkController.cs
5,822
C#
// <copyright file="TagKeyValueFilter.cs" company="App Metrics Contributors"> // Copyright (c) App Metrics Contributors. All rights reserved. // </copyright> using System.Collections.Generic; namespace App.Metrics.Filters { public class TagKeyValueFilter : Dictionary<string, string> { } }
25.333333
78
0.736842
[ "Apache-2.0" ]
8adre/AppMetrics
src/Core/src/App.Metrics.Abstractions/Filters/TagKeyValueFilter.cs
306
C#
using System; using Android.Bluetooth; using Plugin.BLE.Abstractions; using Plugin.BLE.Abstractions.Extensions; using Plugin.BLE.Android.CallbackEventArgs; namespace Plugin.BLE.Android { public interface IGattCallback { event EventHandler<ServicesDiscoveredCallbackEventArgs> ServicesDiscovered; event EventHandler<CharacteristicReadCallbackEventArgs> CharacteristicValueUpdated; event EventHandler<CharacteristicWriteCallbackEventArgs> CharacteristicValueWritten; event EventHandler<DescriptorCallbackEventArgs> DescriptorValueWritten; event EventHandler<DescriptorCallbackEventArgs> DescriptorValueRead; event EventHandler<RssiReadCallbackEventArgs> RemoteRssiRead; event EventHandler ConnectionInterrupted; event EventHandler<MtuRequestCallbackEventArgs> MtuRequested; } public class GattCallback : BluetoothGattCallback, IGattCallback { private readonly Adapter _adapter; private readonly Device _device; public event EventHandler<ServicesDiscoveredCallbackEventArgs> ServicesDiscovered; public event EventHandler<CharacteristicReadCallbackEventArgs> CharacteristicValueUpdated; public event EventHandler<CharacteristicWriteCallbackEventArgs> CharacteristicValueWritten; public event EventHandler<RssiReadCallbackEventArgs> RemoteRssiRead; public event EventHandler ConnectionInterrupted; public event EventHandler<DescriptorCallbackEventArgs> DescriptorValueWritten; public event EventHandler<DescriptorCallbackEventArgs> DescriptorValueRead; public event EventHandler<MtuRequestCallbackEventArgs> MtuRequested; public GattCallback(Adapter adapter, Device device) { _adapter = adapter; _device = device; } public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState) { base.OnConnectionStateChange(gatt, status, newState); if (!gatt.Device.Address.Equals(_device.BluetoothDevice.Address)) { Trace.Message($"Gatt callback for device {_device.BluetoothDevice.Address} was called for device with address {gatt.Device.Address}. This shoud not happen. Please log an issue."); return; } //ToDo ignore just for me Trace.Message($"References of parent device and gatt callback device equal? {ReferenceEquals(_device.BluetoothDevice, gatt.Device).ToString().ToUpper()}"); Trace.Message($"OnConnectionStateChange: GattStatus: {status}"); switch (newState) { // disconnected case ProfileState.Disconnected: // Close GATT regardless, else we can accumulate zombie gatts. CloseGattInstances(gatt); // If status == 19, then connection was closed by the peripheral device (clean disconnect), consider this as a DeviceDisconnected if (_device.IsOperationRequested || (int)status == 19) { Trace.Message("Disconnected by user"); //Found so we can remove it _device.IsOperationRequested = false; _adapter.ConnectedDeviceRegistry.Remove(gatt.Device.Address); if (status != GattStatus.Success && (int)status != 19) { // The above error event handles the case where the error happened during a Connect call, which will close out any waiting asyncs. // Android > 5.0 uses this switch branch when an error occurs during connect Trace.Message($"Error while connecting '{_device.Name}'. Not raising disconnect event."); _adapter.HandleConnectionFail(_device, $"GattCallback error: {status}"); } else { //we already hadled device error so no need th raise disconnect event(happens when device not in range) _adapter.HandleDisconnectedDevice(true, _device); } break; } //connection must have been lost, because the callback was not triggered by calling disconnect Trace.Message($"Disconnected '{_device.Name}' by lost connection"); _adapter.ConnectedDeviceRegistry.Remove(gatt.Device.Address); _adapter.HandleDisconnectedDevice(false, _device); // inform pending tasks ConnectionInterrupted?.Invoke(this, EventArgs.Empty); break; // connecting case ProfileState.Connecting: Trace.Message("Connecting"); break; // connected case ProfileState.Connected: Trace.Message("Connected"); //Check if the operation was requested by the user if (_device.IsOperationRequested) { _device.Update(gatt.Device, gatt); //Found so we can remove it _device.IsOperationRequested = false; } else { //ToDo explore this //only for on auto-reconnect (device is not in operation registry) _device.Update(gatt.Device, gatt); } if (status != GattStatus.Success) { // The above error event handles the case where the error happened during a Connect call, which will close out any waiting asyncs. // Android <= 4.4 uses this switch branch when an error occurs during connect Trace.Message($"Error while connecting '{_device.Name}'. GattStatus: {status}. "); _adapter.HandleConnectionFail(_device, $"GattCallback error: {status}"); CloseGattInstances(gatt); } else { _adapter.ConnectedDeviceRegistry[gatt.Device.Address] = _device; _adapter.HandleConnectedDevice(_device); } break; // disconnecting case ProfileState.Disconnecting: Trace.Message("Disconnecting"); break; } } private void CloseGattInstances(BluetoothGatt gatt) { //ToDO just for me Trace.Message($"References of parnet device gatt and callback gatt equal? {ReferenceEquals(_device._gatt, gatt).ToString().ToUpper()}"); if (!ReferenceEquals(gatt, _device._gatt)) { gatt.Close(); } //cleanup everything else _device.CloseGatt(); } public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { base.OnServicesDiscovered(gatt, status); Trace.Message("OnServicesDiscovered: {0}", status.ToString()); ServicesDiscovered?.Invoke(this, new ServicesDiscoveredCallbackEventArgs()); } public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status) { base.OnCharacteristicRead(gatt, characteristic, status); Trace.Message("OnCharacteristicRead: value {0}; status {1}", characteristic.GetValue().ToHexString(), status); CharacteristicValueUpdated?.Invoke(this, new CharacteristicReadCallbackEventArgs(characteristic)); } public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { base.OnCharacteristicChanged(gatt, characteristic); CharacteristicValueUpdated?.Invoke(this, new CharacteristicReadCallbackEventArgs(characteristic)); } public override void OnCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status) { base.OnCharacteristicWrite(gatt, characteristic, status); Trace.Message("OnCharacteristicWrite: value {0} status {1}", characteristic.GetValue().ToHexString(), status); CharacteristicValueWritten?.Invoke(this, new CharacteristicWriteCallbackEventArgs(characteristic, GetExceptionFromGattStatus(status))); } public override void OnReliableWriteCompleted(BluetoothGatt gatt, GattStatus status) { base.OnReliableWriteCompleted(gatt, status); Trace.Message("OnReliableWriteCompleted: {0}", status); } public override void OnMtuChanged(BluetoothGatt gatt, int mtu, GattStatus status) { base.OnMtuChanged(gatt, mtu, status); Trace.Message("OnMtuChanged to value: {0}", mtu); MtuRequested?.Invoke(this, new MtuRequestCallbackEventArgs(GetExceptionFromGattStatus(status), mtu)); } public override void OnReadRemoteRssi(BluetoothGatt gatt, int rssi, GattStatus status) { base.OnReadRemoteRssi(gatt, rssi, status); Trace.Message("OnReadRemoteRssi: device {0} status {1} value {2}", gatt.Device.Name, status, rssi); RemoteRssiRead?.Invoke(this, new RssiReadCallbackEventArgs(GetExceptionFromGattStatus(status), rssi)); } public override void OnDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, GattStatus status) { base.OnDescriptorWrite(gatt, descriptor, status); Trace.Message("OnDescriptorWrite: {0}", descriptor.GetValue()?.ToHexString()); DescriptorValueWritten?.Invoke(this, new DescriptorCallbackEventArgs(descriptor, GetExceptionFromGattStatus(status))); } public override void OnDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, GattStatus status) { base.OnDescriptorRead(gatt, descriptor, status); Trace.Message("OnDescriptorRead: {0}", descriptor.GetValue()?.ToHexString()); DescriptorValueRead?.Invoke(this, new DescriptorCallbackEventArgs(descriptor, GetExceptionFromGattStatus(status))); } private Exception GetExceptionFromGattStatus(GattStatus status) { Exception exception = null; switch (status) { case GattStatus.Failure: case GattStatus.InsufficientAuthentication: case GattStatus.InsufficientEncryption: case GattStatus.InvalidAttributeLength: case GattStatus.InvalidOffset: case GattStatus.ReadNotPermitted: case GattStatus.RequestNotSupported: case GattStatus.WriteNotPermitted: exception = new Exception(status.ToString()); break; case GattStatus.Success: break; } return exception; } } }
44.666667
195
0.619579
[ "Apache-2.0" ]
Laller88/xamarin-bluetooth-le
Source/Plugin.BLE.Android/GattCallback.cs
11,392
C#
namespace TeamBuilder.Data.Migrations { using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using System; [DbContext(typeof(TeamBuilderContext))] partial class TeamBuilderContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.1-rtm-125") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("TeamBuilder.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CreatorId"); b.Property<string>("Description") .HasMaxLength(250); b.Property<DateTime?>("EndDate"); b.Property<string>("Name") .IsRequired() .HasMaxLength(25); b.Property<DateTime?>("StartDate"); b.HasKey("Id"); b.HasIndex("CreatorId"); b.ToTable("Events"); }); modelBuilder.Entity("TeamBuilder.Models.Invitation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("InvitedUserId"); b.Property<bool>("IsActive"); b.Property<int>("TeamId"); b.HasKey("Id"); b.HasIndex("InvitedUserId"); b.HasIndex("TeamId"); b.ToTable("Invitations"); }); modelBuilder.Entity("TeamBuilder.Models.Team", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Acronym") .IsRequired() .HasMaxLength(3); b.Property<int>("CreatorId"); b.Property<string>("Description") .HasMaxLength(32); b.Property<string>("Name") .IsRequired() .HasMaxLength(25); b.HasKey("Id"); b.HasAlternateKey("Name"); b.HasIndex("CreatorId"); b.ToTable("Teams"); }); modelBuilder.Entity("TeamBuilder.Models.TeamEvent", b => { b.Property<int>("TeamId"); b.Property<int>("EventId"); b.HasKey("TeamId", "EventId"); b.HasIndex("EventId"); b.ToTable("TeamsEvents"); }); modelBuilder.Entity("TeamBuilder.Models.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("Age"); b.Property<string>("FirstName") .HasMaxLength(25); b.Property<int?>("Gender"); b.Property<bool?>("IsDeleted"); b.Property<string>("LastName") .HasMaxLength(25); b.Property<string>("Password") .IsRequired() .HasMaxLength(30); b.Property<string>("Username") .IsRequired() .HasMaxLength(25); b.HasKey("Id"); b.HasAlternateKey("Username"); b.ToTable("Users"); }); modelBuilder.Entity("TeamBuilder.Models.UserTeam", b => { b.Property<int>("UserId"); b.Property<int>("TeamId"); b.HasKey("UserId", "TeamId"); b.HasIndex("TeamId"); b.ToTable("UsersTeams"); }); modelBuilder.Entity("TeamBuilder.Models.Event", b => { b.HasOne("TeamBuilder.Models.User", "Creator") .WithMany("Events") .HasForeignKey("CreatorId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("TeamBuilder.Models.Invitation", b => { b.HasOne("TeamBuilder.Models.User", "InvitedUser") .WithMany("Invitations") .HasForeignKey("InvitedUserId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("Invitations") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("TeamBuilder.Models.Team", b => { b.HasOne("TeamBuilder.Models.User", "Creator") .WithMany("CreatedTeams") .HasForeignKey("CreatorId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("TeamBuilder.Models.TeamEvent", b => { b.HasOne("TeamBuilder.Models.Event", "Event") .WithMany("EventTeams") .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("TeamEvents") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("TeamBuilder.Models.UserTeam", b => { b.HasOne("TeamBuilder.Models.Team", "Team") .WithMany("TeamUsers") .HasForeignKey("TeamId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("TeamBuilder.Models.User", "User") .WithMany("UserTeams") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); #pragma warning restore 612, 618 } } }
32.286408
117
0.436476
[ "MIT" ]
RAstardzhiev/SoftUni-C-
Databases Advanced - Entity Framework Core/Workshop/TeamBuilder.Data/Migrations/TeamBuilderContextModelSnapshot.cs
6,653
C#
using System.Web; using RollbarSharp.Serialization; namespace RollbarSharp.Builders { public class PersonModelBuilder { /// <summary> /// Creates a <see cref="PersonModel"/> from the current HTTP request. /// This will not be able to find the user's email address /// </summary> /// <returns></returns> public static PersonModel CreateFromCurrentRequest() { if (HttpContext.Current == null) return new PersonModel(); return CreateFromHttpRequest(HttpContext.Current.Request); } /// <summary> /// Find just the username from server vars: AUTH_USER, LOGON_USER, REMOTE_USER /// Sets both the ID and Username to this username since ID is required. /// Email address won't be set. /// </summary> /// <param name="request"></param> /// <returns></returns> public static PersonModel CreateFromHttpRequest(HttpRequest request) { var username = request.ServerVariables["AUTH_USER"] ?? request.ServerVariables["LOGON_USER"] ?? request.ServerVariables["REMOTE_USER"]; return new PersonModel {Id = username, Username = username}; } } }
35.289474
88
0.574198
[ "Apache-2.0" ]
richardversluis/RollbarSharp
src/RollbarSharp/Builders/PersonModelBuilder.cs
1,343
C#
namespace DotNetToolkit.Repository.Configuration.Options.Internal { using Caching; using Conventions; using Interceptors; using JetBrains.Annotations; using Logging; using System; using System.Collections.Generic; using System.Linq; using Utility; /// <summary> /// An implementation of <see cref="IRepositoryOptions" />. /// </summary> internal class RepositoryOptions : IRepositoryOptions { #region Fields private Dictionary<Type, Lazy<IRepositoryInterceptor>> _interceptors = new Dictionary<Type, Lazy<IRepositoryInterceptor>>(); private IRepositoryContextFactory _contextFactory; private ILoggerProvider _loggerProvider; private ICacheProvider _cachingProvider; private IRepositoryConventions _conventions; #endregion #region Properties /// <summary> /// Gets the configured interceptors. /// </summary> public IReadOnlyDictionary<Type, Lazy<IRepositoryInterceptor>> Interceptors { get { return _interceptors; } } /// <summary> /// Gets the configured logger provider. /// </summary> public ILoggerProvider LoggerProvider { get { return _loggerProvider; } } /// <summary> /// Gets the configured caching provider. /// </summary> public ICacheProvider CachingProvider { get { return _cachingProvider; } } /// <summary> /// Gets the configured internal context factory. /// </summary> public IRepositoryContextFactory ContextFactory { get { return _contextFactory; } } /// <summary> /// Gets the configured conventions. /// </summary> public IRepositoryConventions Conventions { get { return _conventions; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RepositoryOptions" /> class. /// </summary> public RepositoryOptions() { } /// <summary> /// Initializes a new instance of the <see cref="RepositoryOptions" /> class. /// </summary> /// <param name="options">The repository options to clone.</param> public RepositoryOptions([NotNull] IRepositoryOptions options) { Guard.NotNull(options, nameof(options)); _interceptors = options.Interceptors.ToDictionary(x => x.Key, x => x.Value); _cachingProvider = options.CachingProvider; _loggerProvider = options.LoggerProvider; _contextFactory = options.ContextFactory; _conventions = options.Conventions; } #endregion #region Public Methods /// <summary> /// Clones the current configured options to a new instance. /// </summary> /// <returns>The new clone instance.</returns> public RepositoryOptions Clone() => new RepositoryOptions(this); /// <summary> /// Returns the option instance with a configured interceptor. /// </summary> /// <param name="underlyingType">The type of interceptor.</param> /// <param name="interceptorFactory">The interceptor factory.</param> /// <returns>The same option instance.</returns> public RepositoryOptions With([NotNull] Type underlyingType, Func<IRepositoryInterceptor> interceptorFactory) { Guard.NotNull(underlyingType, nameof(underlyingType)); Guard.NotNull(interceptorFactory, nameof(interceptorFactory)); var clone = Clone(); var lazy = new Lazy<IRepositoryInterceptor>(interceptorFactory); if (clone._interceptors.ContainsKey(underlyingType)) clone._interceptors[underlyingType] = lazy; else clone._interceptors.Add(underlyingType, lazy); return clone; } /// <summary> /// Returns the option instance with a configured context factory. /// </summary> /// <param name="contextFactory">The context factory.</param> /// <returns>The same option instance.</returns> public RepositoryOptions With([NotNull] IRepositoryContextFactory contextFactory) { var clone = Clone(); clone._contextFactory = Guard.NotNull(contextFactory, nameof(contextFactory)); return clone; } /// <summary> /// Returns the option instance with a configured logger provider for logging messages within the repository. /// </summary> /// <param name="loggerProvider">The logger factory.</param> /// <returns>The same option instance.</returns> public RepositoryOptions With([NotNull] ILoggerProvider loggerProvider) { var clone = Clone(); clone._loggerProvider = Guard.NotNull(loggerProvider, nameof(loggerProvider)); return clone; } /// <summary> /// Returns the option instance with a configured caching provider for caching queries within the repository. /// </summary> /// <param name="cacheProvider">The caching provider.</param> /// <returns>The same option instance.</returns> public RepositoryOptions With([NotNull] ICacheProvider cacheProvider) { var clone = Clone(); clone._cachingProvider = Guard.NotNull(cacheProvider, nameof(cacheProvider)); return clone; } /// <summary> /// Returns the option instance with a configured conventions. /// </summary> /// <param name="conventions">The configurable conventions.</param> /// <returns>The same option instance.</returns> public RepositoryOptions With([NotNull] IRepositoryConventions conventions) { var clone = Clone(); clone._conventions = Guard.NotNull(conventions, nameof(conventions)); return clone; } #endregion } }
35.315789
132
0.623282
[ "MIT" ]
FeodorFitsner/DotNetToolkit.Repository
src/DotNetToolkit.Repository/Configuration/Options/Internal/RepositoryOptions.cs
6,041
C#
using System.Collections; using UnityEngine; namespace GGJ2020.Common { public class ElementShake : MonoBehaviour { private RectTransform rect; private Vector3 originalPosition; private Quaternion originalRotation; private Coroutine rotateCoroutine; private Coroutine positionCoroutine; private void Start() { rect = GetComponent<RectTransform>(); originalPosition = rect.anchoredPosition; originalRotation = rect.rotation; } public void ShakePosition(float power, float frame) { if (rect == null) return; if (positionCoroutine != null) StopCoroutine(positionCoroutine); positionCoroutine = StartCoroutine(ShakePositionCoroutine(power, frame)); } private IEnumerator ShakePositionCoroutine(float power, float frame) { for (var i = 0; i < frame; i++) { var ox = UnityEngine.Random.Range(-1.0f, 1.0f); var oy = UnityEngine.Random.Range(-1.0f, 1.0f); var offset = new Vector3(ox, oy, 0).normalized * UnityEngine.Random.Range(0, power); rect.anchoredPosition = originalPosition + offset; yield return null; } rect.anchoredPosition = originalPosition; } public void ShakeRotation(float angleRange, float frame) { if (rect == null) return; if (rotateCoroutine != null) StopCoroutine(rotateCoroutine); rotateCoroutine = StartCoroutine(ShakeRotationCorountine(angleRange, frame, true)); } private IEnumerator ShakeRotationCorountine(float angleRange, float frame, bool isResetLast) { for (int i = 0; i < frame; i++) { var angle = UnityEngine.Random.Range(-angleRange, angleRange); rect.rotation = Quaternion.AngleAxis(angle, Vector3.forward) * originalRotation; yield return null; } if (isResetLast) { rect.rotation = originalRotation; } } /// <summary> /// 揺れた後そのままにする /// </summary> public void ShakeRotationPermanent(float angleRange, float frame) { if (rect == null) return; if (rotateCoroutine != null) StopCoroutine(rotateCoroutine); rotateCoroutine = StartCoroutine(ShakeRotationCorountine(angleRange, frame, false)); } } }
34.146667
100
0.584928
[ "Apache-2.0" ]
TORISOUP/GGJ2020_Akiba_team2
Assets/GGJ2020/Scripts/Common/ElementShake.cs
2,585
C#
using System; using System.Collections.Generic; using System.Text; namespace BasicServer { public class BasicServerConfig { public string LocalIpEndpoint { get; set; } } }
16.166667
51
0.701031
[ "MIT" ]
mykah89/BACnet.Examples
BasicServer/BasicServerConfig.cs
196
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("01. Odd or Even")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Odd or Even")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("ac2b1778-3b08-4521-86a6-35df801f7ff5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.740556
[ "MIT" ]
MihailStoyanov/TelerikAcademy
Homework/C# Fundamentals Homework/C# Fundamentals - 03. Operators and Expressions/Operators and Expressions/01. Odd or Even/Properties/AssemblyInfo.cs
1,406
C#
//Problem 1. Numbers from 1 to N // Write a program that enters from the console a positive integer n and prints all the numbers //from 1 to n, on a single line, separated by a space. using System; class Numbers { static void Main() { Console.WriteLine("enter positive integer"); int n = int.Parse(Console.ReadLine()); if (n < 0) { Console.WriteLine("error"); return; } for(int i=0;i<=n;i++) { Console.Write(i+" "); } } }
21.869565
98
0.580517
[ "MIT" ]
ivannk0900/Telerik-Academy
C# 1/Loops/NumbersToN/Numbers.cs
505
C#
using AutoMapper; using HomeMadeFood.Services.Common.Contracts; namespace HomeMadeFood.Services.Common { public class MappingService : IMappingService { public T Map<T>(object source) { return Mapper.Map<T>(source); } public TDestination Map<TSource, TDestination>(TSource source, TDestination destination) { return Mapper.Map<TSource, TDestination>(source, destination); } } }
25.777778
96
0.650862
[ "MIT" ]
MilStancheva/HomeMadeFood
HomeMadeFood/Services/Common/HomeMadeFood.Services.Common/MappingService.cs
466
C#
// // MIT License // Copyright (c) 2021 Polarith. // See the LICENSE file in the project root for full license information. // using Polarith.UnityUtils; using UnityEngine; namespace Polarith.AI.Move { /// <summary> /// <see cref="AIMFormationBox"/> computes an agent's position based on its order inside a box-shaped formation and /// the reference position or -object of the formation. /// Front-end component of the underlying <see cref="Move.FormationBox"/> class. /// </summary> [AddComponentMenu("Polarith AI » Move/Behaviours/Steering/AIM Formation Box")] [HelpURL("http://docs.polarith.com/ai/component-aim-formationbox.html")] public sealed class AIMFormationBox : AIMFormation { #region Fields ================================================================================================= [Tooltip("Reference to the underlying back-end class (read only).")] [SerializeField] private FormationBox formationBox = new FormationBox(); [Tooltip("Visualizes the shape of the formation by its boundary.")] [SerializeField] private BoxGizmo formationGizmo = new BoxGizmo(); #endregion // Fields #region Properties ============================================================================================= /// <summary> /// Polymorphic reference to the underlying back-end class <see cref="Move.SteeringBehaviour"/> (read only). /// </summary> public override SteeringBehaviour SteeringBehaviour { get { return formationBox; } } //-------------------------------------------------------------------------------------------------------------- /// <summary> /// Polymorphic reference to the underlying back-end class <see cref="Move.Formation"/> (read only). /// </summary> public override Formation Formation { get { return formationBox; } } //-------------------------------------------------------------------------------------------------------------- /// <summary> /// Reference to the underlying back-end class <see cref="Move.FormationBox"/> (read only). /// </summary> public FormationBox FormationBox { get { return formationBox; } set { formationBox = value; } } //-------------------------------------------------------------------------------------------------------------- /// <summary> /// Determines whether the underlying back-end class is thread-safe (read only). Returns always <c>true</c>. /// </summary> public override bool ThreadSafe { get { return true; } } #endregion // Properties #region Methods ================================================================================================ /// <summary> /// Visualizes the boundary of the formation based on its size. /// </summary> protected override void OnDrawGizmos() { base.OnDrawGizmos(); if (!formationGizmo.Enabled || !isActiveAndEnabled) return; float x, y, z; if (formationBox.Shape == ShapeType.Planar) { x = formationBox.AgentsPerLine.X / 2f * formationBox.Spacing; y = formationBox.Layers * formationBox.Spacing / 2f; z = 0; } else { x = formationBox.AgentsPerLine.X / 2f * formationBox.Spacing; y = formationBox.AgentsPerLine.Y / 2f * formationBox.Spacing; z = formationBox.Layers * formationBox.Spacing / 2f; } if (TargetObject != null) formationGizmo.Draw(TargetObject.transform.position, x, y, z, TargetObject.transform.rotation); else formationGizmo.Draw(TargetPosition, x, y, z, Quaternion.identity); } #endregion // Methods } // class AIMFormationBox } // namespace Polarith.AI.Move
37.017857
120
0.494935
[ "MIT" ]
Polarith/AI-Formation
Assets/Polarith/AI/Sources/Move/Front/Formation/AIMFormationBox.cs
4,149
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; public class SourceController : MonoBehaviour { public AudioSource source; public void Play() { source.Play(); } public void Pause() { source.Pause(); } }
15.619048
45
0.667683
[ "MIT" ]
mikosama326/unity-audio-endeavors
Assets/SourceController.cs
328
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20190401.Inputs { /// <summary> /// ExpressRouteLink child resource definition. /// </summary> public sealed class ExpressRouteLinkArgs : Pulumi.ResourceArgs { /// <summary> /// Administrative state of the physical port. /// </summary> [Input("adminState")] public InputUnion<string, Pulumi.AzureNative.Network.V20190401.ExpressRouteLinkAdminState>? AdminState { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Name of child port resource that is unique among child port resources of the parent. /// </summary> [Input("name")] public Input<string>? Name { get; set; } public ExpressRouteLinkArgs() { } } }
29.170732
124
0.622074
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20190401/Inputs/ExpressRouteLinkArgs.cs
1,196
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using EZCameraShake; public class Enemy : MonoBehaviour { [SerializeField] int damage=1; [SerializeField] AudioClip audioBoom; public GameObject boomParticle; private void OnTriggerEnter2D(Collider2D collision) { Player player = collision.GetComponent<Player>(); if(player!=null) { player.TakeDamage(damage); Boom(); } if(collision.CompareTag("Wall")) { Destroy(gameObject); } } void Boom() { FindObjectOfType<GameMenager>().audioSource.PlayOneShot(audioBoom); CameraShaker.Instance.ShakeOnce(1f, 1f, .1f, 1); GameObject effect = Instantiate(boomParticle, gameObject.transform.position, Quaternion.identity); Destroy(effect, 2.5f); Destroy(gameObject); } }
25.25
106
0.640264
[ "MIT" ]
KorzenGameDev/CSharpScripts
BunnyEscScripts/Enemy.cs
911
C#
using System.Data; using System.Data.SQLite; namespace EFDemo.Samples { public class SqliteDemo { private const string SqliteFilePath = "sqlitedb.db"; public static void SqLiteCreate() { using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + SqliteFilePath)) { using (SQLiteCommand comm = conn.CreateCommand()) { conn.Open(); comm.CommandText = @"CREATE TABLE COMPANY( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );"; comm.ExecuteNonQuery(); } } } public static void SqLiteSelect() { DataSet ds = new DataSet(); using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + SqliteFilePath)) { using (SQLiteCommand comm = conn.CreateCommand()) { conn.Open(); //comm.Parameters.Clear(); comm.CommandText = "Select * From COMPANY"; // comm.CommandText = "SELECT * FROM sqlite_master WHERE type = 'table' and name='COMPANY'"; using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm)) { adapter.Fill(ds); } } } } public static void SqLiteInsert() { using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + SqliteFilePath)) { using (SQLiteCommand comm = conn.CreateCommand()) { conn.Open(); #region 1.1插入数据 comm.CommandText = @"INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 );"; comm.ExecuteNonQuery(); #endregion 1.1插入数据 #region 1.2使用参数插入数据 //comm.CommandText = "INSERT INTO COMPANY VALUES(@id,@name)"; //comm.Parameters.AddRange( // new[] // { // CreateSqliteParameter("@id", DbType.Int32, 4, 11), // CreateSqliteParameter("@name", DbType.String, 10, "Hello 11") // }); //comm.ExecuteNonQuery(); #endregion 1.2使用参数插入数据 } } } public static SQLiteParameter CreateSqliteParameter(string name, DbType type, int size, object value) { SQLiteParameter parm = new SQLiteParameter(name, type, size) { Value = value }; return parm; } } }
36
135
0.434028
[ "MIT" ]
huruiyi/CSharpExample
CSharpExample/CSharpBasic/EFDemo/Samples/SqliteDemo.cs
3,218
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.Commands.RedisCache.Models { using Microsoft.Azure.Management.Redis.Models; public class RedisCacheAttributesWithAccessKeys : RedisCacheAttributes { public RedisCacheAttributesWithAccessKeys(RedisCreateOrUpdateResponse cache, string resourceGroupName) { Id = cache.Resource.Id; Location = cache.Resource.Location; Name = cache.Resource.Name; Type = cache.Resource.Type; HostName = cache.Resource.Properties.HostName; Port = cache.Resource.Properties.Port; ProvisioningState = cache.Resource.Properties.ProvisioningState; SslPort = cache.Resource.Properties.SslPort; RedisConfiguration = cache.Resource.Properties.RedisConfiguration; EnableNonSslPort = cache.Resource.Properties.EnableNonSslPort.Value; RedisVersion = cache.Resource.Properties.RedisVersion; Size = SizeConverter.GetSizeInUserSpecificFormat(cache.Resource.Properties.Sku.Family, cache.Resource.Properties.Sku.Capacity); Sku = cache.Resource.Properties.Sku.Name; PrimaryKey = cache.Resource.Properties.AccessKeys.PrimaryKey; SecondaryKey = cache.Resource.Properties.AccessKeys.SecondaryKey; ResourceGroupName = resourceGroupName; VirtualNetwork = cache.Resource.Properties.VirtualNetwork; Subnet = cache.Resource.Properties.Subnet; StaticIP = cache.Resource.Properties.StaticIP; TenantSettings = cache.Resource.Properties.TenantSettings; ShardCount = cache.Resource.Properties.ShardCount; } public string PrimaryKey { get; private set; } public string SecondaryKey { get; private set; } } }
50.960784
140
0.649481
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/RedisCache/Commands.RedisCache/Models/RedisCacheAttributesWithAccessKeys.cs
2,551
C#
using Bookstore.Domain.ValueObjects.Contracts; using Flunt.Notifications; namespace Bookstore.Domain.ValueObjects { public class Email : Notifiable<Notification> { private readonly string _email; public Email(string email) { _email = email; AddNotifications(new CreateEmailContract(this)); } public override string ToString() => _email; public static Email Parse(string value) => new Email(value); public static bool TryParse(string value, out Email result) { result = new Email(value); return result.IsValid; } public override bool Equals(object? obj) { if (obj == null || (!(obj is Email) && !(obj is string))) return false; var stringObj = obj.ToString(); return ((Email)stringObj).GetHashCode() == _email.GetHashCode(); } public override int GetHashCode() { return _email.GetHashCode(); } public static implicit operator Email(string value) => Parse(value); public static implicit operator string(Email value) => value.ToString(); } }
27.155556
80
0.584288
[ "MIT" ]
carlosforti/Bookstore
src/Bookstore.Domain/ValueObjects/Email.cs
1,224
C#
namespace Sidekick.Apis.Poe.Parser { /// <summary> /// Stores data about each line in the parsing process /// </summary> public class ParsingLine { /// <summary> /// Stores data about each line in the parsing process /// </summary> /// <param name="text">The line of the item description</param> public ParsingLine(int index, string text) { Index = index; Text = text; } /// <summary> /// Indicates if this line has been successfully parsed /// </summary> public bool Parsed { get; set; } = false; /// <summary> /// The index of the line inside the ParsingBlock /// </summary> public int Index { get; } /// <summary> /// The line of the item description /// </summary> public string Text { get; set; } public override string ToString() { return Text; } } }
25.564103
71
0.518556
[ "MIT" ]
CoderDanUK/Sidekick
src/Sidekick.Apis.Poe/Parser/ParsingLine.cs
997
C#
using ExpandedContent.Config; using ExpandedContent.Extensions; using ExpandedContent.Utilities; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints.Classes.Prerequisites; using Kingmaker.Blueprints.Classes.Selection; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.Items; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.UnitLogic.Alignments; using Kingmaker.UnitLogic.FactLogic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExpandedContent.Tweaks.Deities { internal class Eritrice { private static readonly BlueprintFeature CharmDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("f1ceba79ee123cc479cece27bc994ff2"); private static readonly BlueprintFeature GoodDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("882521af8012fc749930b03dc18a69de"); private static readonly BlueprintFeature KnowledgeDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("443d44b3e0ea84046a9bf304c82a0425"); private static readonly BlueprintFeature NobilityDomainAllowed = Resources.GetBlueprint<BlueprintFeature>("e0471d01e73254a4ca23278705b75e57"); private static readonly BlueprintSpellbook CrusaderSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("673d39f7da699aa408cdda6282e7dcc0"); private static readonly BlueprintSpellbook ClericSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("4673d19a0cf2fab4f885cc4d1353da33"); private static readonly BlueprintSpellbook InquisitorSpellbook = Resources.GetBlueprint<BlueprintSpellbook>("57fab75111f377248810ece84193a5a5"); private static readonly BlueprintFeature ChannelPositiveAllowed = Resources.GetBlueprint<BlueprintFeature>("8c769102f3996684fb6e09a2c4e7e5b9"); private static readonly BlueprintCharacterClass ClericClass = Resources.GetBlueprint<BlueprintCharacterClass>("67819271767a9dd4fbfd4ae700befea0"); private static readonly BlueprintCharacterClass InquistorClass = Resources.GetBlueprint<BlueprintCharacterClass>("f1a70d9e1b0b41e49874e1fa9052a1ce"); private static readonly BlueprintCharacterClass WarpriestClass = Resources.GetBlueprint<BlueprintCharacterClass>("30b5e47d47a0e37438cc5a80c96cfb99"); private static readonly BlueprintCharacterClass PaladinClass = Resources.GetBlueprint<BlueprintCharacterClass>("bfa11238e7ae3544bbeb4d0b92e897ec"); public static void AddEritriceFeature() { BlueprintItem MasterworkDagger = Resources.GetBlueprint<BlueprintItem>("dfc92affae244554e8745a9ee9b7c520"); BlueprintArchetype FeralChampionArchetype = Resources.GetBlueprint<BlueprintArchetype>("f68ca492c9c15e241ab73735fbd0fb9f"); BlueprintArchetype PriestOfBalance = Resources.GetBlueprint<BlueprintArchetype>("a4560e3fb5d247d68fb1a2738fcc0855"); BlueprintArchetype SilverChampionArchetype = Resources.GetModBlueprint<BlueprintArchetype>("SilverChampionArchetype"); BlueprintFeature DaggerProficiency = Resources.GetBlueprint<BlueprintFeature>("b776c19291928cf4184d4dc65f09f3a6"); var EritriceIcon = AssetLoader.LoadInternal("Deities", "Icon_Eritrice.jpg"); var EritriceFeature = Helpers.CreateBlueprint<BlueprintFeature>("EritriceFeature", (bp => { bp.SetName("Eritrice"); bp.SetDescription("\nTitles: Heart-Speaker " + "\nAlignment: Neutral Good " + "\nAreas of Concern: Debate, Opinions, Truth " + "\nDomains: Charm, Good, Knowledge, Nobility " + "\nSubdomains: Agathion, Education, Leadership, Memory, Thought " + "\nFavoured Weapon: Dagger " + "\nHoly Symbol: Lion-shaped lectern " + "\nSacred Animal: Lion " + "\nAt the dawn of creation, so the stories go, the archdevil Geryon filled a pit in the Hellish realm of Stygia with an outpouring of lies. " + "From beneath the weight of these lies rang out a single truth, which flew free of the fifth layer of Hell before ascending to the upper planes. " + "That truth was Eritrice. The muscular Eritrice stands 8 feet tall, and her feminine form is typically covered with a pale brown pelt. Her head is " + "that of a female lion's and her eyes gleam like amethysts. She wears a short leather kilt beneath a rose-colored breastplate. Eritrice's voice is " + "so compelling, it is said, that those who hear her speak forget her remarkable appearance. Eritrice works to spread truth and wisdom throughout the " + "world, but believes that insight gained through spirited debate is more valuable than knowledge gleaned from books. Her agents encourage discussion and " + "respectful disagreement. In regions where lies are spoken aloud but truth remains hidden, Eritrice and her minions help good individuals pass messages. " + "Geryon and his minions are Heart-Speaker's sworn enemies, and the two are known to have had titanic battles in the past. Heart-Speaker makes her home on " + "the broad, sun-soaked plains of Nirvana. Her favorite spot is the Windswept Lea, a green and verdant meadow. When entertaining guests, she stays in a " + "grand pavilion of chestnut wood, whose walls open to the sweet grassland and whose rooms are separated by hanging shantung curtains."); bp.m_Icon = EritriceIcon; bp.Ranks = 1; bp.IsClassFeature = true; bp.HideInCharacterSheetAndLevelUp = false; bp.AddComponent<PrerequisiteNoArchetype>(c => { c.m_CharacterClass = ClericClass.ToReference<BlueprintCharacterClassReference>(); c.m_Archetype = PriestOfBalance.ToReference<BlueprintArchetypeReference>(); }); bp.AddComponent<PrerequisiteNoArchetype>(c => { c.m_CharacterClass = WarpriestClass.ToReference<BlueprintCharacterClassReference>(); c.m_Archetype = FeralChampionArchetype.ToReference<BlueprintArchetypeReference>(); }); bp.AddComponent<PrerequisiteNoArchetype>(c => { c.HideInUI = true; c.m_CharacterClass = PaladinClass.ToReference<BlueprintCharacterClassReference>(); c.m_Archetype = SilverChampionArchetype.ToReference<BlueprintArchetypeReference>(); }); bp.Groups = new FeatureGroup[] { FeatureGroup.Deities }; bp.AddComponent<PrerequisiteAlignment>(c => { c.Alignment = AlignmentMaskType.LawfulGood | AlignmentMaskType.NeutralGood | AlignmentMaskType.ChaoticGood | AlignmentMaskType.TrueNeutral; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { ChannelPositiveAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { CharmDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { GoodDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { KnowledgeDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[1] { NobilityDomainAllowed.ToReference<BlueprintUnitFactReference>() }; }); bp.AddComponent<ForbidSpellbookOnAlignmentDeviation>(c => { c.m_Spellbooks = new BlueprintSpellbookReference[1] { CrusaderSpellbook.ToReference<BlueprintSpellbookReference>() }; c.m_Spellbooks = new BlueprintSpellbookReference[1] { ClericSpellbook.ToReference<BlueprintSpellbookReference>() }; c.m_Spellbooks = new BlueprintSpellbookReference[1] { InquisitorSpellbook.ToReference<BlueprintSpellbookReference>() }; }); bp.AddComponent<AddFeatureOnClassLevel>(c => { c.m_Class = ClericClass.ToReference<BlueprintCharacterClassReference>(); c.m_Feature = DaggerProficiency.ToReference<BlueprintFeatureReference>(); c.Level = 1; c.m_Archetypes = null; c.m_AdditionalClasses = new BlueprintCharacterClassReference[2] { InquistorClass.ToReference<BlueprintCharacterClassReference>(), WarpriestClass.ToReference<BlueprintCharacterClassReference>() }; }); bp.AddComponent<AddStartingEquipment>(c => { c.m_BasicItems = new BlueprintItemReference[1] { MasterworkDagger.ToReference<BlueprintItemReference>() }; c.m_RestrictedByClass = new BlueprintCharacterClassReference[3] { ClericClass.ToReference<BlueprintCharacterClassReference>(), InquistorClass.ToReference<BlueprintCharacterClassReference>(), WarpriestClass.ToReference<BlueprintCharacterClassReference>() }; }); })); } } }
72.703704
177
0.682017
[ "MIT" ]
ka-dyn/ExpandedContent
ExpandedContent/Tweaks/Deities/Eritrice.cs
9,817
C#
// // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // using Mono.Cecil; using System.Text; namespace nanoFramework.Tools.MetadataProcessor.Core.Extensions { internal static class TypeReferenceExtensions { public static bool IsToInclude(this TypeReference value) { return !nanoTablesContext.IgnoringAttributes.Contains(value.FullName); } public static string TypeSignatureAsString(this TypeReference type) { if (type.MetadataType == MetadataType.IntPtr) { return "I"; } if (type.MetadataType == MetadataType.UIntPtr) { return "U"; } nanoCLR_DataType dataType; if (nanoSignaturesTable.PrimitiveTypes.TryGetValue(type.FullName, out dataType)) { switch (dataType) { case nanoCLR_DataType.DATATYPE_VOID: case nanoCLR_DataType.DATATYPE_BOOLEAN: case nanoCLR_DataType.DATATYPE_CHAR: case nanoCLR_DataType.DATATYPE_I1: case nanoCLR_DataType.DATATYPE_U1: case nanoCLR_DataType.DATATYPE_I2: case nanoCLR_DataType.DATATYPE_U2: case nanoCLR_DataType.DATATYPE_I4: case nanoCLR_DataType.DATATYPE_U4: case nanoCLR_DataType.DATATYPE_I8: case nanoCLR_DataType.DATATYPE_U8: case nanoCLR_DataType.DATATYPE_R4: case nanoCLR_DataType.DATATYPE_BYREF: case nanoCLR_DataType.DATATYPE_OBJECT: case nanoCLR_DataType.DATATYPE_WEAKCLASS: return dataType.ToString().Replace("DATATYPE_", ""); case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE: return "STRING"; case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE_TO_PRESERVE: return "R8"; case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE_TO_MARSHAL: return "TIMESPAN"; case nanoCLR_DataType.DATATYPE_REFLECTION: return type.FullName.Replace(".", ""); } } if (type.MetadataType == MetadataType.Class) { StringBuilder classSig = new StringBuilder("CLASS ["); classSig.Append(type.MetadataToken.ToInt32().ToString("x8")); classSig.Append("]"); return classSig.ToString(); } if (type.MetadataType == MetadataType.ValueType) { StringBuilder valueTypeSig = new StringBuilder("VALUETYPE ["); valueTypeSig.Append(type.MetadataToken.ToInt32().ToString("x8")); valueTypeSig.Append("]"); return valueTypeSig.ToString(); } if (type.IsArray) { StringBuilder arraySig = new StringBuilder("SZARRAY "); arraySig.Append(type.GetElementType().TypeSignatureAsString()); return arraySig.ToString(); } if (type.IsByReference) { StringBuilder byrefSig = new StringBuilder("BYREF "); byrefSig.Append(type.GetElementType().TypeSignatureAsString()); return byrefSig.ToString(); } if (type.IsGenericParameter || type.IsGenericInstance) { return $"!!{type.Name}"; } return ""; } public static string ToNativeTypeAsString(this TypeReference type) { nanoCLR_DataType dataType; if (nanoSignaturesTable.PrimitiveTypes.TryGetValue(type.FullName, out dataType)) { switch (dataType) { case nanoCLR_DataType.DATATYPE_VOID: return "void"; case nanoCLR_DataType.DATATYPE_BOOLEAN: return "bool"; case nanoCLR_DataType.DATATYPE_CHAR: return "char"; case nanoCLR_DataType.DATATYPE_I1: return "int8_t"; case nanoCLR_DataType.DATATYPE_U1: return "uint8_t"; case nanoCLR_DataType.DATATYPE_I2: return "int16_t"; case nanoCLR_DataType.DATATYPE_U2: return "uint16_t"; case nanoCLR_DataType.DATATYPE_I4: return "signed int"; case nanoCLR_DataType.DATATYPE_U4: return "unsigned int"; case nanoCLR_DataType.DATATYPE_I8: return "int64_t"; case nanoCLR_DataType.DATATYPE_U8: return "uint64_t"; case nanoCLR_DataType.DATATYPE_R4: return "float"; case nanoCLR_DataType.DATATYPE_BYREF: return ""; // system.String case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE: return "const char*"; // System.Double case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE_TO_PRESERVE: return "double"; default: return "UNSUPPORTED"; } } if (type.MetadataType == MetadataType.Class) { return "UNSUPPORTED"; } if (type.MetadataType == MetadataType.ValueType) { return "UNSUPPORTED"; } if (type.IsArray) { StringBuilder arraySig = new StringBuilder("CLR_RT_TypedArray_"); arraySig.Append(type.GetElementType().ToCLRTypeAsString()); return arraySig.ToString(); } if (type.IsGenericParameter) { return "UNSUPPORTED"; } return ""; } public static string ToCLRTypeAsString(this TypeReference type) { nanoCLR_DataType dataType; if (nanoSignaturesTable.PrimitiveTypes.TryGetValue(type.FullName, out dataType)) { switch (dataType) { case nanoCLR_DataType.DATATYPE_VOID: return "void"; case nanoCLR_DataType.DATATYPE_BOOLEAN: return "bool"; case nanoCLR_DataType.DATATYPE_CHAR: return "CHAR"; case nanoCLR_DataType.DATATYPE_I1: return "INT8"; case nanoCLR_DataType.DATATYPE_U1: return "UINT8"; case nanoCLR_DataType.DATATYPE_I2: return "INT16"; case nanoCLR_DataType.DATATYPE_U2: return "UINT16"; case nanoCLR_DataType.DATATYPE_I4: return "INT32"; case nanoCLR_DataType.DATATYPE_U4: return "UINT32"; case nanoCLR_DataType.DATATYPE_I8: return "INT64"; case nanoCLR_DataType.DATATYPE_U8: return "UINT64"; case nanoCLR_DataType.DATATYPE_R4: return "float"; case nanoCLR_DataType.DATATYPE_BYREF: return "NONE"; // system.String case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE: return "LPCSTR"; // System.Double case nanoCLR_DataType.DATATYPE_LAST_PRIMITIVE_TO_PRESERVE: return "double"; default: return "UNSUPPORTED"; } } if (type.MetadataType == MetadataType.Class) { return "UNSUPPORTED"; } if (type.MetadataType == MetadataType.ValueType) { return "UNSUPPORTED"; } if (type.IsArray) { StringBuilder arraySig = new StringBuilder(); arraySig.Append(type.GetElementType().ToCLRTypeAsString()); arraySig.Append("_ARRAY"); return arraySig.ToString(); } if (type.IsGenericParameter) { return "UNSUPPORTED"; } return ""; } public static nanoSerializationType ToSerializationType(this TypeReference value) { nanoCLR_DataType dataType; if (nanoSignaturesTable.PrimitiveTypes.TryGetValue(value.FullName, out dataType)) { switch (dataType) { case nanoCLR_DataType.DATATYPE_BOOLEAN: return nanoSerializationType.ELEMENT_TYPE_BOOLEAN; case nanoCLR_DataType.DATATYPE_I1: return nanoSerializationType.ELEMENT_TYPE_I1; case nanoCLR_DataType.DATATYPE_U1: return nanoSerializationType.ELEMENT_TYPE_U1; case nanoCLR_DataType.DATATYPE_I2: return nanoSerializationType.ELEMENT_TYPE_I2; case nanoCLR_DataType.DATATYPE_U2: return nanoSerializationType.ELEMENT_TYPE_U2; case nanoCLR_DataType.DATATYPE_I4: return nanoSerializationType.ELEMENT_TYPE_I4; case nanoCLR_DataType.DATATYPE_U4: return nanoSerializationType.ELEMENT_TYPE_U4; case nanoCLR_DataType.DATATYPE_I8: return nanoSerializationType.ELEMENT_TYPE_I8; case nanoCLR_DataType.DATATYPE_U8: return nanoSerializationType.ELEMENT_TYPE_U8; case nanoCLR_DataType.DATATYPE_R4: return nanoSerializationType.ELEMENT_TYPE_R4; case nanoCLR_DataType.DATATYPE_R8: return nanoSerializationType.ELEMENT_TYPE_R8; case nanoCLR_DataType.DATATYPE_CHAR: return nanoSerializationType.ELEMENT_TYPE_CHAR; case nanoCLR_DataType.DATATYPE_STRING: return nanoSerializationType.ELEMENT_TYPE_STRING; default: return 0; } } return 0; } } }
37.204698
93
0.505727
[ "MIT" ]
Eclo/metadata-processor
MetadataProcessor.Core/Extensions/TypeReferenceExtensions.cs
11,087
C#
using Jamiras.Commands; using Jamiras.Components; using Jamiras.DataModels; using Jamiras.DataModels.Metadata; using Jamiras.Services; using Jamiras.ViewModels; using Jamiras.ViewModels.Converters; using Jamiras.ViewModels.Fields; using Jamiras.ViewModels.Grid; using RATools.Data; using RATools.Parser; using RATools.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace RATools.ViewModels { public class NewScriptDialogViewModel : DialogViewModelBase { public NewScriptDialogViewModel() { DialogTitle = "New Script"; CanClose = true; SearchCommand = new DelegateCommand(Search); CheckAllCommand = new DelegateCommand(CheckAll); UncheckAllCommand = new DelegateCommand(UncheckAll); CheckWithTicketsCommand = new DelegateCommand(CheckWithTickets); GameId = new IntegerFieldViewModel("Game _ID", 1, 999999); _achievements = new ObservableCollection<DumpAchievementItem>(); _memoryItems = new List<MemoryItem>(); _ticketNotes = new TinyDictionary<int, string>(); _macros = new List<RichPresenceMacro>(); CodeNoteFilters = new[] { new CodeNoteFilterLookupItem(CodeNoteFilter.All, "All"), new CodeNoteFilterLookupItem(CodeNoteFilter.ForSelectedAchievements, "For Selected Achievements"), }; NoteDumps = new[] { new NoteDumpLookupItem(NoteDump.None, "None"), new NoteDumpLookupItem(NoteDump.All, "All"), new NoteDumpLookupItem(NoteDump.OnlyForDefinedMethods, "Only for Functions"), }; MemoryAddresses = new GridViewModel(); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Size", MemoryItem.SizeProperty, new DelegateConverter(a => Field.GetSizeFunction((FieldSize)a), null)) { Width = 48 }); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Address", MemoryItem.AddressProperty, new DelegateConverter(a => String.Format("0x{0:X6}", a), null)) { Width = 56 }); MemoryAddresses.Columns.Add(new TextColumnDefinition("Function Name", MemoryItem.FunctionNameProperty, new StringFieldMetadata("Function Name", 40, StringFieldAttributes.Required)) { Width = 120 }); MemoryAddresses.Columns.Add(new DisplayTextColumnDefinition("Notes", MemoryItem.NotesProperty)); } public IntegerFieldViewModel GameId { get; private set; } public static readonly ModelProperty IsGameLoadedProperty = ModelProperty.Register(typeof(NewScriptDialogViewModel), "IsGameLoaded", typeof(bool), false); public bool IsGameLoaded { get { return (bool)GetValue(IsGameLoadedProperty); } private set { SetValue(IsGameLoadedProperty, value); } } public CommandBase SearchCommand { get; private set; } private void Search() { int gameId = GameId.Value.GetValueOrDefault(); foreach (var directory in ServiceRepository.Instance.FindService<ISettings>().EmulatorDirectories) { var dataDirectory = Path.Combine(directory, "RACache", "Data"); var notesFile = Path.Combine(dataDirectory, gameId + "-Notes.json"); if (!File.Exists(notesFile)) notesFile = Path.Combine(dataDirectory, gameId + "-Notes2.txt"); if (File.Exists(notesFile)) { LoadGame(gameId, dataDirectory); var richPresenceFile = Path.Combine(dataDirectory, gameId + "-Rich.txt"); if (File.Exists(richPresenceFile)) LoadRichPresence(richPresenceFile); return; } } TaskDialogViewModel.ShowWarningMessage("Could not locate code notes for game " + gameId, "The game does not appear to have been recently loaded in any of the emulators specified in the Settings dialog."); return; } private static FieldSize CheckForBigEndian(Token token, FieldSize leSize, FieldSize beSize) { if (token.Contains("bit-BE", StringComparison.OrdinalIgnoreCase) || token.Contains("bit BE", StringComparison.OrdinalIgnoreCase)) { return beSize; } return leSize; } private void LoadGame(int gameId, string raCacheDirectory) { _game = new GameViewModel(gameId, ""); _game.AssociateRACacheDirectory(raCacheDirectory); _game.PopulateEditorList(null); DialogTitle = "New Script - " + _game.Title; _achievements.Clear(); _ticketNotes.Clear(); _memoryItems.Clear(); MemoryAddresses.Rows.Clear(); var unofficialAchievements = new List<DumpAchievementItem>(); foreach (var achievement in _game.Editors.OfType<AchievementViewModel>()) { var publishedAchievement = achievement.Published.Asset as Achievement; if (publishedAchievement == null) continue; var dumpAchievement = new DumpAchievementItem(achievement.Id, publishedAchievement.Title); if (publishedAchievement.IsUnofficial) { dumpAchievement.IsUnofficial = true; unofficialAchievements.Add(dumpAchievement); } else { _achievements.Add(dumpAchievement); } foreach (var trigger in achievement.Published.TriggerList) { foreach (var group in trigger.Groups) { foreach (var requirement in group.Requirements) { if (requirement.Requirement == null) continue; if (requirement.Requirement.Left != null && requirement.Requirement.Left.IsMemoryReference) { var memoryItem = AddMemoryAddress(requirement.Requirement.Left); if (memoryItem != null && !dumpAchievement.MemoryAddresses.Contains(memoryItem)) dumpAchievement.MemoryAddresses.Add(memoryItem); } if (requirement.Requirement.Right != null && requirement.Requirement.Right.IsMemoryReference) { var memoryItem = AddMemoryAddress(requirement.Requirement.Right); if (memoryItem != null && !dumpAchievement.MemoryAddresses.Contains(memoryItem)) dumpAchievement.MemoryAddresses.Add(memoryItem); } } } } dumpAchievement.IsSelected = true; dumpAchievement.PropertyChanged += DumpAchievement_PropertyChanged; } foreach (var unofficialAchievement in unofficialAchievements) _achievements.Add(unofficialAchievement); foreach (var kvp in _game.Notes) { FieldSize size = FieldSize.Byte; Token token = new Token(kvp.Value, 0, kvp.Value.Length); if (token.Contains("16-bit", StringComparison.OrdinalIgnoreCase) || token.Contains("16 bit", StringComparison.OrdinalIgnoreCase)) { size = CheckForBigEndian(token, FieldSize.Word, FieldSize.BigEndianWord); } else if (token.Contains("32-bit", StringComparison.OrdinalIgnoreCase) || token.Contains("32 bit", StringComparison.OrdinalIgnoreCase)) { size = CheckForBigEndian(token, FieldSize.DWord, FieldSize.BigEndianDWord); } else if (token.Contains("24-bit", StringComparison.OrdinalIgnoreCase) || token.Contains("24 bit", StringComparison.OrdinalIgnoreCase)) { size = CheckForBigEndian(token, FieldSize.TByte, FieldSize.BigEndianTByte); } else if (token.Contains("float]", StringComparison.OrdinalIgnoreCase) || token.Contains("float)", StringComparison.OrdinalIgnoreCase)) { size = FieldSize.Float; } else if (token.Contains("MBF32", StringComparison.OrdinalIgnoreCase) || token.Contains("MBF-32", StringComparison.OrdinalIgnoreCase) || token.Contains("MBF40", StringComparison.OrdinalIgnoreCase) || token.Contains("MBF-40", StringComparison.OrdinalIgnoreCase)) { // MBF-40 values are 100% compatible with MBF-32. The last 8 bits are // too insignificant to be handled by the runtime, so can be ignored. size = FieldSize.MBF32; } AddMemoryAddress(new Field { Size = size, Type = FieldType.MemoryAddress, Value = (uint)kvp.Key }); } if (_achievements.Count == 0) SelectedCodeNotesFilter = CodeNoteFilter.All; UpdateMemoryGrid(); IsGameLoaded = true; GameId.IsEnabled = false; if (_achievements.Count > 0) ServiceRepository.Instance.FindService<IBackgroundWorkerService>().RunAsync(MergeOpenTickets); } private class RichPresenceMacro { public string Name; public ValueFormat FormatType; public Dictionary<string, string> LookupEntries; public List<string> DisplayLines; } private List<RichPresenceMacro> _macros; private void LoadRichPresence(string richPresenceFile) { RichPresenceMacro currentMacro = null; RichPresenceMacro displayMacro = null; using (var file = File.OpenText(richPresenceFile)) { do { var line = file.ReadLine(); if (line == null) break; var index = line.IndexOf("//"); if (index != -1) line = line.Substring(0, index).TrimEnd(); if (line.Length == 0) continue; if (line.StartsWith("Format:")) { currentMacro = new RichPresenceMacro { Name = line.Substring(7) }; _macros.Add(currentMacro); } else if (line.StartsWith("FormatType=")) { currentMacro.FormatType = Leaderboard.ParseFormat(line.Substring(11)); } else if (line.StartsWith("Lookup:")) { currentMacro = new RichPresenceMacro { Name = line.Substring(7), LookupEntries = new Dictionary<string, string>() }; _macros.Add(currentMacro); } else if (line.StartsWith("Display:")) { currentMacro = displayMacro = new RichPresenceMacro { Name = "Display", DisplayLines = new List<string>() }; _macros.Add(currentMacro); } else { if (currentMacro.DisplayLines != null) { currentMacro.DisplayLines.Add(line); } else if (currentMacro.LookupEntries != null) { index = line.IndexOf('='); if (index > 0) currentMacro.LookupEntries[line.Substring(0, index)] = line.Substring(index + 1); } } } while (true); } foreach (var macro in _macros) { if (macro.LookupEntries != null) { var dumpLookup = new DumpAchievementItem(0, macro.Name) { IsLookup = true }; dumpLookup.PropertyChanged += DumpAchievement_PropertyChanged; _achievements.Add(dumpLookup); } } if (displayMacro != null) { var dumpRichPresence = new DumpAchievementItem(0, "Rich Presence Script") { IsRichPresence = true }; for (int i = 0; i < displayMacro.DisplayLines.Count; ++i) { var line = displayMacro.DisplayLines[i]; if (line[0] == '?') { var index = line.IndexOf('?', 1); if (index != -1) { var trigger = line.Substring(1, index - 1); var achievement = new AchievementBuilder(); achievement.ParseRequirements(Tokenizer.CreateTokenizer(trigger)); foreach (var requirement in achievement.CoreRequirements) AddMemoryReferences(dumpRichPresence, requirement); foreach (var alt in achievement.AlternateRequirements) foreach (var requirement in alt) AddMemoryReferences(dumpRichPresence, requirement); } AddMacroMemoryReferences(dumpRichPresence, line.Substring(index + 1)); } else { AddMacroMemoryReferences(dumpRichPresence, line); if (i < displayMacro.DisplayLines.Count) displayMacro.DisplayLines.RemoveRange(i + 1, displayMacro.DisplayLines.Count - i - 1); break; } } dumpRichPresence.PropertyChanged += DumpAchievement_PropertyChanged; _achievements.Add(dumpRichPresence); } } private void AddMacroMemoryReferences(DumpAchievementItem displayRichPresence, string displayString) { var index = 0; do { index = displayString.IndexOf('@', index); if (index == -1) return; var index2 = displayString.IndexOf('(', index); if (index2 == -1) return; var index3 = displayString.IndexOf(')', index2); if (index3 == -1) return; var name = displayString.Substring(index + 1, index2 - index - 1); var parameter = displayString.Substring(index2 + 1, index3 - index2 - 1); var macro = _achievements.FirstOrDefault(a => a.IsLookup && a.Label == name); if (macro == null) macro = displayRichPresence; if (parameter[1] == ':') { var achievement = new AchievementBuilder(); achievement.ParseRequirements(Tokenizer.CreateTokenizer(parameter)); foreach (var requirement in achievement.CoreRequirements) AddMemoryReferences(macro, requirement); foreach (var alt in achievement.AlternateRequirements) foreach (var requirement in alt) AddMemoryReferences(macro, requirement); } else { foreach (var part in parameter.Split('_')) { foreach (var operand in part.Split('*')) { var field = Field.Deserialize(Tokenizer.CreateTokenizer(operand)); if (field.IsMemoryReference) { var memoryItem = AddMemoryAddress(field); if (memoryItem != null && !macro.MemoryAddresses.Contains(memoryItem)) macro.MemoryAddresses.Add(memoryItem); } } } } index = index2 + 1; } while (true); } private void MergeOpenTickets() { var openTickets = new List<int>(); var tickets = OpenTicketsViewModel.GetGameTickets(_game.GameId); foreach (var kvp in tickets) { var achievement = _achievements.FirstOrDefault(a => a.Id == kvp.Key); if (achievement != null) { openTickets.AddRange(kvp.Value.OpenTickets); achievement.OpenTickets.AddRange(kvp.Value.OpenTickets); achievement.RaiseOpenTicketCountChanged(); } } foreach (var ticket in openTickets) { var ticketPage = RAWebCache.Instance.GetTicketPage(ticket); var tokenizer = Tokenizer.CreateTokenizer(ticketPage); tokenizer.ReadTo("<td>Notes: </td>"); tokenizer.ReadTo("<code>"); tokenizer.Advance(6); var notes = tokenizer.ReadTo("</code>").ToString(); _ticketNotes[ticket] = notes.ToString(); } } private void AddMemoryReferences(DumpAchievementItem dumpAchievement, Requirement requirement) { if (requirement.Left != null && requirement.Left.IsMemoryReference) { var memoryItem = AddMemoryAddress(requirement.Left); if (memoryItem != null && !dumpAchievement.MemoryAddresses.Contains(memoryItem)) dumpAchievement.MemoryAddresses.Add(memoryItem); } if (requirement.Right != null && requirement.Right.IsMemoryReference) { var memoryItem = AddMemoryAddress(requirement.Right); if (memoryItem != null && !dumpAchievement.MemoryAddresses.Contains(memoryItem)) dumpAchievement.MemoryAddresses.Add(memoryItem); } } private MemoryItem AddMemoryAddress(Field field) { int index = 0; while (index < _memoryItems.Count) { if (_memoryItems[index].Address > field.Value) break; if (_memoryItems[index].Address == field.Value) { if (_memoryItems[index].Size > field.Size) break; if (_memoryItems[index].Size == field.Size) return _memoryItems[index]; } index++; } string notes; if (!_game.Notes.TryGetValue((int)field.Value, out notes)) return null; var item = new MemoryItem(field.Value, field.Size, notes.Replace("\r\n", " ").Replace('\n', ' ')); _memoryItems.Insert(index, item); return item; } private GameViewModel _game; private readonly TinyDictionary<int, string> _ticketNotes; public class DumpAchievementItem : LookupItem { public DumpAchievementItem(int id, string label) : base(id, label) { OpenTickets = new List<int>(); MemoryAddresses = new List<MemoryItem>(); } public bool IsUnofficial { get; set; } public bool IsLookup { get; set; } public bool IsRichPresence { get; set; } public int OpenTicketCount { get { return OpenTickets.Count; } } internal List<int> OpenTickets { get; private set; } internal void RaiseOpenTicketCountChanged() { OnPropertyChanged(() => OpenTicketCount); } internal List<MemoryItem> MemoryAddresses { get; private set; } } public IEnumerable<DumpAchievementItem> Achievements { get { return _achievements; } } private readonly ObservableCollection<DumpAchievementItem> _achievements; private void DumpAchievement_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsSelected") { var item = sender as DumpAchievementItem; if (item != null) { if (item.IsRichPresence && item.IsSelected) { foreach (var achievement in _achievements) { if (achievement.IsLookup) achievement.IsSelected = true; } } else if (item.IsLookup && !item.IsSelected) { foreach (var achievement in _achievements) { if (achievement.IsRichPresence) achievement.IsSelected = false; } } } UpdateMemoryGrid(); } } public CommandBase CheckAllCommand { get; private set; } private void CheckAll() { foreach (var achievment in _achievements) achievment.IsSelected = true; } public CommandBase UncheckAllCommand { get; private set; } private void UncheckAll() { foreach (var achievement in _achievements) achievement.IsSelected = false; } public CommandBase CheckWithTicketsCommand { get; private set; } private void CheckWithTickets() { foreach (var achievement in _achievements) achievement.IsSelected = (achievement.OpenTicketCount > 0); } public enum CodeNoteFilter { None = 0, All, ForSelectedAchievements, } public enum NoteDump { None = 0, All, OnlyForDefinedMethods, } public class CodeNoteFilterLookupItem { public CodeNoteFilterLookupItem(CodeNoteFilter id, string label) { Id = id; Label = label; } public CodeNoteFilter Id { get; private set; } public string Label { get; private set; } } public IEnumerable<CodeNoteFilterLookupItem> CodeNoteFilters { get; private set; } public class NoteDumpLookupItem { public NoteDumpLookupItem(NoteDump id, string label) { Id = id; Label = label; } public NoteDump Id { get; private set; } public string Label { get; private set; } } public IEnumerable<NoteDumpLookupItem> NoteDumps { get; private set; } public static readonly ModelProperty SelectedCodeNotesFilterProperty = ModelProperty.Register(typeof(NewScriptDialogViewModel), "SelectedCodeNotesFilter", typeof(CodeNoteFilter), CodeNoteFilter.ForSelectedAchievements, OnSelectedCodeNotesFilterChanged); public CodeNoteFilter SelectedCodeNotesFilter { get { return (CodeNoteFilter)GetValue(SelectedCodeNotesFilterProperty); } set { SetValue(SelectedCodeNotesFilterProperty, value); } } private static void OnSelectedCodeNotesFilterChanged(object sender, ModelPropertyChangedEventArgs e) { ((NewScriptDialogViewModel)sender).UpdateMemoryGrid(); } public static readonly ModelProperty SelectedNoteDumpProperty = ModelProperty.Register(typeof(NewScriptDialogViewModel), "SelectedNoteDump", typeof(NoteDump), NoteDump.OnlyForDefinedMethods); public NoteDump SelectedNoteDump { get { return (NoteDump)GetValue(SelectedNoteDumpProperty); } set { SetValue(SelectedNoteDumpProperty, value); } } public static readonly ModelProperty MemoryAddressesLabelProperty = ModelProperty.Register(typeof(NewScriptDialogViewModel), "MemoryAddressesLabel", typeof(string), "Referenced memory addresses"); public string MemoryAddressesLabel { get { return (string)GetValue(MemoryAddressesLabelProperty); } private set { SetValue(MemoryAddressesLabelProperty, value); } } public GridViewModel MemoryAddresses { get; private set; } private void UpdateMemoryGrid() { var visibleAddresses = new List<MemoryItem>(); if (SelectedCodeNotesFilter == CodeNoteFilter.None) { MemoryAddressesLabel = "No memory addresses"; } else { if (SelectedCodeNotesFilter == CodeNoteFilter.All) { MemoryAddressesLabel = "All known memory addresses"; foreach (var memoryItem in _memoryItems) visibleAddresses.Add(memoryItem); // will merge in any non-byte references from selected achievements } else { MemoryAddressesLabel = (string)MemoryAddressesLabelProperty.DefaultValue; // will merge in all references from selected achievements } foreach (var achievement in _achievements) { if (!achievement.IsSelected) continue; foreach (var address in achievement.MemoryAddresses) { if (!visibleAddresses.Contains(address)) visibleAddresses.Add(address); } } } // update the grid var rowsToRemove = new List<MemoryItem>(); foreach (var row in MemoryAddresses.Rows) { var memoryItem = (MemoryItem)row.Model; if (!visibleAddresses.Remove(memoryItem)) rowsToRemove.Add(memoryItem); } foreach (var memoryItem in rowsToRemove) MemoryAddresses.RemoveRow(memoryItem); visibleAddresses.Sort((l,r) => { int diff = (int)l.Address - (int)r.Address; if (diff == 0) diff = (int)l.Size - (int)r.Size; return diff; }); var memIndex = 0; for (int addrIndex = 0; addrIndex < visibleAddresses.Count; addrIndex++) { var memoryItem = visibleAddresses[addrIndex]; while (memIndex < MemoryAddresses.Rows.Count) { var rowItem = (MemoryItem)MemoryAddresses.Rows[memIndex].Model; if (rowItem.Address < memoryItem.Address || rowItem.Size < memoryItem.Size) { memIndex++; continue; } break; } MemoryAddresses.InsertRow(memIndex, memoryItem); } } [DebuggerDisplay("{Size} {Address}")] public class MemoryItem : ViewModelBase { public MemoryItem(uint address, FieldSize size, string notes) { Address = address; Size = size; Notes = notes; } public static readonly ModelProperty AddressProperty = ModelProperty.Register(typeof(MemoryItem), "Address", typeof(uint), (uint)0); public uint Address { get { return (uint)GetValue(AddressProperty); } private set { SetValue(AddressProperty, value); } } public static readonly ModelProperty SizeProperty = ModelProperty.Register(typeof(MemoryItem), "Size", typeof(FieldSize), FieldSize.Byte); public FieldSize Size { get { return (FieldSize)GetValue(SizeProperty); } private set { SetValue(SizeProperty, value); } } public static readonly ModelProperty FunctionNameProperty = ModelProperty.Register(typeof(MemoryItem), "FunctionName", typeof(string), String.Empty); public string FunctionName { get { return (string)GetValue(FunctionNameProperty); } set { SetValue(FunctionNameProperty, value); } } public static readonly ModelProperty NotesProperty = ModelProperty.Register(typeof(MemoryItem), "Notes", typeof(string), String.Empty); public string Notes { get { return (string)GetValue(NotesProperty); } private set { SetValue(NotesProperty, value); } } } private readonly List<MemoryItem> _memoryItems; public GameViewModel Finalize() { var cleansed = _game.Title; foreach (var c in Path.GetInvalidFileNameChars()) cleansed = cleansed.Replace(c.ToString(), ""); if (String.IsNullOrEmpty(cleansed)) cleansed = _game.GameId.ToString(); _game.Script.Filename = cleansed + ".rascript"; var memoryStream = new MemoryStream(); Dump(memoryStream); _game.Script.SetContent(Encoding.UTF8.GetString(memoryStream.ToArray())); _game.Script.SetModified(); return _game; } private static string EscapeString(string input) { return input.Replace("\"", "\\\""); } private void Dump(Stream outStream) { MemoryAddresses.Commit(); using (var stream = new StreamWriter(outStream)) { stream.Write("// "); stream.WriteLine(_game.Title); stream.Write("// #ID = "); stream.WriteLine(String.Format("{0}", _game.GameId)); bool needLine = true; bool hadFunction = false; var numberFormat = ServiceRepository.Instance.FindService<ISettings>().HexValues ? NumberFormat.Hexadecimal : NumberFormat.Decimal; string addressFormat = "{0:X4}"; if (_memoryItems.Count > 0 && _memoryItems[_memoryItems.Count - 1].Address > 0xFFFF) addressFormat = "{0:X6}"; // TODO: addressFormat is only used in note comments - also apply to generated code var lookupsToDump = _achievements.Where(a => a.IsLookup && a.IsSelected).ToList(); bool first; var dumpNotes = SelectedNoteDump; var filter = SelectedCodeNotesFilter; uint previousNoteAddress = UInt32.MaxValue; foreach (var memoryItem in _memoryItems) { if (filter == CodeNoteFilter.ForSelectedAchievements) { if (MemoryAddresses.GetRow(memoryItem) == null) continue; } string notes = null; if (dumpNotes != NoteDump.None) { if (_game.Notes.TryGetValue((int)memoryItem.Address, out notes)) { if (String.IsNullOrEmpty(memoryItem.FunctionName)) { if (dumpNotes == NoteDump.OnlyForDefinedMethods) continue; if (memoryItem.Address == previousNoteAddress) continue; } } } if (!String.IsNullOrEmpty(notes)) { notes = notes.Trim(); if (notes.Length > 0) { if (needLine || hadFunction || !String.IsNullOrEmpty(memoryItem.FunctionName)) { needLine = false; stream.WriteLine(); } var lines = notes.Split('\n'); stream.Write("// $"); previousNoteAddress = memoryItem.Address; var address = String.Format(addressFormat, memoryItem.Address); stream.Write(address); stream.Write(": "); stream.WriteLine(lines[0].Trim()); for (int i = 1; i < lines.Length; i++) { stream.Write("// "); if (address.Length > 4) stream.Write(" ".ToCharArray(), 0, address.Length - 4); stream.WriteLine(lines[i].Trim()); } } } if (!String.IsNullOrEmpty(memoryItem.FunctionName)) { if (needLine) { needLine = false; stream.WriteLine(); } hadFunction = true; if (memoryItem.FunctionName.EndsWith("()")) memoryItem.FunctionName = memoryItem.FunctionName.Substring(0, memoryItem.FunctionName.Length - 2); stream.Write("function "); stream.Write(memoryItem.FunctionName); stream.Write("() => "); var memoryReference = Field.GetMemoryReference(memoryItem.Address, memoryItem.Size); stream.WriteLine(memoryReference); foreach (var dumpLookup in lookupsToDump) { if (dumpLookup.MemoryAddresses.Count == 1 && dumpLookup.MemoryAddresses[0].Address == memoryItem.Address && dumpLookup.MemoryAddresses[0].Size == memoryItem.Size) { DumpLookup(stream, dumpLookup); lookupsToDump.Remove(dumpLookup); break; } } } else { hadFunction = false; } } foreach (var dumpLookup in lookupsToDump) DumpLookup(stream, dumpLookup); foreach (var dumpAchievement in _achievements.Where(a => a.IsSelected && !a.IsLookup && !a.IsRichPresence)) { var achievementViewModel = _game.Editors.OfType<AchievementViewModel>().FirstOrDefault(a => a.Id == dumpAchievement.Id); if (achievementViewModel == null) continue; stream.WriteLine(); foreach (var ticket in dumpAchievement.OpenTickets) { string notes; if (_ticketNotes.TryGetValue(ticket, out notes)) { var lines = notes.Replace("<br/>", "\n").Split('\n'); stream.Write("// Ticket "); stream.Write(ticket); stream.Write(": "); first = true; const int MaxLength = 103; // 120 - "// Ticket XXXXX: ".Length for (int i = 0; i < lines.Length; i++) { if (first) first = false; else stream.Write("// "); var line = lines[i].Trim(); if (line.Length == 0) { stream.WriteLine(""); continue; } while (line.Length > MaxLength) { var index = line.LastIndexOf(' ', MaxLength - 1); if (index < 0) { stream.WriteLine(line); line = ""; } else { var front = line.Substring(0, index).Trim(); stream.WriteLine(front); line = line.Substring(index + 1).Trim(); if (line.Length > 0) stream.Write("// "); } } if (line.Length > 0) stream.WriteLine(line); } if (first) stream.WriteLine(); } } stream.WriteLine("achievement("); var achievementData = achievementViewModel.Published.Asset as Achievement; stream.Write(" title = \""); stream.Write(EscapeString(achievementData.Title)); stream.Write("\", description = \""); stream.Write(EscapeString(achievementData.Description)); stream.Write("\", points = "); stream.Write(achievementData.Points); stream.WriteLine(","); stream.Write(" id = "); stream.Write(achievementData.Id); stream.Write(", badge = \""); stream.Write(achievementData.BadgeName); stream.Write("\", published = \""); stream.Write(achievementData.Published); stream.Write("\", modified = \""); stream.Write(achievementData.LastModified); stream.WriteLine("\","); stream.Write(" trigger = "); const int indent = 14; // " trigger = ".length DumpTrigger(stream, numberFormat, dumpAchievement, achievementViewModel.Published.TriggerList.First(), indent); stream.WriteLine(); stream.WriteLine(")"); } foreach (var dumpRichPresence in _achievements.Where(a => a.IsRichPresence && a.IsSelected)) { var displayMacro = _macros.FirstOrDefault(m => m.DisplayLines != null); DumpRichPresence(stream, displayMacro, dumpRichPresence, numberFormat); } } } private void DumpLookup(StreamWriter stream, DumpAchievementItem dumpLookup) { var macro = _macros.FirstOrDefault(m => m.Name == dumpLookup.Label); if (macro == null) return; stream.WriteLine(); stream.Write(dumpLookup.Label); stream.WriteLine("Lookup = {"); foreach (var entry in macro.LookupEntries) { if (entry.Key == "*") continue; stream.Write(" "); stream.Write(entry.Key); stream.Write(": \""); stream.Write(EscapeString(entry.Value)); stream.WriteLine("\","); } stream.WriteLine("}"); } private void DumpRichPresence(StreamWriter stream, RichPresenceMacro displayMacro, DumpAchievementItem dumpRichPresence, NumberFormat numberFormat) { int index; foreach (var line in displayMacro.DisplayLines) { string displayString = line; stream.WriteLine(); if (line[0] == '?') { index = line.IndexOf('?', 1); if (index != -1) { var trigger = line.Substring(1, index - 1); var achievement = new AchievementBuilder(); achievement.ParseRequirements(Tokenizer.CreateTokenizer(trigger)); var vmAchievement = new AssetSourceViewModel(null, "RichPresence"); vmAchievement.Asset = achievement.ToAchievement(); stream.Write("rich_presence_conditional_display("); DumpTrigger(stream, numberFormat, dumpRichPresence, vmAchievement.TriggerList.First(), 4); stream.Write(", \""); } ++index; } else { stream.Write("rich_presence_display(\""); index = 0; } var macros = new List<KeyValuePair<string, string>>(); do { var index1 = displayString.IndexOf('@', index); if (index1 == -1) { stream.Write(displayString.Substring(index)); break; } if (index1 > index) stream.Write(displayString.Substring(index, index1 - index)); stream.Write('{'); stream.Write(macros.Count()); stream.Write('}'); var index2 = displayString.IndexOf('(', index1); var index3 = displayString.IndexOf(')', index2); var name = displayString.Substring(index1 + 1, index2 - index1 - 1); var parameter = displayString.Substring(index2 + 1, index3 - index2 - 1); macros.Add(new KeyValuePair<string, string>(name, parameter)); index = index3 + 1; } while (true); stream.Write('"'); foreach (var kvp in macros) { stream.WriteLine(","); stream.Write(" "); var macro = _macros.FirstOrDefault(m => m.Name == kvp.Key); if (macro.LookupEntries != null) { stream.Write("rich_presence_lookup(\""); stream.Write(macro.Name); stream.Write("\", "); } else { stream.Write("rich_presence_value(\""); stream.Write(macro.Name); stream.Write("\", "); } var parameter = kvp.Value; if (parameter[1] == ':') { var achievement = new AchievementBuilder(); achievement.ParseRequirements(Tokenizer.CreateTokenizer(parameter)); if (achievement.CoreRequirements.Count > 0 && achievement.CoreRequirements.Last().Type == RequirementType.Measured) achievement.CoreRequirements.Last().Type = RequirementType.None; var vmAchievement = new AssetSourceViewModel(null, "Rich Presence"); vmAchievement.Asset = achievement.ToAchievement(); DumpTrigger(stream, numberFormat, dumpRichPresence, vmAchievement.TriggerList.First(), 32); } else { DumpLegacyExpression(stream, parameter, dumpRichPresence); } if (macro.LookupEntries != null) { stream.Write(", "); stream.Write(macro.Name); stream.Write("Lookup"); string defaultEntry; if (macro.LookupEntries.TryGetValue("*", out defaultEntry)) { stream.Write(", fallback=\""); stream.Write(EscapeString(defaultEntry)); stream.Write('"'); } stream.Write(')'); } else { if (macro.FormatType != ValueFormat.Value) { stream.Write(", format=\""); stream.Write(Leaderboard.GetFormatString(macro.FormatType)); stream.Write('"'); } stream.Write(')'); } } if (macros.Count() > 0) stream.WriteLine(); stream.WriteLine(')'); } } private static void DumpLegacyExpression(StreamWriter stream, string parameter, DumpAchievementItem dumpRichPresence) { var builder = new StringBuilder(); var parts = parameter.Split('_'); for (int i = 0; i < parts.Length; ++i) { if (i > 0) builder.Append(" + "); var operands = parts[i].Split('*'); for (int j = 0; j < operands.Length; ++j) { if (j > 0) builder.Append(" * "); var operand = operands[j]; if (operand[0] == 'v' || operand[0] == 'V') { operand = operand.Substring(1); if (operand[0] == '-') { if (builder[builder.Length - 2] == '+') { builder[builder.Length - 2] = '-'; operand = operand.Substring(1); } } builder.Append(operand); } else if (operand[0] == 'h' || operand[0] == 'H') { builder.Append("0x"); builder.Append(operand.Substring(1)); } else if (operand.Length > 2 && operand[1] == '.' && operand[0] == '0' && builder[builder.Length - 2] == '*') { bool isDivisor = false; var f = Double.Parse(operand, System.Globalization.NumberFormatInfo.InvariantInfo); if (f > 0.0) { var divisor = 1 / f; if (Math.Abs(Math.Round(divisor) - divisor) < 0.000001) { isDivisor = true; builder[builder.Length - 2] = '/'; builder.Append((int)divisor); } } if (!isDivisor) builder.Append(operand); } else { var field = Field.Deserialize(Tokenizer.CreateTokenizer(operand)); bool needsClosingParenthesis = true; switch (field.Type) { case FieldType.PreviousValue: builder.Append("prev("); break; case FieldType.PriorValue: builder.Append("prior("); break; case FieldType.BinaryCodedDecimal: builder.Append("bcd("); break; default: needsClosingParenthesis = false; break; } if (field.IsMemoryReference) { var memoryItem = dumpRichPresence.MemoryAddresses.FirstOrDefault(m => m.Address == field.Value && m.Size == field.Size); if (memoryItem != null && !String.IsNullOrEmpty(memoryItem.FunctionName)) { builder.Append(memoryItem.FunctionName); builder.Append("()"); } else { builder.Append(Field.GetMemoryReference(field.Value, field.Size)); } } else { builder.Append(operand); } if (needsClosingParenthesis) builder.Append(')'); } } } stream.Write(builder.ToString()); } private static void DumpTrigger(StreamWriter stream, NumberFormat numberFormat, DumpAchievementItem dumpAchievement, TriggerViewModel triggerViewModel, int indent) { var groupEnumerator = triggerViewModel.Groups.GetEnumerator(); groupEnumerator.MoveNext(); bool isCoreEmpty = !groupEnumerator.Current.Requirements.Any(); if (!isCoreEmpty) DumpPublishedRequirements(stream, dumpAchievement, groupEnumerator.Current, numberFormat, indent); bool first = true; while (groupEnumerator.MoveNext()) { if (first) { if (!isCoreEmpty) { stream.WriteLine(" &&"); stream.Write(new string(' ', indent)); } stream.Write('('); first = false; if (triggerViewModel.Groups.Count() == 2) { // only core and one alt, inject an always_false clause to prevent the compiler from joining them stream.Write("always_false() || "); } stream.Write('('); } else { stream.WriteLine(" ||"); stream.Write(new string(' ', indent)); stream.Write(" ("); } DumpPublishedRequirements(stream, dumpAchievement, groupEnumerator.Current, numberFormat, indent + 2); stream.Write(")"); } if (!first) stream.Write(')'); } private static void DumpPublishedRequirements(StreamWriter stream, DumpAchievementItem dumpAchievement, RequirementGroupViewModel requirementGroupViewModel, NumberFormat numberFormat, int indent) { const int MaxWidth = 120; var definition = new StringBuilder(); Parser.AchievementBuilder.AppendStringGroup(definition, requirementGroupViewModel.Requirements.Select(r => r.Requirement), numberFormat, MaxWidth, indent); foreach (var memoryItem in dumpAchievement.MemoryAddresses.Where(m => !String.IsNullOrEmpty(m.FunctionName))) { var memoryReference = Field.GetMemoryReference(memoryItem.Address, memoryItem.Size); var functionCall = memoryItem.FunctionName + "()"; definition.Replace(memoryReference, functionCall); } stream.Write(definition.ToString()); } } }
40.943555
210
0.476983
[ "MIT" ]
Jamiras/RATools
ViewModels/NewScriptDialogViewModel.cs
53,679
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.Extensions.Caching.Memory { /// <summary> /// CacheEntry Stack 是一个链表,每个元素包含了一个 CacheEntry 对象 /// 在调用 Push 方法的时候,就会生成一个新的 CacheEntryStack, 该方法的返回一个 CacheEntryStack, 而且 Previous 属性就是调用 /// 的 CacheEntryStack 对象 /// </summary> internal class CacheEntryStack { private readonly CacheEntryStack _previous; private readonly CacheEntry _entry; private CacheEntryStack() { } private CacheEntryStack(CacheEntryStack previous, CacheEntry entry) { if (previous == null) { throw new ArgumentNullException(nameof(previous)); } _previous = previous; _entry = entry; } public static CacheEntryStack Empty { get; } = new CacheEntryStack(); public CacheEntryStack Push(CacheEntry c) { return new CacheEntryStack(this, c); } public CacheEntry Peek() { return _entry; } } }
26.413043
111
0.6107
[ "Apache-2.0" ]
gaufung/Extensions
src/Caching/Memory/src/CacheEntryStack.cs
1,323
C#
/* Copyright 2019 Christian Bender christian1.bender@student.uni-siegen.de 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 DCAKeyRecovery.Logic.Cipher3 { public class Cipher3Characteristic : Characteristic { /// <summary> /// Constructor /// </summary> public Cipher3Characteristic() { InputDifferentials = new ushort[5]; OutputDifferentials = new ushort[4]; for (int i = 0; i < InputDifferentials.Length; i++) { InputDifferentials[i] = 0; } for (int i = 0; i < OutputDifferentials.Length; i++) { OutputDifferentials[i] = 0; } } /// <summary> /// override of Clone() /// </summary> /// <returns></returns> public override object Clone() { Characteristic obj = new Cipher3Characteristic { InputDifferentials = (ushort[])InputDifferentials.Clone(), OutputDifferentials = (ushort[])OutputDifferentials.Clone(), Probability = Probability }; return obj; } /// <summary> /// override of ToString() /// </summary> /// <returns></returns> public override string ToString() { return "Prob: " + Probability + " InputDiffRound5: " + InputDifferentials[4] + " OutputDiffRound4: " + OutputDifferentials[3] + " InputDiffRound4: " + InputDifferentials[3] + " OutputDiffRound3: " + OutputDifferentials[2] + " InputDiffRound3: " + InputDifferentials[2] + " OutputDiffRound2: " + OutputDifferentials[1] + " InputDiffRound2: " + InputDifferentials[1] + " OutputDiffRound1: " + OutputDifferentials[0] + " InputDiffRound1: " + InputDifferentials[0]; } } }
34.942857
114
0.581766
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/DCAKeyRecovery/Logic/Cipher3/Cipher3Characteristic.cs
2,448
C#
namespace EZNEW.Cache.Keys { /// <summary> /// Move response /// </summary> public class MoveResponse : CacheResponse { } }
15.8
46
0.537975
[ "MIT" ]
eznew-net/EZNEW.Develop
EZNEW/Cache/Keys/Response/MoveResponse.cs
160
C#
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; // 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("Microsoft.Practices.Prism.UnityExtensions")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Prism")] [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("42402988-a9aa-4545-9f54-2ab613c5af70")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguageAttribute("en")]
50.547619
86
0.640603
[ "MIT" ]
cointoss1973/Prism4.1-WPF
PrismLibrary/Desktop/Prism.UnityExtensions/Properties/AssemblyInfo.cs
2,123
C#
namespace OpenRpg.Localization.Data.DataSources { public interface ILocaleDataSource { object NativeSource { get; } string Get(string localeCode, string key); void Create(string localeCode, string text, string key); void Update(string localeCode, string text, string key); bool Delete(string localeCode, string key); bool Exists(string localeCode, string key); LocaleDataset GetLocaleDataset(string localeCode); } }
37.153846
64
0.693582
[ "MIT" ]
openrpg/core
src/OpenRpg.Localization/Data/DataSources/ILocaleDataSource.cs
483
C#
namespace SQLiteLogViewer { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; /// <summary> /// Interaction logic for QueryWindow.xaml /// </summary> public partial class QueryWindow : Window { public QueryWindow() { this.InitializeComponent(); } } }
23.714286
46
0.65512
[ "MIT" ]
Bhaskers-Blu-Org2/sqlite-tracer
Source/Windows/QueryWindow.xaml.cs
666
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.NAS20170626.Models { public class CancelDirQuotaResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("Success")] [Validation(Required=true)] public bool? Success { get; set; } } }
20.478261
54
0.658174
[ "Apache-2.0" ]
atptro/alibabacloud-sdk
nas-20170626/csharp/core/Models/CancelDirQuotaResponse.cs
471
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Common { using System; using System.Collections.Generic; /// <summary> /// Describes capacity information for services of this application. This description can be used for describing the /// following. /// - Reserving the capacity for the services on the nodes /// - Limiting the total number of nodes that services of this application can run on /// - Limiting the custom capacity metrics to limit the total consumption of this metric by the services of this /// application /// </summary> public partial class ApplicationCapacityDescription { /// <summary> /// Initializes a new instance of the ApplicationCapacityDescription class. /// </summary> /// <param name="minimumNodes">The minimum number of nodes where Service Fabric will reserve capacity for this /// application. Note that this does not mean that the services of this application will be placed on all of those /// nodes. If this property is set to zero, no capacity will be reserved. The value of this property cannot be more /// than the value of the MaximumNodes property.</param> /// <param name="maximumNodes">The maximum number of nodes where Service Fabric will reserve capacity for this /// application. Note that this does not mean that the services of this application will be placed on all of those /// nodes. By default, the value of this property is zero and it means that the services can be placed on any /// node.</param> /// <param name="applicationMetrics">List of application capacity metric description.</param> public ApplicationCapacityDescription( long? minimumNodes = default(long?), long? maximumNodes = 0, IEnumerable<ApplicationMetricDescription> applicationMetrics = default(IEnumerable<ApplicationMetricDescription>)) { minimumNodes?.ThrowIfLessThan("minimumNodes", 0); maximumNodes?.ThrowIfLessThan("maximumNodes", 0); this.MinimumNodes = minimumNodes; this.MaximumNodes = maximumNodes; this.ApplicationMetrics = applicationMetrics; } /// <summary> /// Gets the minimum number of nodes where Service Fabric will reserve capacity for this application. Note that this /// does not mean that the services of this application will be placed on all of those nodes. If this property is set /// to zero, no capacity will be reserved. The value of this property cannot be more than the value of the MaximumNodes /// property. /// </summary> public long? MinimumNodes { get; } /// <summary> /// Gets the maximum number of nodes where Service Fabric will reserve capacity for this application. Note that this /// does not mean that the services of this application will be placed on all of those nodes. By default, the value of /// this property is zero and it means that the services can be placed on any node. /// </summary> public long? MaximumNodes { get; } /// <summary> /// Gets list of application capacity metric description. /// </summary> public IEnumerable<ApplicationMetricDescription> ApplicationMetrics { get; } } }
55.257576
127
0.658898
[ "MIT" ]
Bhaskers-Blu-Org2/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Common/Generated/ApplicationCapacityDescription.cs
3,647
C#
namespace DragonSpark.Compose.Extents.Results; public sealed class DefaultExtent<T> : ResultExtent<T> { public static DefaultExtent<T> Default { get; } = new DefaultExtent<T>(); DefaultExtent() {} }
25.375
74
0.743842
[ "MIT" ]
DragonSpark/Framework
DragonSpark/Compose/Extents/Results/DefaultExtent.cs
205
C#
using System; using System.Runtime.Serialization; using TOTVS.Fullstack.Challenge.AuctionHouse.Domain.Constants; namespace TOTVS.Fullstack.Challenge.AuctionHouse.Domain.Exceptions { /// <summary> /// Exceção lançada quando um parâmetro que passar por validação for inválido /// </summary> [Serializable] public class InvalidParameterException : Exception { /// <summary> /// Mensagem da exceção /// </summary> public override string Message { get; } /// <summary> /// Nome do parâmetro inválido /// </summary> public string ParameterName { get; } /// <summary> /// Construtor padrão /// </summary> /// <param name="parameterName">Tipo do recurso</param> public InvalidParameterException(string parameterName) : base() { ParameterName = parameterName; Message = String.Format(ErrorMessage.InvalidParameterException, ParameterName); } /// <summary> /// Construtor de serialização /// </summary> /// <param name="info">Dados de serialização</param> /// <param name="context">Contexto de fluxo de dados</param> protected InvalidParameterException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
31.72093
115
0.620968
[ "MIT" ]
jpmoura/TotvsFullstackChallenge
API/TOTVS.Fullstack.Challenge.AuctionHouse.Domain/Exceptions/InvalidParameterException.cs
1,382
C#
namespace Cosmos.I18N.Countries.Oceania { /// <summary> /// 澳大利亚(The Commonwealth of Australia,大洋洲,AU,AUS,036),澳大利亚联邦 <br /> /// Cosmos i18n code: i18n_country_aodaliya /// </summary> public static class Australia { // ReSharper disable once InconsistentNaming private static readonly CountryInfo _country; static Australia() { _country = new CountryInfo { Country = Country.Australia, CountryType = CountryType.Country, BeongsToCountry = Country.Australia, UNCode = "036", Alpha2Code = "AU", Alpha3Code = "AUS", Name = "The Commonwealth of Australia", ShorterForm = "Argentina", ChineseName = "澳大利亚联邦", ChineseShorterForm = "澳大利亚", Continent = Continent.Oceania, CommonwealthOfNations = true, I18NIdentityCode = I18N_IDENTITY_CODE, }; } /// <summary> /// 澳大利亚(The Commonwealth of Australia,大洋洲,AU,AUS,036),澳大利亚联邦 <br /> /// Cosmos i18n code: i18n_country_aodaliya /// </summary> public static CountryInfo Instance => _country; /// <summary> /// i18n /// </summary> // ReSharper disable once InconsistentNaming public const string I18N_IDENTITY_CODE = "i18n_country_aodaliya"; } }
36.275
76
0.560303
[ "Apache-2.0" ]
awesomedotnetcore/I18N
src/Cosmos.I18N.Countries/Cosmos/I18N/Countries/Oceania/Australia.cs
1,551
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Global // ReSharper disable StringLiteralTypo // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedParameter.Local // ReSharper disable UnusedType.Global /* DatabaseInfoCommand.cs -- получение информации о базе данных * Ars Magna project, http://arsmagna.ru */ #region Using directives using System; using AM; using ManagedIrbis.Direct; #endregion #nullable enable namespace ManagedIrbis.Server.Commands { /// <summary> /// Получение информации о базе данных. /// </summary> public class DatabaseInfoCommand : ServerCommand { #region Construction /// <summary> /// Конструктор. /// </summary> public DatabaseInfoCommand ( WorkData data ) : base(data) { } // constructor #endregion #region Private members private static void _WriteRecords ( ServerResponse response, int[]? mfns ) { if (!ReferenceEquals(mfns, null) && mfns.Length != 0) { var line = string.Join(",", mfns); response.WriteAnsiString(line); } response.NewLine(); } // method _WriteRecords #endregion #region ServerCommand members /// <inheritdoc cref="ServerCommand.Execute" /> public override void Execute() { var engine = Data.Engine.ThrowIfNull(); engine.OnBeforeExecute(Data); try { var context = engine.RequireAdministratorContext(Data); Data.Context = context; UpdateContext(); var request = Data.Request.ThrowIfNull(); var database = request.RequireAnsiString(); DatabaseInfo info; using (var direct = engine.GetDatabase(database)) { info = direct.GetDatabaseInfo(); } var response = Data.Response.ThrowIfNull(); response.WriteInt32(0).NewLine(); _WriteRecords(response, info.LogicallyDeletedRecords); _WriteRecords(response, info.PhysicallyDeletedRecords); _WriteRecords(response, info.NonActualizedRecords); _WriteRecords(response, info.LockedRecords); response.WriteInt32(info.MaxMfn).NewLine(); response.WriteInt32(info.DatabaseLocked ? 1 : 0).NewLine(); SendResponse(); } catch (IrbisException exception) { SendError(exception.ErrorCode); } catch (Exception exception) { Magna.TraceException(nameof(DatabaseInfoCommand) + "::" + nameof(Execute), exception); SendError(-8888); } engine.OnAfterExecute(Data); } // method Execute #endregion } // class DatabaseInfoCommand } // namespace ManagedIrbis.Server.Commands
28.007874
102
0.581108
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Libs/ManagedIrbis5/Source/Server/Commands/DatabaseInfoCommand.cs
3,630
C#
using System; using System.Collections.Generic; using UnityEngine.Events; #if OBJECTPOOL_DEBUG using UnityEngine; #endif namespace CoreGame { public class ObjectPool<T> where T : class { public delegate T0 UnityFunc<T0>(string name); private readonly Stack<T> stack; private readonly UnityAction<T> onGet; private readonly UnityAction<T> onRelease; private readonly UnityFunc<T> onNew; public string Name { get; set; } public int CountAll { get; private set; } public int CountActive { get { return CountAll - CountInactive; } } public int CountInactive { get { return stack.Count; } } public ObjectPool(int capacity, UnityFunc<T> actionNew, UnityAction<T> actionOnGet = null, UnityAction<T> actionOnRelease = null, string name = null) { if (actionNew == null) throw new ArgumentException("New action can't be null!"); stack = new Stack<T>(capacity); onNew = actionNew; onGet = actionOnGet; onRelease = actionOnRelease; Name = name; } public void WarmUp(int count) { for (var i = 0; i < count; i++) { var element = onNew(Name); CountAll++; stack.Push(element); } } public T Get() { #if OBJECTPOOL_DEBUG var created = false; #endif T element; if (stack.Count == 0) { #if OBJECTPOOL_DEBUG created = true; logWarning("Created an object."); #endif element = onNew(Name); CountAll++; } else { element = stack.Pop(); } if (onGet != null) onGet(element); #if OBJECTPOOL_DEBUG log(string.Format("Getting object from pool. New: {0}, count: {1}, left: {2}", created, CountAll, stack.Count)); #endif return element; } public void Release(T element) { if (stack.Contains(element)) { #if OBJECTPOOL_DEBUG log(string.Format("Dupe release")); #endif return; } #if OBJECTPOOL_DEBUG if (stack.Count > 0 && ReferenceEquals(stack.Peek(), element)) logError("Internal error. Trying to destroy object that is already released to pool."); #endif if (onRelease != null) onRelease(element); stack.Push(element); #if OBJECTPOOL_DEBUG log(string.Format("Returned object to pool. Left: {0}", stack.Count)); #endif } public void Release(object element) { var obj = (T)element; if (obj == null) return; Release(obj); } #if OBJECTPOOL_DEBUG private void log(string message) { if (string.IsNullOrEmpty(Name)) return; UnityEngine.Debug.LogFormat("[{0}] ObjectPool ({1}): {2}", DateTime.Now.ToString("hh:mm:ss.fff"), Name, message); } private void logWarning(string message) { if (string.IsNullOrEmpty(Name)) return; UnityEngine.Debug.LogWarningFormat("[{0}] ObjectPool ({1}): {2}", DateTime.Now.ToString("hh:mm:ss.fff"), Name, message); } private void logError(string message) { if (string.IsNullOrEmpty(Name)) return; UnityEngine.Debug.LogErrorFormat("[{0}] ObjectPool ({1}): {2}", DateTime.Now.ToString("hh:mm:ss.fff"), Name, message); } #endif } }
28.658915
132
0.536381
[ "MIT" ]
binhnguyen86/VNGFps
Assets/Scripts/FrameworkHelper/PoolHelper/ObjectPool.cs
3,699
C#
using Microsoft.Extensions.Logging; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SrcSet.Core; using Statiq.Common; namespace SrcSet.Statiq; public class CreateResponsiveImages : ParallelModule { private readonly Func<Stream, Task<Image>> _loadImage; private readonly IEnumerable<ushort> _widths; public CreateResponsiveImages(Func<Stream, Task<Image>> loadImage, IEnumerable<ushort> widths) { _loadImage = loadImage; _widths = widths; } protected override async Task<IEnumerable<IDocument>> ExecuteInputAsync(IDocument input, IExecutionContext context) { var inputStream = input.GetContentStream(); var destinations = _widths.Select(w => input.Source.GetDestination(w)).ToList(); var cached = destinations.Select(d => context.FileSystem.GetOutputFile(d)).Where(f => f.Exists).ToList(); var alreadyDone = cached.Count == destinations.Count; if (alreadyDone) { context.Log(LogLevel.Debug, "Skipping {source} since all sizes already exist", input.Source); var docs = cached.Select(f => CachedDocument(input.Source, f.Path, f, context)); return await Task.WhenAll(docs); } var image = await _loadImage(inputStream); var documents = _widths.Select(w => GetResizedDocument(input.Source, image, w, context)); return await Task.WhenAll(documents); } private static async Task<IDocument> GetResizedDocument(NormalizedPath source, Image image, ushort width, IExecutionContext context) { var destination = source.GetDestination(width); var cached = context.FileSystem.GetOutputFile(destination); if (cached.Exists) { context.Log(LogLevel.Debug, "Skipping {destination} since it already exists", destination); return await CachedDocument(source, destination, cached, context); } var encoder = image.DetectEncoder(destination.ToString()); var output = new MemoryStream(); context.Log(LogLevel.Debug, "Resizing {source} to {destination}...", source, destination); var newSize = image.Size().Resize(width); using var resized = image.Resize(newSize); await resized.SaveAsync(output, encoder); var content = context.GetContentProvider(output); return context.CreateDocument(source, destination, content); } private static async Task<IDocument> CachedDocument(NormalizedPath source, NormalizedPath destination, IFile cached, IExecutionContext context) { var stream = new MemoryStream(); await cached.OpenRead().CopyToAsync(stream); var content = context.GetContentProvider(stream); return context.CreateDocument(source, context.FileSystem.GetRelativeOutputPath(destination), content); } }
38.701493
144
0.76668
[ "MIT" ]
ecoAPM/SrcSet
SrcSet.Statiq/CreateResponsiveImages.cs
2,593
C#
namespace UCS.Database { using System.Data.Entity; using System.Data.Entity.Infrastructure; public class Mysql : DbContext { public Mysql() : base("name=mysql") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Clan> Clan { get; set; } public virtual DbSet<Player> Player { get; set; } } }
24.1
76
0.609959
[ "MIT" ]
antzsmt/Ultrapowa-Boom-Beach-Server
Ultrapowa Boom Beach Server/Database/Mysql.cs
484
C#
/* Copyright 2014 Eduardo Yuschuk (eduardo.yuschuk@gmail.com) */ using System; using System.IO; using System.Globalization; namespace QuotesConversion { public class QuotesConverter { private static char[] _separator = new char[] {','}; private static CultureInfo _culture = CultureInfo.GetCultureInfo("en-US"); private static DateTime _epoch = new DateTime(1970, 1, 1); public interface IQuoteDateTimeParser { /// <summary> /// Convierte una representación de fecha en texto, en cualquier formato, en un entero largo conteniendo la cantidad de milisegundos desde la época. /// </summary> /// <param name="text">La fecha en un formato cualquiera que será soportado por la implementación.</param> /// <returns>La cantidad de milisegundos desde la época</returns> long Parse(string text); } public class QuoteDateTimeAsNumberParser : IQuoteDateTimeParser { public static IQuoteDateTimeParser Instance { get; } = new QuoteDateTimeAsNumberParser(); public long Parse(string text) { return long.Parse(text); } } public class QuoteDateTimeAsTextParser : IQuoteDateTimeParser { private string _format; private CultureInfo _cultureInfo; public QuoteDateTimeAsTextParser(string format, CultureInfo cultureInfo) { _format = format; _cultureInfo = cultureInfo; } public long Parse(string text) { var dateTime = DateTime.ParseExact(text, _format, _cultureInfo); var inContext = dateTime - _epoch; var totalMilliseconds = inContext.TotalMilliseconds; return (long) totalMilliseconds; } } public static DateTime GetQuoteDateTimeFromString(string text, IQuoteDateTimeParser parser) { string[] parts = text.Split(_separator); long time = parser.Parse(parts[0]); return _epoch + TimeSpan.FromMilliseconds(time); } public static void GetQuoteDateTimeFromString(string text, out DateTime dateTime) { string[] parts = text.Split(_separator); long time = long.Parse(parts[0]); dateTime = _epoch + TimeSpan.FromMilliseconds(time); } public static void GetQuoteDateTimeFromString(string text, out DateTime dateTime, out long time) { string[] parts = text.Split(_separator); time = long.Parse(parts[0]); dateTime = _epoch + TimeSpan.FromMilliseconds(time); } public static void GetQuoteFromString(string text, out DateTime dateTime, out decimal ask, out decimal bid) { string[] parts = text.Split(_separator); long time = long.Parse(parts[0]); dateTime = _epoch + TimeSpan.FromMilliseconds(time); ask = decimal.Parse(parts[1], _culture); bid = decimal.Parse(parts[2], _culture); } public static void GetQuoteFromString(string text, out DateTime dateTime, out long time, out decimal ask, out decimal bid, IQuoteDateTimeParser parser) { string[] parts = text.Split(_separator); time = parser.Parse(parts[0]); dateTime = _epoch + TimeSpan.FromMilliseconds(time); ask = decimal.Parse(parts[1], _culture); bid = decimal.Parse(parts[2], _culture); } public static bool GetQuoteDateTimeFromBinaryReader(BinaryReader reader, out DateTime dateTime) { if (reader == null) { dateTime = default(DateTime); return false; } try { long time = reader.ReadInt64(); dateTime = _epoch + TimeSpan.FromMilliseconds(time); reader.ReadDecimal(); reader.ReadDecimal(); return true; } catch (Exception) { dateTime = default(DateTime); return false; } } public static bool GetQuoteDateTimeFromStreamReader(StreamReader reader, out DateTime dateTime) { if (reader == null) { dateTime = default(DateTime); return false; } try { string line = reader.ReadLine(); GetQuoteDateTimeFromString(line, out dateTime); return true; } catch (Exception) { dateTime = default(DateTime); return false; } } public static bool GetQuoteFromBinaryReader(BinaryReader reader, out DateTime dateTime, out decimal ask, out decimal bid) { if (reader == null) { dateTime = default(DateTime); ask = default(decimal); bid = default(decimal); return false; } try { long time = reader.ReadInt64(); dateTime = _epoch + TimeSpan.FromMilliseconds(time); ask = reader.ReadDecimal(); bid = reader.ReadDecimal(); return true; } catch (Exception) { dateTime = default(DateTime); ask = default(decimal); bid = default(decimal); return false; } } } }
34.035503
160
0.544159
[ "MIT" ]
eduardo-yuschuk/cs_trading
QuotesConversion/QuotesConverter.cs
5,759
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookRangeFormatAutofitRowsRequest. /// </summary> public partial interface IWorkbookRangeFormatAutofitRowsRequest : IBaseRequest { /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task PostAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookRangeFormatAutofitRowsRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookRangeFormatAutofitRowsRequest Select(string value); } }
36.795918
153
0.583472
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/IWorkbookRangeFormatAutofitRowsRequest.cs
1,803
C#
using System; using System.Runtime.CompilerServices; namespace NetFabric.Hyperlinq { public static partial class ArrayExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Count<TSource>(this in ArraySegment<TSource> source) => source.Count; static int Count<TSource>(this in ArraySegment<TSource> source, Predicate<TSource> predicate) { var counter = 0; if (source.Any()) { if (source.IsWhole()) { foreach (var item in source.Array) counter += predicate(item).AsByte(); } else { var array = source.Array; var end = source.Offset + source.Count - 1; for (var index = source.Offset; index <= end; index++) counter += predicate(array![index]).AsByte(); } } return counter; } static int Count<TSource>(this in ArraySegment<TSource> source, PredicateAt<TSource> predicate) { var counter = 0; if (source.Any()) { if (source.IsWhole()) { var index = 0; foreach (var item in source.Array) { counter += predicate(item, index).AsByte(); index++; } } else { var array = source.Array; var end = source.Count - 1; if (source.Offset == 0) { for (var index = 0; index <= end; index++) counter += predicate(array![index], index).AsByte(); } else { var offset = source.Offset; for (var index = 0; index <= end; index++) counter += predicate(array![index + offset], index).AsByte(); } } } return counter; } } }
32.898551
103
0.413216
[ "MIT" ]
manofstick/NetFabric.Hyperlinq
NetFabric.Hyperlinq/Aggregation/Count/Count.ArraySegment.cs
2,270
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace jaytwo.FoscamLib.Test { [TestClass] public class FoscamHdUrlBuilderTests { private static FoscamHdUrlBuilder GetTestFoscamHdUrlBuilder() { var result = new FoscamHdUrlBuilder(); result.Host = "host"; result.Port = 123; result.Username = "me@you.com"; result.Password = "password"; return result; } [TestMethod] public void FoscamHdUrlBuilder_GetRootUrl() { var builder = GetTestFoscamHdUrlBuilder(); builder.UseHttps = false; Assert.AreEqual("http://host:123/", builder.GetRootUrl()); Assert.AreEqual(builder.GetRootUrl(), builder.GetRootUri().AbsoluteUri); builder.UseHttps = true; Assert.AreEqual("https://host:123/", builder.GetRootUrl()); } [TestMethod] public void FoscamHdUrlBuilder_GetCommandUrl() { var builder = GetTestFoscamHdUrlBuilder(); var command = "hello"; Assert.AreEqual("http://host:123/cgi-bin/CGIProxy.fcgi?cmd=hello&usr=me%40you.com&pwd=password", builder.GetCommandUrl(command)); } [TestMethod] public void FoscamHdUrlBuilder_GetSnapshotUrlMainStream() { var builder = GetTestFoscamHdUrlBuilder(); Assert.AreEqual("http://host:123/cgi-bin/CGIProxy.fcgi?cmd=snapPicture&usr=me%40you.com&pwd=password", builder.GetSnapshotUrlMainStream()); } [TestMethod] public void FoscamHdUrlBuilder_GetSnapshotUrlSubStream() { var builder = GetTestFoscamHdUrlBuilder(); Assert.AreEqual("http://host:123/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=me%40you.com&pwd=password", builder.GetSnapshotUrlSubStream()); } [TestMethod] public void FoscamHdUrlBuilder_GetVideoUrlMainStream() { var builder = GetTestFoscamHdUrlBuilder(); var expectedWithCredentials = "rtsp://me%40you.com:password@host:123/videoMain"; builder.UseHttps = false; Assert.AreEqual(expectedWithCredentials, builder.GetVideoUrlMainStream()); builder.UseHttps = true; Assert.AreEqual(expectedWithCredentials, builder.GetVideoUrlMainStream()); var expectedWithoutCredentials = "rtsp://host:123/videoMain"; builder.UseHttps = false; Assert.AreEqual(expectedWithoutCredentials, builder.GetVideoUrlMainStream(false)); builder.UseHttps = true; Assert.AreEqual(expectedWithoutCredentials, builder.GetVideoUrlMainStream(false)); } [TestMethod] public void FoscamHdUrlBuilder_GetVideoUrlSubStream() { var builder = GetTestFoscamHdUrlBuilder(); var expected = "rtsp://me%40you.com:password@host:123/videoSub"; builder.UseHttps = false; Assert.AreEqual(expected, builder.GetVideoUrlSubStream()); builder.UseHttps = true; Assert.AreEqual(expected, builder.GetVideoUrlSubStream()); var expectedWithoutCredentials = "rtsp://host:123/videoSub"; builder.UseHttps = false; Assert.AreEqual(expectedWithoutCredentials, builder.GetVideoUrlSubStream(false)); builder.UseHttps = true; Assert.AreEqual(expectedWithoutCredentials, builder.GetVideoUrlSubStream(false)); } } }
28.877358
142
0.752369
[ "MIT" ]
jakegough/jaytwo.FoscamLib
Test/FoscamHdUrlBuilderTests.cs
3,063
C#