content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// <autogenerated> // This file was generated by T4 code generator Median.int.tt. // Any changes made to this file manually will be lost next time the file is regenerated. // </autogenerated> using System; using System.Linq; using System.Dynamic; using System.Collections; using System.Threading.Tasks; using static Ramda.NET.Currying; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Ramda.NET { public static partial class R { /// <summary> /// Returns the median of the given list of numbers. /// <para /> /// sig: [Number] -> Number /// </summary> /// <param name="list">first</param> /// <returns>Number</returns> public static dynamic Median(IList<int> list) { return Currying.Median(list); } } }
25.566667
91
0.706649
[ "MIT" ]
sagifogel/Ramda.NET
Ramda/Median.int.cs
769
C#
using System.Collections.Generic; namespace Darwin.Syntax.Expressions { internal sealed record UnaryExpression(SyntaxToken Operator, DarwinExpression Expression) : DarwinExpression { public override DarwinExpressionType Type => DarwinExpressionType.Unary; public override IEnumerable<SyntaxNode> GetChildren() { yield return Operator; yield return Expression; } } }
29.066667
112
0.701835
[ "MIT" ]
ivanbiljan/darwin
src/Darwin/Syntax/Expressions/UnaryExpression.cs
438
C#
using FluentAssertions; using Microsoft.CSharp.RuntimeBinder; using Xerris.DotNet.Core.Validations; using Xunit; namespace Xerris.DotNet.Core.Test.Core.Validations { public class ValidationExceptionTest { [Fact] public void CanConstruct() { var validationException = new ValidationException(new RuntimeBinderException("poopoo")); validationException.Message.Should().Be("poopoo"); } } }
26.764706
100
0.692308
[ "MIT" ]
xerris/Xerris.DotNet.Core
test/Xerris.DotNet.Core.Test/Core/Validations/ValidationExceptionTest.cs
455
C#
using UnityEngine; using System.Collections; public class FauxGravityAttractor : MonoBehaviour { public float gravity = -10; private ConstantForce seudograv = Addforce(gravityUp * gravity); public void Attract (Transform body) { Vector3 gravityUp = (body.position - transform.position).normalized; Vector3 bodyUp = body.up; body.GetComponent<Rigidbody>seudograv; Quaternion targetRotation = Quaternion.FromToRotation(bodyUp,gravityUp) * body.rotation; body.rotation = Quaternion.Slerp(body.rotation,targetRotation,50*Time.deltaTime); } }
29.368421
90
0.781362
[ "Apache-2.0" ]
FunktronicLabs/FunkyVR
FunkyPlanets/Assets/scripts/FauxGravityAttractor.cs
560
C#
using System.Threading.Tasks; namespace ExistForAll.SimpleSettings.Validations { public interface ISettingValidation<T> : ISettingsValidator { Task<ValidationResult> Validate(ValidationContext<T> context); } }
26.444444
71
0.735294
[ "MIT" ]
existall/Settings
src/Core/ExistForAll.SimpleSettings/Validations/ISettingValidation.cs
238
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using EfsTools.Items; using EfsTools.Mbn; using EfsTools.Qualcomm; using EfsTools.Qualcomm.QcdmCommands.Base; using EfsTools.Resourses; using EfsTools.Utils; using EfsTools.WebDAV; using Microsoft.Extensions.Configuration; using NWebDav.Server; using NWebDav.Server.Http; using NWebDav.Server.HttpListener; using NWebDav.Server.Stores; namespace EfsTools { internal class EfsTools { private readonly EfsToolsConfigurationSection _config; private readonly IConfigurationRoot _configurationRoot; private readonly Logger _logger; public EfsTools(Logger logger) { var builder = new ConfigurationBuilder(); var module = Assembly.GetCallingAssembly().ManifestModule; var modulePath = $"{module.FullyQualifiedName}.config"; _configurationRoot = builder.AddXmlFile(modulePath, false, false).Build(); _config = new EfsToolsConfigurationSection(_configurationRoot); _logger = logger; } public void GetTargetInfo() { using (var manager = OpenQcdmManager()) { var diagVersion = manager.DiagVersion; var version = manager.Version; var buildId = manager.BuildId; var guid = manager.Guid; var gsmVersion = manager.Gsm.Version; var state = manager.CallManager.CallState; var serialNo = manager.Nv.ReadString(2824).TrimEnd('\0'); var imei = manager.Imei; var systemTime = manager.SystemTime; _logger.LogInfo( $"Imei: {imei}, " + $"SerialNo: '{serialNo}', " + $"MobileSoftwareId: '{buildId.MobileSoftwareId}', DiagVersion: {diagVersion}, CompilationDate: '{version.CompilationDate}', CompilationTime: '{version.CompilationTime}', ReleaseDate: '{version.ReleaseDate}', ReleaseTime: '{version.ReleaseTime}', " + $"VersionDirectory: '{version.VersionDirectory}', MobileFirmwareRevision: {version.MobileFirmwareRevision}, MobileCaiRevision: {version.MobileCaiRevision}, MobileModel: {version.MobileModel}, " + $"StationClassMask: {version.StationClassMask}, SlotCycleIndex: {version.SlotCycleIndex}, HwVersion: {version.HwVersionMajor}.{version.HwVersionMinor}, " + $"MSM: 0x{buildId.Msm:X}, MobileModelId: {buildId.MobileModelId}, MobileModelName: {buildId.MobileModelName}, " + $"Guid: '{guid}', SystemTime: '{systemTime}'"); if (gsmVersion != null) { _logger.LogInfo( $"GSM VocorerDspVersion: 0x{gsmVersion.VocorerDspVersion:X}, MdspVersionRom: 0x{gsmVersion.MdspVersionRom:X}, MdspVersionRam: 0x{gsmVersion.MdspVersionRam:X}"); } _logger.LogInfo($"Call state: 0x{state:X}"); } } public void GetLog(string messageMask, string logMask, bool verbose) { var enabledMessageMasks = string.IsNullOrEmpty(messageMask) ? new MessageId[0] : messageMask.Split(',') .Select(it => (MessageId) EnumUtils.ParseEnumInt(typeof(MessageId), it, _logger)) .ToArray(); var enabledLogMasks = string.IsNullOrEmpty(logMask) ? new LogId[0] : logMask.Split(',').Select(it => (LogId) EnumUtils.ParseEnumInt(typeof(LogId), it, _logger)) .ToArray(); using (var manager = OpenQcdmManager()) { if (verbose) { if (enabledMessageMasks.Length > 0) { _logger.LogInfo(Strings.QcdmLogSubcribingToMessagesFormat, string.Join(", ", enabledMessageMasks)); } if (enabledLogMasks.Length > 0) { _logger.LogInfo(Strings.QcdmLogSubcribingToLogsFormat, string.Join(", ", enabledLogMasks)); } } var count1 = manager.DiagServ.DebugMessageDroppedCount; var count2 = manager.DiagServ.DebugMessageAllocationCount; var count5 = manager.DiagServ.LogDroppedCount; var count6 = manager.DiagServ.LogAllocationCount; manager.DisableEventReports(); manager.DisableMessages(); manager.DisableLogs(); var affectedMessages = new HashSet<MessageId>(manager.SetMessageMask(enabledMessageMasks)); var affectedLogs = new HashSet<LogId>(manager.SetLogMask(enabledLogMasks)); if (verbose) { if (enabledMessageMasks.Length > 0) { foreach (var enabledMessageMask in enabledMessageMasks) { if (!affectedMessages.Contains(enabledMessageMask)) { _logger.LogWarning(Strings.QcdmLogSubcribingMessageNotSupportedErrorFormat, enabledMessageMask); } } _logger.LogInfo(Strings.QcdmLogSubcribingToMessagesResultFormat, string.Join(", ", affectedMessages)); } if (enabledLogMasks.Length > 0) { foreach (var enabledLogMask in enabledLogMasks) { if (!affectedLogs.Contains(enabledLogMask)) { _logger.LogWarning(Strings.QcdmLogSubcribingLogNotSupportedErrorFormat, enabledLogMask); } } _logger.LogInfo(Strings.QcdmLogSubcribingToLogsResultFormat, string.Join(", ", affectedLogs)); } } var cancellationTokenSource = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { cancellationTokenSource.Cancel(); }; manager.ProcessLogs(_logger, cancellationTokenSource.Token); } } public void GetTime() { using (var manager = OpenQcdmManager()) { var time = manager.SystemTime; _logger.LogInfo($"Time: {time}"); } } public void GetEfsInfo() { using (var manager = OpenQcdmManager()) { var helloInfo = manager.Efs.HelloInfo; var efsInfo = manager.Efs.EfsInfo; _logger.LogInfo( $"Version: {helloInfo.Version}, MaxDirectories: {efsInfo.MaxDirectories}, MapPathnameLength: {efsInfo.MapPathnameLength}, " + $"MaxFileSize: {efsInfo.MaxFileSize}, MaxFilenameLength: {efsInfo.MaxFilenameLength}, MaxMounts: {efsInfo.MaxMounts}, " + $"MaxSymlinkDepth: {efsInfo.MaxSymlinkDepth}"); } } public void EfsReadFile(string efsPath, string computerPath) { if (!string.IsNullOrEmpty(efsPath)) { using (var manager = OpenQcdmManager()) { FileUtils.PhoneReadFile(manager, efsPath, computerPath, _logger); } } } public void EfsWriteFile(string computerPath, string efsPath, bool create, bool itemFile) { if (!string.IsNullOrEmpty(efsPath) && !string.IsNullOrEmpty(computerPath)) { using (var manager = OpenQcdmManager()) { FileUtils.PhoneWriteFile(manager, computerPath, efsPath, 0777, itemFile, _logger); } } } public void EfsRenameFile(string efsPath, string newEfsPath) { if (!string.IsNullOrEmpty(efsPath) && !string.IsNullOrEmpty(newEfsPath)) { using (var manager = OpenQcdmManager()) { var efs = manager.Efs; efs.RenameFile(efsPath, newEfsPath); efs.SyncNoWait(newEfsPath, 1); } } } public void EfsDownloadDirectory(string efsPath, string computerPath, bool noExtraData, bool processNvItems) { if (!string.IsNullOrEmpty(efsPath) && !string.IsNullOrEmpty(computerPath)) { using (var manager = OpenQcdmManager()) { var path1 = PathUtils.FixUnixPath(efsPath); var path2 = PathUtils.FixPath(computerPath); FileUtils.PhoneDownloadDirectory(manager, path1, path2, noExtraData, _logger); if (processNvItems) { NvItemUtils.PhoneDownloadNvItems(manager, path2, _logger); } } } } public void EfsUploadDirectory(string computerPath, string efsPath, bool createItemFilesAsDefault, bool processNvItems) { if (!string.IsNullOrEmpty(efsPath) && !string.IsNullOrEmpty(computerPath)) { var path1 = File.Exists(computerPath) ? computerPath : PathUtils.FixPath(computerPath); path1 = CheckAndFixPath(path1); if (!string.IsNullOrEmpty(path1)) { path1 = PathUtils.FixPath(path1); using (var manager = OpenQcdmManager()) { var path2 = PathUtils.FixUnixPath(efsPath); FileUtils.PhoneUploadDirectory(manager, path1, path2, createItemFilesAsDefault, _logger); if (processNvItems) { NvItemUtils.PhoneUploadNvItems(manager, path1, _logger); } } } } } public void EfsCreateDirectory(string path, bool recursive) { using (var manager = OpenQcdmManager()) { FileUtils.PhoneCreateDirectory(manager, path, recursive, _logger); } } public void EfsDeleteDirectory(string path, bool recursive) { using (var manager = OpenQcdmManager()) { FileUtils.PhoneDeleteDirectory(manager, path, recursive, _logger); } } public void EfsListDirectory(string path, bool recursive) { using (var manager = OpenQcdmManager()) { _logger.LogInfo(string.Format(Strings.QcdmListOfDirectoryFormat, path)); FileUtils.PhoneListDirectory(manager, path, recursive, string.Empty, _logger); } } public void GetModemConfig(string path, string inputDirectory, string itemNames, int subscription, bool verbose) { var inDirectory = inputDirectory; if (!string.IsNullOrEmpty(inDirectory)) { inDirectory = CheckAndFixPath(inDirectory); } _logger.LogInfo(Strings.QcdmGeneratingModemConfig); if (string.IsNullOrEmpty(inputDirectory)) { using (var manager = OpenQcdmManager()) { using (var output = File.CreateText(path)) { var items = string.IsNullOrEmpty(itemNames) ? NvItemUtils.PhoneLoadItems(manager, subscription, _logger, verbose) : NvItemUtils.PhoneLoadItems(manager, subscription, _logger, verbose, new HashSet<string>(itemNames.Split(','))); ItemsJsonSerializer.SerializeItems(items, output); output.Flush(); output.Close(); } } } else { using (var output = File.CreateText(path)) { var items = string.IsNullOrEmpty(itemNames) ? NvItemUtils.LocalLoadItems(inDirectory, subscription, _logger, verbose) : NvItemUtils.LocalLoadItems(inDirectory, subscription, _logger, verbose, new HashSet<string>(itemNames.Split(','))); ItemsJsonSerializer.SerializeItems(items, output); output.Flush(); output.Close(); } } } public void SetModemConfig(string path, string outputDirectory, int subscription, bool verbose) { _logger.LogInfo(Strings.QcdmApplyingModemConfig); if (string.IsNullOrEmpty(outputDirectory)) { using (var manager = OpenQcdmManager()) { using (var input = new StreamReader(File.OpenRead(path), Encoding.UTF8, true)) { var configItems = NvItemUtils.GetConfigs(input); input.BaseStream.Seek(0, SeekOrigin.Begin); var items = NvItemUtils.PhoneLoadItems(manager, subscription, _logger, verbose, configItems); ItemsJsonSerializer.DeserializeItems(items, input); NvItemUtils.PhoneSaveItems(manager, subscription, items, _logger, verbose); } } } else { using (var input = new StreamReader(File.OpenRead(path), Encoding.UTF8, true)) { Directory.CreateDirectory(outputDirectory); var configItems = NvItemUtils.GetConfigs(input); input.BaseStream.Seek(0, SeekOrigin.Begin); var items = NvItemUtils.LocalLoadItems(outputDirectory, subscription, _logger, verbose, configItems); ItemsJsonSerializer.DeserializeItems(items, input); NvItemUtils.LocalSaveItems(outputDirectory, subscription, items, _logger, verbose); } } } public void EfsDeleteFile(string path) { using (var manager = OpenQcdmManager()) { FileUtils.PhoneDeleteFile(manager, path, _logger); } } public void EfsFixFileNames(string efsPath) { if (!string.IsNullOrEmpty(efsPath)) { using (var manager = OpenQcdmManager()) { var path = PathUtils.FixUnixPath(efsPath); FileUtils.PhoneFixFileNames(manager, path, _logger); } } } public void ExtractMbn(string inputMbnFilePath, string outputComputerDirectoryPath, bool noExtraData) { _logger.LogInfo(Strings.QcdmExtractingMbnFileFormat, inputMbnFilePath); MbnExtractor.Extract(inputMbnFilePath, outputComputerDirectoryPath, noExtraData, _logger); } private string CheckAndFixPath(string path) { if (File.Exists(path) && Path.GetExtension(path) == ".mbn") { var b = Directory.Exists(path); var tmpPath = Path.Combine(Path.GetTempPath(), "EfsTools", Path.GetRandomFileName()); Directory.CreateDirectory(tmpPath); ExtractMbn(path, tmpPath, true); return tmpPath; } return path; } public void StartWebDavServer(int port, LogLevel logLevel, bool readOnly) { using (var manager = OpenQcdmManager()) { EfsFileManager.Instance.UpdateEntries(manager, "/"); using (var httpListener = new HttpListener()) { var uri = $"http://127.0.0.1:{port}/"; httpListener.Prefixes.Add(uri); httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; httpListener.Start(); if (_logger != null && logLevel >= LogLevel.Info) { _logger.LogInfo(Strings.WebDavServerStartedFormat, uri); } var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; Console.CancelKeyPress += ((sender, args) => cancellationTokenSource.Cancel()); var requestHandlerFactory = new RequestHandlerFactory(); var webDavDispatcher = new WebDavDispatcher(new EfsStore(manager, readOnly, _logger, logLevel), requestHandlerFactory); //var homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); //var webDavDispatcher = new WebDavDispatcher(new DiskStore(homeFolder), requestHandlerFactory); while (!cancellationToken.IsCancellationRequested) { var contextTask = httpListener.GetContextAsync(); contextTask.Wait(cancellationToken); var httpListenerContext = contextTask.Result; if (httpListenerContext != null) { var httpContext = new HttpContext(httpListenerContext); var dispatchRequestTask = webDavDispatcher.DispatchRequestAsync(httpContext); dispatchRequestTask.Wait(cancellationToken); } } } manager.Close(); } } private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { throw new NotImplementedException(); } private QcdmManager OpenQcdmManager() { var manager = new QcdmManager(_config.Port, _config.Baudrate, 7000, _config.HdlcSendControlChar, _config.IgnoreUnsupportedCommands, _logger); if (_config.Port != manager.PortName) { _logger.LogInfo(Strings.QcdmUseComPortFormat, manager.PortName); } manager.Open(); manager.SendPassword(_config.Password); manager.SendSpc(_config.Spc); manager.DisableLogs(); manager.DisableMessages(); return manager; } } }
43.476718
270
0.524939
[ "MIT" ]
JohnBel/EfsTools
EfsTools/EfsTools.cs
19,610
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace RezRouting.Demos.MvcWalkthrough2.ViewEngines { // Adapted from https://github.com/danmalcolm/ControllerPathViewEngine public class ControllerPathResolver { private readonly ConcurrentDictionary<Type, string> paths = new ConcurrentDictionary<Type, string>(); private readonly ControllerPathSettings settings; public ControllerPathResolver(ControllerPathSettings settings) { this.settings = settings; } public string GetPath(Type controllerType) { return paths.GetOrAdd(controllerType, GetControllerPath); } private string GetControllerPath(Type controllerType) { string controllerName = GetControllerName(controllerType); var directories = GetDirectoriesBaseOnNamespace(controllerType).ToList(); bool excludeControllerName = settings.MergeNameIntoNamespace && controllerName.Equals(directories.LastOrDefault(), StringComparison.OrdinalIgnoreCase); if (!excludeControllerName) { directories.Add(controllerName); } return string.Join("/", directories); } private IEnumerable<string> GetDirectoriesBaseOnNamespace(Type controllerType) { var directories = controllerType.Namespace != null ? controllerType.Namespace.Split('.') : null; if (directories == null || directories.Length == 0) return Enumerable.Empty<string>(); // Get a directory for each level within namespace below last occurence of // a "Controllers" element. return directories .Reverse() .TakeWhile(x => x != "Controllers") .Reverse(); } private string GetControllerName(Type controllerType) { string name = controllerType.Name; if (name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) { return name.Substring(0, name.Length - "Controller".Length); } return name; } } }
34.727273
109
0.619983
[ "MIT" ]
danmalcolm/RezRouting.Net
src/RezRouting.Demos.MvcWalkthrough2/ViewEngines/ControllerPathResolver.cs
2,292
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // namespace Lomo.Commerce.Service.HighSecurity { using System; /// <summary> /// The Probe.aspx page. /// </summary> /// <remarks> /// Probe.aspx is used by MSN-based monitoring to determine whether the machine is current in service. If the file is not /// found, the machine is remove from service. Once the file is restored, the machine is returned to service. /// </remarks> public partial class Probe : System.Web.UI.Page { /// <summary> /// Initializes the page. /// </summary> /// <param name="sender"> /// The object that invoked this method. /// </param> /// <param name="e"> /// Event arguments sent to this method. /// </param> protected void Page_Init(object sender, EventArgs e) { // Set ViewStateUserKey to prevent one-click attacks. ViewStateUserKey = Guid.NewGuid().ToString(); } /// <summary> /// Loads the page. /// </summary> /// <param name="sender"> /// The object that invoked this method. /// </param> /// <param name="e"> /// Event arguments sent to this method. /// </param> protected void Page_Load(object sender, EventArgs e) { } } }
32.479167
125
0.549711
[ "MIT" ]
BOONRewardsInc/rewards
Commerce/ServiceHighSecurityEndpoints/Probe.aspx.cs
1,559
C#
using System.Threading.Tasks; namespace DefaultInterfaceMethods { public class RabbitMqMessageSender : IMessageSender { public void Send(string message) { } public Task SendAsync(string message) { // TODO: return Task.CompletedTask; } } }
17.263158
55
0.57622
[ "MIT" ]
FreezeSoul/Practical.NET
examples/CSharpNewFeatures/DefaultInterfaceMethods/RabbitMqMessageSender.cs
330
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; namespace Inlining { public static class NoThrowInline { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 275000000; #endif static void ThrowIfNull(string s) { if (s == null) ThrowArgumentNullException(); } static void ThrowArgumentNullException() { throw new ArgumentNullException(); } // // We expect ThrowArgumentNullException to not be inlined into Bench, the throw code is pretty // large and throws are extremly slow. However, we need to be careful not to degrade the // non-exception path performance by preserving registers across the call. For this the compiler // will have to understand that ThrowArgumentNullException never returns and omit the register // preservation code. // // For example, the Bench method below has 4 arguments (all passed in registers on x64) and fairly // typical argument validation code. If the compiler does not inline ThrowArgumentNullException // and does not make use of the "no return" information then all 4 register arguments will have // to be spilled and then reloaded. That would add 8 unnecessary memory accesses. // [MethodImpl(MethodImplOptions.NoInlining)] static int Bench(string a, string b, string c, string d) { ThrowIfNull(a); ThrowIfNull(b); ThrowIfNull(c); ThrowIfNull(d); return a.Length + b.Length + c.Length + d.Length; } public static int Main() { return (Bench("a", "bc", "def", "ghij") == 10) ? 100 : -1; } } }
30.844828
102
0.681386
[ "MIT" ]
333fred/runtime
src/tests/JIT/Performance/CodeQuality/Inlining/NoThrowInline.cs
1,789
C#
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework; namespace Pivotal.Data.GemFireXD.Tests { /// <summary> /// Simple runner for junit test debugging etc. This just invokes the methods /// that have been hard-coded below without any regard to attributes etc. Use /// only for debugging tests in Visual Studio, for example. /// </summary> class Program { static void Main(string[] args) { Console.WriteLine("Current directory: " + Environment.CurrentDirectory); object testObject; int testNumber = 0; List<MethodInfo> fixtureSetup = new List<MethodInfo>(); List<MethodInfo> fixtureTearDown = new List<MethodInfo>(); List<MethodInfo> setup = new List<MethodInfo>(); List<MethodInfo> tearDown = new List<MethodInfo>(); Assembly assembly = Assembly.GetAssembly(typeof(BasicTests)); List<MethodInfo> testMethods = new List<MethodInfo>(); foreach (Type testType in assembly.GetTypes()) { object[] attrs = testType.GetCustomAttributes( typeof(TestFixtureAttribute), false); if (attrs != null && attrs.Length > 0) { testMethods.Clear(); fixtureSetup.Clear(); fixtureTearDown.Clear(); setup.Clear(); tearDown.Clear(); foreach (MethodInfo method in testType.GetMethods()) { attrs = method.GetCustomAttributes( typeof(TestFixtureSetUpAttribute), true); if (attrs != null && attrs.Length > 0) { fixtureSetup.Add(method); } attrs = method.GetCustomAttributes( typeof(TestFixtureTearDownAttribute), true); if (attrs != null && attrs.Length > 0) { fixtureTearDown.Add(method); } attrs = method.GetCustomAttributes( typeof(SetUpAttribute), true); if (attrs != null && attrs.Length > 0) { setup.Add(method); } attrs = method.GetCustomAttributes( typeof(TearDownAttribute), true); if (attrs != null && attrs.Length > 0) { tearDown.Add(method); } attrs = method.GetCustomAttributes(typeof(TestAttribute), false); if (attrs != null && attrs.Length > 0) { testMethods.Add(method); } } if (testMethods.Count > 0) { testObject = Activator.CreateInstance(testType); foreach (MethodInfo method in fixtureSetup) { try { Console.WriteLine("TestFixtureSetup: " + method.DeclaringType + '.' + method.Name + " for class: " + method.ReflectedType); method.Invoke(testObject, null); } catch (Exception ex) { Console.WriteLine("TestFixtureSetup: unexpected exception: " + ex); throw; } } try { foreach (MethodInfo testMethod in testMethods) { foreach (MethodInfo method in setup) { try { Console.WriteLine("TestSetup: " + method.DeclaringType + '.' + method.Name + " for class: " + method.ReflectedType); method.Invoke(testObject, null); } catch (Exception ex) { Console.WriteLine("TestSetup: unexpected exception: " + ex); throw; } } try { Console.WriteLine("========== Running test [ " + testType + '.' + testMethod.Name + "(" + (++testNumber) + ")] ============"); testMethod.Invoke(testObject, null); } catch (Exception ex) { Console.WriteLine("Test: unexpected exception: " + ex); throw; } finally { foreach (MethodInfo method in tearDown) { try { Console.WriteLine("TearDown: " + method.DeclaringType + '.' + method.Name + " for class: " + method.ReflectedType); method.Invoke(testObject, null); } catch (Exception ex) { Console.WriteLine("TearDown: unexpected exception: " + ex); } } } } } finally { foreach (MethodInfo method in fixtureTearDown) { try { Console.WriteLine("TestFixtureTearDown: " + method.DeclaringType + '.' + method.Name + " for class: " + method.ReflectedType); method.Invoke(testObject, null); } catch (Exception ex) { Console.WriteLine("TestFixtureTearDown: " + "unexpected exception: " + ex); } } } } } } Console.WriteLine(); Console.WriteLine("----------- Successfully ran " + testNumber + " tests."); } /* static void Main(string[] args) { int result; using (DbConnection conn = new GFXDClientConnection( "server=localhost:1527")) { conn.Open(); DbCommand cmd = conn.CreateCommand(); // employee table and data cmd.CommandText = "create table employee (" + " id int PRIMARY KEY," + " first_name varchar (100) NOT NULL," + " middle_name varchar (100)," + " last_name varchar (100)," + " email varchar(200))"; result = cmd.ExecuteNonQuery(); cmd.CommandText = "insert into employee values " + "(1, 'Vijay', 'S', 'Mehra', '[email protected]')," + "(2, 'Shirish', NULL, 'Kumar', '[email protected]')," + "(3, 'Venkatesh', 'T', 'Ramachandran', '[email protected]')"; result = cmd.ExecuteNonQuery(); Console.WriteLine("Inserted " + result + " records in employee table"); Console.WriteLine(); // query data back displaying the results cmd.CommandText = "select * from employee"; using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(string.Format("Employee details -- Name:" + " {0} {1} {2}, ID: {3}, Email: {4}", reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(0), reader.GetString(4))); } } conn.Close(); Console.WriteLine(); Console.WriteLine("Done."); } } */ } }
38.050505
81
0.526414
[ "Apache-2.0" ]
SnappyDataInc/snappy-store
gemfirexd/client/test/csharp/ado-tests-runner/Program.cs
7,534
C#
using FakeItEasy; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.ClassBased; using FluentNHibernate.Visitors; using NUnit.Framework; namespace FluentNHibernate.Testing.MappingModel { [TestFixture] public class HibernateMappingTester { [Test] public void CanAddClassMappings() { var hibMap = new HibernateMapping(); var classMap1 = new ClassMapping(); var classMap2 = new ClassMapping(); hibMap.AddClass(classMap1); hibMap.AddClass(classMap2); hibMap.Classes.ShouldContain(classMap1); hibMap.Classes.ShouldContain(classMap2); } [Test] public void ShouldPassClassmappingsToTheVisitor() { // FakeItEasy calls ToString methods, which ends up in NullPointer // if Type attribute is not the AttributeStore var attributeStore = new AttributeStore(); attributeStore.Set("Type", 0, typeof(object)); var hibMap = new HibernateMapping(); var classMap = new ClassMapping(attributeStore); hibMap.AddClass(classMap); var visitor = A.Fake<IMappingModelVisitor>(); hibMap.AcceptVisitor(visitor); A.CallTo(() => visitor.Visit(classMap)).MustHaveHappened(); } } }
31.288889
79
0.610795
[ "BSD-3-Clause" ]
BrunoJuchli/fluent-nhibernate
src/FluentNHibernate.Testing/MappingModel/HibernateMappingTester.cs
1,410
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices { using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// Used to specify the authentication type used by a device. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum AuthenticationType { /// <summary> /// Shared Access Key /// </summary> [EnumMember(Value = "sas")] Sas = 0, /// <summary> /// Self-signed certificate /// </summary> [EnumMember(Value = "selfSigned")] SelfSigned = 1, /// <summary> /// Certificate Authority /// </summary> [EnumMember(Value = "certificateAuthority")] CertificateAuthority = 2, /// <summary> /// No Authentication Token at this scope /// </summary> [EnumMember(Value = "none")] None = 3 } }
28.567568
101
0.600757
[ "MIT" ]
Azure/azure-iot-sdk-csharp
shared/src/AuthenticationType.cs
1,057
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("05.CharacterStats")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.CharacterStats")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("042ffa69-7fbe-4a39-92b6-489fb833f454")] // 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.891892
84
0.748217
[ "MIT" ]
vpaleshnikov/SoftUni-TechModule
ProgrammingFundamentals/01.C#IntroAndBasicSyntaxExercises/05.CharacterStats/Properties/AssemblyInfo.cs
1,405
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace BindableBase { // https://github.com/PrismLibrary/Prism/blob/master/Source/Prism/Mvvm/BindableBase.cs /// <summary> /// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models. /// </summary> public abstract class BindableBase : INotifyPropertyChanged { /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers that /// support CallerMemberName.</param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; RaisePropertyChanged(propertyName); return true; } /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers that /// support CallerMemberName.</param> /// <param name="onChanged">Action that is called after the property value has been changed.</param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; onChanged?.Invoke(); RaisePropertyChanged(propertyName); return true; } /// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="propertyName">Name of the property used to notify listeners. This /// value is optional and can be provided automatically when invoked from compilers /// that support <see cref="CallerMemberNameAttribute"/>.</param> protected void RaisePropertyChanged([CallerMemberName]string propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Raises this object's PropertyChanged event. /// </summary> /// <param name="args">The PropertyChangedEventArgs</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { PropertyChanged?.Invoke(this, args); } } }
45
134
0.646013
[ "MIT" ]
devwock/uwp-samples
Samples/BindableBase/BindableBase.cs
3,827
C#
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; namespace Cortside.RestSharpClient { internal class NullDistributedCache : IDistributedCache { public byte[] Get(string key) { throw new System.NotSupportedException(); } public Task<byte[]> GetAsync(string key, CancellationToken token = default) { return Task.FromResult<byte[]>(null); } public void Refresh(string key) { throw new System.NotSupportedException(); } public Task RefreshAsync(string key, CancellationToken token = default) { return Task.CompletedTask; } public void Remove(string key) { throw new System.NotSupportedException(); } public Task RemoveAsync(string key, CancellationToken token = default) { return Task.CompletedTask; } public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { throw new System.NotSupportedException(); } public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) { return Task.CompletedTask; } } }
31.8
129
0.647799
[ "MIT" ]
cortside/RestSharpClient
src/Cortside.RestSharpClient/NullDistributedCache.cs
1,272
C#
using System.Text.Json.Serialization; using Google.Cloud.Firestore; namespace Warehouse.Shared.Models { [FirestoreData] public class InputModel { [FirestoreDocumentId] [JsonPropertyName("ID")] public string Id { get; set; } [FirestoreProperty] public string InputTypeId { get; set; } [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public string UnitMeasure { get; set; } } }
22.409091
47
0.626775
[ "Apache-2.0" ]
kiulcode/BlazorFirebase
Warehouse/Shared/Models/InputModel.cs
495
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Waf.Applications; using System.Waf.UnitTesting; using System.Windows.Input; namespace Test.Waf.UnitTesting { [TestClass] public class CanExecuteChangedEventTest { [TestMethod] public void CommandCanExecuteChangedTest1() { var command = new DelegateCommand(() => { }); AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged()); AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 1, ExpectedChangedCountMode.Exact); AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 0, ExpectedChangedCountMode.AtLeast); AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 2, ExpectedChangedCountMode.AtMost); AssertHelper.ExpectedException<ArgumentNullException>( () => AssertHelper.CanExecuteChangedEvent(null, () => command.RaiseCanExecuteChanged())); AssertHelper.ExpectedException<ArgumentNullException>( () => AssertHelper.CanExecuteChangedEvent(command, null)); AssertHelper.ExpectedException<ArgumentOutOfRangeException>( () => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), -1, ExpectedChangedCountMode.Exact)); } [TestMethod] public void CommandCanExecuteChangedTest2() { var command = new DelegateCommand(() => { }); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => { })); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => { command.RaiseCanExecuteChanged(); command.RaiseCanExecuteChanged(); })); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 0, ExpectedChangedCountMode.Exact)); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 2, ExpectedChangedCountMode.Exact)); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 2, ExpectedChangedCountMode.AtLeast)); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged(), 0, ExpectedChangedCountMode.AtMost)); } [TestMethod] public void WrongEventSenderTest() { var command = new WrongCommand(); AssertHelper.ExpectedException<AssertException>(() => AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged())); } private class WrongCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { throw new NotImplementedException(); } public void Execute(object parameter) { throw new NotImplementedException(); } public void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(null, EventArgs.Empty); } } } }
40.617021
145
0.617863
[ "MIT" ]
pskpatil/waf
src/System.Waf/System.Waf/System.Waf.Core.Test/UnitTesting/CanExecuteChangedEventTest.cs
3,820
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace Medikit.EID.Tlv { public enum SpecialOrganisations { SHAPE = 1, NATO = 2, FORMER_BLUE_CARD_HOLDER = 4, RESEARCHER = 5 } }
26.076923
107
0.660767
[ "Apache-2.0" ]
ddonabedian/medikit
src/EID/Medikit.EID/Tlv/SpecialOrganisations.cs
341
C#
// https://docs.microsoft.com/en-us/visualstudio/modeling/t4-include-directive?view=vs-2017 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.Bot.Builder.Solutions.Responses; namespace SkillSample.Responses.Sample { /// <summary> /// Contains bot responses. /// </summary> public class SampleResponses : IResponseIdCollection { // Generated accessors public const string NamePrompt = "NamePrompt"; public const string HaveNameMessage = "HaveNameMessage"; } }
31.722222
92
0.711033
[ "MIT" ]
3ve4me/botframework-solutions
templates/Skill-Template/csharp/Sample/SkillSample/Responses/Sample/SampleResponses.cs
573
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Diagnostics.Runtime.Utilities; using System; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.Diagnostics.Runtime.DacInterface { /// <summary> /// This is an undocumented, untested, and unsupported interface. Do not use. /// </summary> public sealed unsafe class SOSDac : CallableCOMWrapper { internal static Guid IID_ISOSDac = new Guid("436f00f2-b42a-4b9f-870c-e73db66ae930"); private ISOSDacVTable* VTable => (ISOSDacVTable*)_vtable; private static RejitData[] s_emptyRejit; private readonly DacLibrary _library; public SOSDac(DacLibrary library, IntPtr ptr) : base(library.OwningLibrary, ref IID_ISOSDac, ptr) { _library = library; } public SOSDac(CallableCOMWrapper toClone) : base(toClone) { } private const int CharBufferSize = 256; private byte[] _buffer = new byte[CharBufferSize]; private DacGetIntPtr _getHandleEnum; private DacGetIntPtrWithArg _getStackRefEnum; private DacGetThreadData _getThreadData; private DacGetHeapDetailsWithArg _getGCHeapDetails; private DacGetHeapDetails _getGCHeapStaticData; private DacGetUlongArray _getGCHeapList; private DacGetUlongArray _getAppDomainList; private DacGetUlongArrayWithArg _getAssemblyList; private DacGetUlongArrayWithArg _getModuleList; private DacGetAssemblyData _getAssemblyData; private DacGetADStoreData _getAppDomainStoreData; private DacGetMTData _getMethodTableData; private DacGetUlongWithArg _getMTForEEClass; private DacGetGCInfoData _getGCHeapData; private DacGetCommonMethodTables _getCommonMethodTables; private DacGetCharArrayWithArg _getMethodTableName; private DacGetByteArrayWithArg _getJitHelperFunctionName; private DacGetCharArrayWithArg _getPEFileName; private DacGetCharArrayWithArg _getAppDomainName; private DacGetCharArrayWithArg _getAssemblyName; private DacGetCharArrayWithArg _getAppBase; private DacGetCharArrayWithArg _getConfigFile; private DacGetModuleData _getModuleData; private DacGetSegmentData _getSegmentData; private DacGetAppDomainData _getAppDomainData; private DacGetJitManagers _getJitManagers; private DacTraverseLoaderHeap _traverseLoaderHeap; private DacTraverseStubHeap _traverseStubHeap; private DacTraverseModuleMap _traverseModuleMap; private DacGetFieldInfo _getFieldInfo; private DacGetFieldData _getFieldData; private DacGetObjectData _getObjectData; private DacGetCCWData _getCCWData; private DacGetRCWData _getRCWData; private DacGetCharArrayWithArg _getFrameName; private DacGetUlongWithArg _getMethodDescPtrFromFrame; private DacGetUlongWithArg _getMethodDescPtrFromIP; private DacGetCodeHeaderData _getCodeHeaderData; private DacGetSyncBlockData _getSyncBlock; private DacGetThreadPoolData _getThreadPoolData; private DacGetWorkRequestData _getWorkRequestData; private DacGetDomainLocalModuleDataFromAppDomain _getDomainLocalModuleDataFromAppDomain; private DacGetLocalModuleData _getDomainLocalModuleDataFromModule; private DacGetCodeHeaps _getCodeHeaps; private DacGetCOMPointers _getCCWInterfaces; private DacGetCOMPointers _getRCWInterfaces; private DacGetUlongWithArgs _getILForModule; private DacGetThreadLocalModuleData _getThreadLocalModuleData; private DacGetUlongWithArgs _getMethodTableSlot; private DacGetCharArrayWithArg _getMethodDescName; private DacGetThreadFromThinLock _getThreadFromThinlockId; private DacGetUInt _getTlsIndex; private DacGetThreadStoreData _getThreadStoreData; private GetMethodDescDataDelegate _getMethodDescData; private GetMetaDataImportDelegate _getMetaData; private GetMethodDescFromTokenDelegate _getMethodDescFromToken; public RejitData[] GetRejitData(ulong md, ulong ip = 0) { InitDelegate(ref _getMethodDescData, VTable->GetMethodDescData); int hr = _getMethodDescData(Self, md, ip, out MethodDescData data, 0, null, out int needed); if (SUCCEEDED(hr) && needed > 1) { RejitData[] result = new RejitData[needed]; hr = _getMethodDescData(Self, md, ip, out data, result.Length, result, out needed); if (SUCCEEDED(hr)) return result; } if (s_emptyRejit == null) s_emptyRejit = new RejitData[0]; return s_emptyRejit; } public bool GetMethodDescData(ulong md, ulong ip, out MethodDescData data) { InitDelegate(ref _getMethodDescData, VTable->GetMethodDescData); int hr = _getMethodDescData(Self, md, ip, out data, 0, null, out int needed); return SUCCEEDED(hr); } public bool GetThreadStoreData(out ThreadStoreData data) { InitDelegate(ref _getThreadStoreData, VTable->GetThreadStoreData); return _getThreadStoreData(Self, out data) == S_OK; } public uint GetTlsIndex() { InitDelegate(ref _getTlsIndex, VTable->GetTLSIndex); if (_getTlsIndex(Self, out uint index) == S_OK) return index; return uint.MaxValue; } public ulong GetThreadFromThinlockId(uint id) { InitDelegate(ref _getThreadFromThinlockId, VTable->GetThreadFromThinlockID); if (_getThreadFromThinlockId(Self, id, out ulong thread) == S_OK) return thread; return 0; } public string GetMethodDescName(ulong md) { if (md == 0) return null; InitDelegate(ref _getMethodDescName, VTable->GetMethodDescName); if (_getMethodDescName(Self, md, 0, null, out int needed) < S_OK) return null; byte[] buffer = AcquireBuffer(needed * 2); if (_getMethodDescName(Self, md, needed, buffer, out int actuallyNeeded) < S_OK) return null; // Patch for a bug on sos side : // Sometimes, when the target method has parameters with generic types // the first call to GetMethodDescName sets an incorrect value into pNeeded. // In those cases, a second call directly after the first returns the correct value. if (needed != actuallyNeeded) { ReleaseBuffer(buffer); buffer = AcquireBuffer(actuallyNeeded * 2); if (_getMethodDescName(Self, md, actuallyNeeded, buffer, out actuallyNeeded) < S_OK) return null; } ReleaseBuffer(buffer); return string.Intern(Encoding.Unicode.GetString(buffer, 0, (actuallyNeeded - 1) * 2)); } public ulong GetMethodTableSlot(ulong mt, int slot) { if (mt == 0) return 0; InitDelegate(ref _getMethodTableSlot, VTable->GetMethodTableSlot); if (_getMethodTableSlot(Self, mt, (uint)slot, out ulong ip) == S_OK) return ip; return 0; } public bool GetThreadLocalModuleData(ulong thread, uint index, out ThreadLocalModuleData data) { InitDelegate(ref _getThreadLocalModuleData, VTable->GetThreadLocalModuleData); return _getThreadLocalModuleData(Self, thread, index, out data) == S_OK; } public ulong GetILForModule(ulong moduleAddr, uint rva) { InitDelegate(ref _getILForModule, VTable->GetILForModule); int hr = _getILForModule(Self, moduleAddr, rva, out ulong result); return hr == S_OK ? result : 0; } public COMInterfacePointerData[] GetCCWInterfaces(ulong ccw, int count) { InitDelegate(ref _getCCWInterfaces, VTable->GetCCWInterfaces); COMInterfacePointerData[] data = new COMInterfacePointerData[count]; if (_getCCWInterfaces(Self, ccw, count, data, out int pNeeded) >= 0) return data; return null; } public COMInterfacePointerData[] GetRCWInterfaces(ulong ccw, int count) { InitDelegate(ref _getRCWInterfaces, VTable->GetRCWInterfaces); COMInterfacePointerData[] data = new COMInterfacePointerData[count]; if (_getRCWInterfaces(Self, ccw, count, data, out int pNeeded) >= 0) return data; return null; } public bool GetDomainLocalModuleDataFromModule(ulong module, out DomainLocalModuleData data) { InitDelegate(ref _getDomainLocalModuleDataFromModule, VTable->GetDomainLocalModuleDataFromModule); int res = _getDomainLocalModuleDataFromModule(Self, module, out data); return SUCCEEDED(res); } public bool GetDomainLocalModuleDataFromAppDomain(ulong appDomain, int id, out DomainLocalModuleData data) { InitDelegate(ref _getDomainLocalModuleDataFromAppDomain, VTable->GetDomainLocalModuleDataFromAppDomain); int res = _getDomainLocalModuleDataFromAppDomain(Self, appDomain, id, out data); return SUCCEEDED(res); } public bool GetWorkRequestData(ulong request, out WorkRequestData data) { InitDelegate(ref _getWorkRequestData, VTable->GetWorkRequestData); int hr = _getWorkRequestData(Self, request, out data); return SUCCEEDED(hr); } public bool GetThreadPoolData(out ThreadPoolData data) { InitDelegate(ref _getThreadPoolData, VTable->GetThreadpoolData); int hr = _getThreadPoolData(Self, out data); return SUCCEEDED(hr); } public bool GetSyncBlockData(int index, out SyncBlockData data) { InitDelegate(ref _getSyncBlock, VTable->GetSyncBlockData); int hr = _getSyncBlock(Self, index, out data); return SUCCEEDED(hr); } public string GetAppBase(ulong domain) { InitDelegate(ref _getAppBase, VTable->GetApplicationBase); return GetString(_getAppBase, domain); } public string GetConfigFile(ulong domain) { InitDelegate(ref _getConfigFile, VTable->GetAppDomainConfigFile); return GetString(_getConfigFile, domain); } public bool GetCodeHeaderData(ulong ip, out CodeHeaderData codeHeaderData) { if (ip == 0) { codeHeaderData = new CodeHeaderData(); return false; } InitDelegate(ref _getCodeHeaderData, VTable->GetCodeHeaderData); int hr = _getCodeHeaderData(Self, ip, out codeHeaderData); return hr == S_OK; } public ulong GetMethodDescPtrFromFrame(ulong frame) { InitDelegate(ref _getMethodDescPtrFromFrame, VTable->GetMethodDescPtrFromFrame); if (_getMethodDescPtrFromFrame(Self, frame, out ulong data) == S_OK) return data; return 0; } public ulong GetMethodDescPtrFromIP(ulong frame) { InitDelegate(ref _getMethodDescPtrFromIP, VTable->GetMethodDescPtrFromIP); if (_getMethodDescPtrFromIP(Self, frame, out ulong data) == S_OK) return data; return 0; } public string GetFrameName(ulong vtable) { InitDelegate(ref _getFrameName, VTable->GetFrameName); return GetString(_getFrameName, vtable, false) ?? "Unknown Frame"; } public bool GetFieldInfo(ulong mt, out V4FieldInfo data) { InitDelegate(ref _getFieldInfo, VTable->GetMethodTableFieldData); int hr = _getFieldInfo(Self, mt, out data); return SUCCEEDED(hr); } public bool GetFieldData(ulong fieldDesc, out FieldData data) { InitDelegate(ref _getFieldData, VTable->GetFieldDescData); int hr = _getFieldData(Self, fieldDesc, out data); return SUCCEEDED(hr); } public bool GetObjectData(ulong obj, out V45ObjectData data) { InitDelegate(ref _getObjectData, VTable->GetObjectData); int hr = _getObjectData(Self, obj, out data); return SUCCEEDED(hr); } public bool GetCCWData(ulong ccw, out CCWData data) { InitDelegate(ref _getCCWData, VTable->GetCCWData); int hr = _getCCWData(Self, ccw, out data); return SUCCEEDED(hr); } public bool GetRCWData(ulong rcw, out RCWData data) { InitDelegate(ref _getRCWData, VTable->GetRCWData); int hr = _getRCWData(Self, rcw, out data); return SUCCEEDED(hr); } public MetaDataImport GetMetadataImport(ulong module) { if (module == 0) return null; InitDelegate(ref _getMetaData, VTable->GetMetaDataImport); if (_getMetaData(Self, module, out IntPtr iunk) != S_OK) return null; try { return new MetaDataImport(_library, iunk); } catch (InvalidCastException) { // QueryInterface on MetaDataImport seems to fail when we don't have full // metadata available. return null; } } public bool GetCommonMethodTables(out CommonMethodTables commonMTs) { InitDelegate(ref _getCommonMethodTables, VTable->GetUsefulGlobals); return _getCommonMethodTables(Self, out commonMTs) == S_OK; } public ulong[] GetAssemblyList(ulong appDomain) { return GetAssemblyList(appDomain, 0); } public ulong[] GetAssemblyList(ulong appDomain, int count) { return GetModuleOrAssembly(appDomain, count, ref _getAssemblyList, VTable->GetAssemblyList); } public bool GetAssemblyData(ulong domain, ulong assembly, out AssemblyData data) { InitDelegate(ref _getAssemblyData, VTable->GetAssemblyData); // The dac seems to have an issue where the assembly data can be filled in for a minidump. // If the data is partially filled in, we'll use it. int hr = _getAssemblyData(Self, domain, assembly, out data); return SUCCEEDED(hr) || data.Address == assembly; } public bool GetAppDomainData(ulong addr, out AppDomainData data) { InitDelegate(ref _getAppDomainData, VTable->GetAppDomainData); // We can face an exception while walking domain data if we catch the process // at a bad state. As a workaround we will return partial data if data.Address // and data.StubHeap are set. int hr = _getAppDomainData(Self, addr, out data); return SUCCEEDED(hr) || data.Address == addr && data.StubHeap != 0; } public string GetAppDomainName(ulong appDomain) { InitDelegate(ref _getAppDomainName, VTable->GetAppDomainName); return GetString(_getAppDomainName, appDomain); } public string GetAssemblyName(ulong assembly) { InitDelegate(ref _getAssemblyName, VTable->GetAssemblyName); return GetString(_getAssemblyName, assembly); } public bool GetAppDomainStoreData(out AppDomainStoreData data) { InitDelegate(ref _getAppDomainStoreData, VTable->GetAppDomainStoreData); int hr = _getAppDomainStoreData(Self, out data); return SUCCEEDED(hr); } public bool GetMethodTableData(ulong addr, out MethodTableData data) { InitDelegate(ref _getMethodTableData, VTable->GetMethodTableData); int hr = _getMethodTableData(Self, addr, out data); return SUCCEEDED(hr); } public string GetMethodTableName(ulong mt) { InitDelegate(ref _getMethodTableName, VTable->GetMethodTableName); return GetString(_getMethodTableName, mt); } public string GetJitHelperFunctionName(ulong addr) { InitDelegate(ref _getJitHelperFunctionName, VTable->GetJitHelperFunctionName); return GetAsciiString(_getJitHelperFunctionName, addr); } public string GetPEFileName(ulong pefile) { InitDelegate(ref _getPEFileName, VTable->GetPEFileName); return GetString(_getPEFileName, pefile); } private string GetString(DacGetCharArrayWithArg func, ulong addr, bool skipNull = true) { int hr = func(Self, addr, 0, null, out int needed); if (hr != S_OK) return null; if (needed == 0) return ""; byte[] buffer = AcquireBuffer(needed * 2); hr = func(Self, addr, needed, buffer, out needed); if (hr != S_OK) { ReleaseBuffer(buffer); return null; } if (skipNull) needed--; string result = Encoding.Unicode.GetString(buffer, 0, needed * 2); ReleaseBuffer(buffer); return result; } private string GetAsciiString(DacGetByteArrayWithArg func, ulong addr) { int hr = func(Self, addr, 0, null, out int needed); if (hr != S_OK) return null; if (needed == 0) return ""; byte[] buffer = AcquireBuffer(needed); hr = func(Self, addr, needed, buffer, out needed); if (hr != S_OK) { ReleaseBuffer(buffer); return null; } int len = Array.IndexOf(buffer, (byte)0); if (len >= 0) needed = len; string result = Encoding.ASCII.GetString(buffer, 0, needed); ReleaseBuffer(buffer); return result; } private byte[] AcquireBuffer(int size) { if (_buffer == null) _buffer = new byte[CharBufferSize]; if (size > _buffer.Length) return new byte[size]; byte[] result = _buffer; _buffer = null; return result; } private void ReleaseBuffer(byte[] buffer) { if (buffer.Length == CharBufferSize) _buffer = buffer; } public ulong GetMethodTableByEEClass(ulong eeclass) { InitDelegate(ref _getMTForEEClass, VTable->GetMethodTableForEEClass); if (_getMTForEEClass(Self, eeclass, out ulong data) == S_OK) return data; return 0; } public bool GetModuleData(ulong module, out ModuleData data) { InitDelegate(ref _getModuleData, VTable->GetModuleData); int hr = _getModuleData(Self, module, out data); return SUCCEEDED(hr); } public ulong[] GetModuleList(ulong assembly) { return GetModuleList(assembly, 0); } public ulong[] GetModuleList(ulong assembly, int count) { return GetModuleOrAssembly(assembly, count, ref _getModuleList, VTable->GetAssemblyModuleList); } private ulong[] GetModuleOrAssembly(ulong address, int count, ref DacGetUlongArrayWithArg func, IntPtr vtableEntry) { InitDelegate(ref func, vtableEntry); int needed; if (count <= 0) { if (func(Self, address, 0, null, out needed) < 0) return new ulong[0]; count = needed; } // We ignore the return value here since the list may be partially filled ulong[] modules = new ulong[count]; func(Self, address, modules.Length, modules, out needed); return modules; } public ulong[] GetAppDomainList(int count = 0) { InitDelegate(ref _getAppDomainList, VTable->GetAppDomainList); if (count <= 0) { if (!GetAppDomainStoreData(out AppDomainStoreData addata)) return new ulong[0]; count = addata.AppDomainCount; } ulong[] data = new ulong[count]; int hr = _getAppDomainList(Self, data.Length, data, out int needed); return hr == S_OK ? data : new ulong[0]; } public bool GetThreadData(ulong address, out ThreadData data) { if (address == 0) { data = new ThreadData(); return false; } InitDelegate(ref _getThreadData, VTable->GetThreadData); int hr = _getThreadData(Self, address, out data); if (IntPtr.Size == 4) data = new ThreadData(ref data); return SUCCEEDED(hr); } public bool GetGcHeapData(out GCInfo data) { InitDelegate(ref _getGCHeapData, VTable->GetGCHeapData); int hr = _getGCHeapData(Self, out data); return SUCCEEDED(hr); } public bool GetSegmentData(ulong addr, out SegmentData data) { InitDelegate(ref _getSegmentData, VTable->GetHeapSegmentData); int hr = _getSegmentData(Self, addr, out data); if (hr == 0 && IntPtr.Size == 4) data = new SegmentData(ref data); return SUCCEEDED(hr); } public ulong[] GetHeapList(int heapCount) { InitDelegate(ref _getGCHeapList, VTable->GetGCHeapList); ulong[] refs = new ulong[heapCount]; int hr = _getGCHeapList(Self, heapCount, refs, out int needed); return hr == S_OK ? refs : null; } public bool GetServerHeapDetails(ulong addr, out HeapDetails data) { InitDelegate(ref _getGCHeapDetails, VTable->GetGCHeapDetails); int hr = _getGCHeapDetails(Self, addr, out data); if (IntPtr.Size == 4) data = new HeapDetails(ref data); return SUCCEEDED(hr); } public bool GetWksHeapDetails(out HeapDetails data) { InitDelegate(ref _getGCHeapStaticData, VTable->GetGCHeapStaticData); int hr = _getGCHeapStaticData(Self, out data); if (IntPtr.Size == 4) data = new HeapDetails(ref data); return SUCCEEDED(hr); } public JitManagerInfo[] GetJitManagers() { InitDelegate(ref _getJitManagers, VTable->GetJitManagerList); int hr = _getJitManagers(Self, 0, null, out int needed); if (hr != S_OK || needed == 0) return new JitManagerInfo[0]; JitManagerInfo[] result = new JitManagerInfo[needed]; hr = _getJitManagers(Self, result.Length, result, out needed); return hr == S_OK ? result : new JitManagerInfo[0]; } public JitCodeHeapInfo[] GetCodeHeapList(ulong jitManager) { InitDelegate(ref _getCodeHeaps, VTable->GetCodeHeapList); int hr = _getCodeHeaps(Self, jitManager, 0, null, out int needed); if (hr != S_OK || needed == 0) return new JitCodeHeapInfo[0]; JitCodeHeapInfo[] result = new JitCodeHeapInfo[needed]; hr = _getCodeHeaps(Self, jitManager, result.Length, result, out needed); return hr == S_OK ? result : new JitCodeHeapInfo[0]; } public enum ModuleMapTraverseKind { TypeDefToMethodTable, TypeRefToMethodTable } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void ModuleMapTraverse(uint index, ulong methodTable, IntPtr token); public bool TraverseModuleMap(ModuleMapTraverseKind mt, ulong module, ModuleMapTraverse traverse) { InitDelegate(ref _traverseModuleMap, VTable->TraverseModuleMap); int hr = _traverseModuleMap(Self, (int)mt, module, Marshal.GetFunctionPointerForDelegate(traverse), IntPtr.Zero); GC.KeepAlive(traverse); return hr == S_OK; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void LoaderHeapTraverse(ulong address, IntPtr size, int isCurrent); public bool TraverseLoaderHeap(ulong heap, LoaderHeapTraverse callback) { InitDelegate(ref _traverseLoaderHeap, VTable->TraverseLoaderHeap); int hr = _traverseLoaderHeap(Self, heap, Marshal.GetFunctionPointerForDelegate(callback)); GC.KeepAlive(callback); return hr == S_OK; } public bool TraverseStubHeap(ulong heap, int type, LoaderHeapTraverse callback) { InitDelegate(ref _traverseStubHeap, VTable->TraverseVirtCallStubHeap); int hr = _traverseStubHeap(Self, heap, type, Marshal.GetFunctionPointerForDelegate(callback)); GC.KeepAlive(callback); return hr == S_OK; } public SOSHandleEnum EnumerateHandles() { InitDelegate(ref _getHandleEnum, VTable->GetHandleEnum); int hr = _getHandleEnum(Self, out IntPtr ptrEnum); return hr == S_OK ? new SOSHandleEnum(_library, ptrEnum) : null; } public SOSStackRefEnum EnumerateStackRefs(uint osThreadId) { InitDelegate(ref _getStackRefEnum, VTable->GetStackReferences); int hr = _getStackRefEnum(Self, osThreadId, out IntPtr ptrEnum); return hr == S_OK ? new SOSStackRefEnum(_library, ptrEnum) : null; } public ulong GetMethodDescFromToken(ulong module, uint token) { InitDelegate(ref _getMethodDescFromToken, VTable->GetMethodDescFromToken); int hr = _getMethodDescFromToken(Self, module, token, out ulong md); return hr == S_OK ? md : 0; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetMethodDescFromTokenDelegate(IntPtr self, ulong module, uint token, out ulong methodDesc); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetMethodDescDataDelegate(IntPtr self, ulong md, ulong ip, out MethodDescData data, int count, [Out] RejitData[] rejitData, out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetIntPtr(IntPtr self, out IntPtr data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetUlongWithArg(IntPtr self, ulong arg, out ulong data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetUlongWithArgs(IntPtr self, ulong arg, uint id, out ulong data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetUInt(IntPtr self, out uint data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetIntPtrWithArg(IntPtr self, uint addr, out IntPtr data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetThreadData(IntPtr self, ulong addr, [Out] out ThreadData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetHeapDetailsWithArg(IntPtr self, ulong addr, out HeapDetails data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetHeapDetails(IntPtr self, out HeapDetails data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetUlongArray(IntPtr self, int count, [Out] ulong[] values, out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetUlongArrayWithArg(IntPtr self, ulong arg, int count, [Out] ulong[] values, out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCharArrayWithArg(IntPtr self, ulong arg, int count, [Out] byte[] values, [Out] out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetByteArrayWithArg(IntPtr self, ulong arg, int count, [Out] byte[] values, [Out] out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetAssemblyData(IntPtr self, ulong in1, ulong in2, out AssemblyData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetADStoreData(IntPtr self, out AppDomainStoreData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetGCInfoData(IntPtr self, out GCInfo data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCommonMethodTables(IntPtr self, out CommonMethodTables data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetThreadPoolData(IntPtr self, out ThreadPoolData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetThreadStoreData(IntPtr self, out ThreadStoreData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetMTData(IntPtr self, ulong addr, out MethodTableData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetModuleData(IntPtr self, ulong addr, out ModuleData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetSegmentData(IntPtr self, ulong addr, out SegmentData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetAppDomainData(IntPtr self, ulong addr, out AppDomainData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetJitManagerInfo(IntPtr self, ulong addr, out JitManagerInfo data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetSyncBlockData(IntPtr self, int index, out SyncBlockData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCodeHeaderData(IntPtr self, ulong addr, out CodeHeaderData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetFieldInfo(IntPtr self, ulong addr, out V4FieldInfo data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetFieldData(IntPtr self, ulong addr, out FieldData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetObjectData(IntPtr self, ulong addr, out V45ObjectData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCCWData(IntPtr self, ulong addr, out CCWData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetRCWData(IntPtr self, ulong addr, out RCWData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetWorkRequestData(IntPtr self, ulong addr, out WorkRequestData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetLocalModuleData(IntPtr self, ulong addr, out DomainLocalModuleData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetThreadFromThinLock(IntPtr self, uint id, out ulong data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCodeHeaps(IntPtr self, ulong addr, int count, [Out] JitCodeHeapInfo[] values, out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetCOMPointers(IntPtr self, ulong addr, int count, [Out] COMInterfacePointerData[] values, out int needed); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetDomainLocalModuleDataFromAppDomain(IntPtr self, ulong appDomainAddr, int moduleID, out DomainLocalModuleData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetThreadLocalModuleData(IntPtr self, ulong addr, uint id, out ThreadLocalModuleData data); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacTraverseLoaderHeap(IntPtr self, ulong addr, IntPtr callback); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacTraverseStubHeap(IntPtr self, ulong addr, int type, IntPtr callback); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacTraverseModuleMap(IntPtr self, int type, ulong addr, IntPtr callback, IntPtr param); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DacGetJitManagers(IntPtr self, int count, [Out] JitManagerInfo[] jitManagers, out int pNeeded); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetMetaDataImportDelegate(IntPtr self, ulong addr, out IntPtr iunk); } #pragma warning disable CS0169 #pragma warning disable CS0649 internal struct ISOSDacVTable { // ThreadStore public readonly IntPtr GetThreadStoreData; // AppDomains public readonly IntPtr GetAppDomainStoreData; public readonly IntPtr GetAppDomainList; public readonly IntPtr GetAppDomainData; public readonly IntPtr GetAppDomainName; public readonly IntPtr GetDomainFromContext; // Assemblies public readonly IntPtr GetAssemblyList; public readonly IntPtr GetAssemblyData; public readonly IntPtr GetAssemblyName; // Modules public readonly IntPtr GetMetaDataImport; public readonly IntPtr GetModuleData; public readonly IntPtr TraverseModuleMap; public readonly IntPtr GetAssemblyModuleList; public readonly IntPtr GetILForModule; // Threads public readonly IntPtr GetThreadData; public readonly IntPtr GetThreadFromThinlockID; public readonly IntPtr GetStackLimits; // MethodDescs public readonly IntPtr GetMethodDescData; public readonly IntPtr GetMethodDescPtrFromIP; public readonly IntPtr GetMethodDescName; public readonly IntPtr GetMethodDescPtrFromFrame; public readonly IntPtr GetMethodDescFromToken; private readonly IntPtr GetMethodDescTransparencyData; // JIT Data public readonly IntPtr GetCodeHeaderData; public readonly IntPtr GetJitManagerList; public readonly IntPtr GetJitHelperFunctionName; private readonly IntPtr GetJumpThunkTarget; // ThreadPool public readonly IntPtr GetThreadpoolData; public readonly IntPtr GetWorkRequestData; private readonly IntPtr GetHillClimbingLogEntry; // Objects public readonly IntPtr GetObjectData; public readonly IntPtr GetObjectStringData; public readonly IntPtr GetObjectClassName; // MethodTable public readonly IntPtr GetMethodTableName; public readonly IntPtr GetMethodTableData; public readonly IntPtr GetMethodTableSlot; public readonly IntPtr GetMethodTableFieldData; private readonly IntPtr GetMethodTableTransparencyData; // EEClass public readonly IntPtr GetMethodTableForEEClass; // FieldDesc public readonly IntPtr GetFieldDescData; // Frames public readonly IntPtr GetFrameName; // PEFiles public readonly IntPtr GetPEFileBase; public readonly IntPtr GetPEFileName; // GC public readonly IntPtr GetGCHeapData; public readonly IntPtr GetGCHeapList; // svr only public readonly IntPtr GetGCHeapDetails; // wks only public readonly IntPtr GetGCHeapStaticData; public readonly IntPtr GetHeapSegmentData; private readonly IntPtr GetOOMData; private readonly IntPtr GetOOMStaticData; private readonly IntPtr GetHeapAnalyzeData; private readonly IntPtr GetHeapAnalyzeStaticData; // DomainLocal private readonly IntPtr GetDomainLocalModuleData; public readonly IntPtr GetDomainLocalModuleDataFromAppDomain; public readonly IntPtr GetDomainLocalModuleDataFromModule; // ThreadLocal public readonly IntPtr GetThreadLocalModuleData; // SyncBlock public readonly IntPtr GetSyncBlockData; private readonly IntPtr GetSyncBlockCleanupData; // Handles public readonly IntPtr GetHandleEnum; private readonly IntPtr GetHandleEnumForTypes; private readonly IntPtr GetHandleEnumForGC; // EH private readonly IntPtr TraverseEHInfo; private readonly IntPtr GetNestedExceptionData; // StressLog public readonly IntPtr GetStressLogAddress; // Heaps public readonly IntPtr TraverseLoaderHeap; public readonly IntPtr GetCodeHeapList; public readonly IntPtr TraverseVirtCallStubHeap; // Other public readonly IntPtr GetUsefulGlobals; public readonly IntPtr GetClrWatsonBuckets; public readonly IntPtr GetTLSIndex; public readonly IntPtr GetDacModuleHandle; // COM public readonly IntPtr GetRCWData; public readonly IntPtr GetRCWInterfaces; public readonly IntPtr GetCCWData; public readonly IntPtr GetCCWInterfaces; private readonly IntPtr TraverseRCWCleanupList; // GC Reference Functions public readonly IntPtr GetStackReferences; public readonly IntPtr GetRegisterName; public readonly IntPtr GetThreadAllocData; public readonly IntPtr GetHeapAllocData; // For BindingDisplay plugin public readonly IntPtr GetFailedAssemblyList; public readonly IntPtr GetPrivateBinPaths; public readonly IntPtr GetAssemblyLocation; public readonly IntPtr GetAppDomainConfigFile; public readonly IntPtr GetApplicationBase; public readonly IntPtr GetFailedAssemblyData; public readonly IntPtr GetFailedAssemblyLocation; public readonly IntPtr GetFailedAssemblyDisplayName; } }
38.825959
169
0.653523
[ "MIT" ]
DamirAinullin/clrmd
src/Microsoft.Diagnostics.Runtime/src/DacInterface/SosDac.cs
39,488
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 marketplace-catalog-2018-09-17.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.MarketplaceCatalog { /// <summary> /// Configuration for accessing Amazon MarketplaceCatalog service /// </summary> public partial class AmazonMarketplaceCatalogConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.1.107"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonMarketplaceCatalogConfig() : base(new Amazon.Runtime.Internal.DefaultConfigurationProvider(AmazonMarketplaceCatalogDefaultConfiguration.GetAllConfigurations())) { this.AuthenticationServiceName = "aws-marketplace"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "catalog.marketplace"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-09-17"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
28.320988
145
0.612031
[ "Apache-2.0" ]
andyhopp/aws-sdk-net
sdk/src/Services/MarketplaceCatalog/Generated/AmazonMarketplaceCatalogConfig.cs
2,294
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using System.IO; using GME.MGA; namespace DynamicsTeamTest.Projects { public class CLM_LightFixture : XmeImportFixture { protected override string xmeFilename { get { return Path.Combine("CLM_Light", "CLM_Light.xme"); } } } public partial class CLM_Light : IUseFixture<CLM_LightFixture> { internal string mgaFile { get { return this.fixture.mgaFile; } } private CLM_LightFixture fixture { get; set; } public void SetFixture(CLM_LightFixture data) { this.fixture = data; } //[Fact] //[Trait("Model", "CLM_Light")] //[Trait("ProjectImport/Open", "CLM_Light")] //public void ProjectXmeImport() //{ // Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); //} [Fact] [Trait("Model", "CLM_Light")] [Trait("ProjectImport/Open", "CLM_Light")] public void ProjectMgaOpen() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.OpenEx(mgaReference, "CyPhyML", null); project.Close(true); Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_SuccessfulImport_Spring_2() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@Spring_2"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.True(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_SuccessfulImport_Spring_2_into_Optional_DesignContainer() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_OptionalContainer"; string componentToInsertPath = "/@Components/@Springs/@Spring_2"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.True(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_SuccessfulImport_Spring_3() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@Spring_3"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.True(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_SuccessfulImport_Spring_ModelicaParameterPortMapWithSameNameAsProperty() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@Spring_ModelicaParameterPortMapWithSameNameAsProperty"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.True(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_SuccessfulImport_Spring_PortClassIncorrect() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_OddCases/@Spring_PortClassIncorrect"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.True(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_RedundantPorts() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_RedundantPorts"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_PropertyWithPortName() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_PropertyWithPortName"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_PortNameIncorrect() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_PortNameIncorrect"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_ParamInsteadOfProperty() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_ParamInsteadOfProperty"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_MissingProperty() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_MissingProperty"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_Spring_MissingPort() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@CLM_Failure/@Spring_MissingPort"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_DesignContainerInstance() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@DesignSpace_MSD/@Instances/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@Spring_2"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } [Fact] [Trait("Model", "CLM_Light")] [Trait("CLM_light", "CLM_Light")] public void CLM_light_FailedImport_DesignContainerLibraryObject() { List<string> componentPaths = new List<string>(); string designContainerPath = "/@AttachedLibrary/@DesignSpace_MSD/@Spring_1"; string componentToInsertPath = "/@Components/@Springs/@Spring_2"; componentPaths.Add(componentToInsertPath); Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); bool insertionSuccessful = CLM_LightRunner.Run(mgaFile, designContainerPath, componentPaths); Assert.False(insertionSuccessful, string.Format("Failed to insert {0}", componentToInsertPath)); } } }
41.299296
123
0.633473
[ "MIT" ]
lefevre-fraser/openmeta-mms
test/DynamicsTeamTest/Projects/CLM_Light.cs
11,731
C#
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace DotNetCoreAkkaWindowsService { internal static class Program { private static async Task Main(string[] args) { var currentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); Directory.SetCurrentDirectory(currentDirectory); var builder = new HostBuilder() .ConfigureAppConfiguration(appConfig => appConfig.AddJsonFile("appsettings.json")) .ConfigureServices(services => services.AddHostedService<AkkaBackgroundService>()); var isDebugging = IsDebugging(args); builder.ConfigureSerilogLogging(isDebugging); if (isDebugging) { await builder.RunConsoleAsync(); } else { await builder.RunAsServiceAsync(); } } private static bool IsDebugging(ICollection<string> args) { #if DEBUG return true; #else return args.Contains("--console"); #endif } } }
30.255814
106
0.637971
[ "MIT" ]
yuriylsh/DotNetCoreAkkaWindowsService
Program.cs
1,303
C#
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System.Xml.Serialization; namespace Amazon.S3.Model { /// <summary> /// The SetBucketVersioningResponse contains the headers and request specific information /// returned by S3 /// </summary> [XmlTypeAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/")] [XmlRootAttribute(Namespace = "http://s3.amazonaws.com/doc/2006-03-01/", IsNullable = false)] public class SetBucketVersioningResponse : S3Response { } }
37.611111
97
0.590842
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.S3/Model/SetBucketVersioningResponse.cs
1,354
C#
namespace AgileObjects.AgileMapper.UnitTests { using System; using Common; using TestClasses; #if !NET35 using Xunit; #else using Fact = NUnit.Framework.TestAttribute; [NUnit.Framework.TestFixture] #endif public class WhenMappingOverComplexTypes { [Fact] public void ShouldReuseAnExistingTargetObject() { var source = new PublicField<string>(); var target = new PublicProperty<string>(); var result = Mapper.Map(source).Over(target); result.ShouldBe(target); } [Fact] public void ShouldMapFromAnAnonymousType() { var source = new { Id = Guid.NewGuid(), Name = "Mr Pants" }; var target = new Person { Id = Guid.NewGuid(), Name = "Mrs Trousers" }; var result = Mapper.Map(source).Over(target); result.Id.ShouldBe(source.Id); result.Name.ShouldBe(source.Name); } [Fact] public void ShouldOverwriteAnExistingSimpleTypePropertyValue() { var source = new PublicField<int> { Value = 123 }; var target = new PublicProperty<int> { Value = 789 }; Mapper.Map(source).Over(target); target.Value.ShouldBe(source.Value); } [Fact] public void ShouldNullAnExistingSimpleTypePropertyValue() { var source = new PublicProperty<double?> { Value = null }; var target = new PublicField<double?> { Value = 537.0 }; Mapper.Map(source).Over(target); target.Value.ShouldBeNull(); } [Fact] public void ShouldApplyAConfiguredConstant() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Person>() .Over<Person>() .Map("Big Timmy") .To(x => x.Name); var source = new Person { Name = "Alice" }; var target = new Person { Name = "Frank" }; var result = mapper.Map(source).Over(target); result.Name.ShouldBe("Big Timmy"); } } [Fact] public void ShouldApplyAConfiguredExpression() { using (var mapper = Mapper.CreateNew()) { mapper.WhenMapping .From<Customer>() .Over<Person>() .Map(ctx => ctx.Source.Id) .To(x => x.Name); var source = new Customer { Id = Guid.NewGuid() }; var target = new Person(); var result = mapper.Map(source).Over(target); result.Name.ShouldBe(source.Id.ToString()); } } [Fact] public void ShouldHandleANullSourceObject() { var target = new PublicProperty<int>(); var result = Mapper.Map(default(PublicField<int>)).Over(target); result.ShouldBe(target); } [Fact] public void ShouldOverwriteAMemberWithAMatchingCtorParameter() { var source = new PublicTwoFields<int, int> { Value1 = 123, Value2 = 456 }; var target = new PublicTwoParamCtor<int, int>(111, 222); Mapper.Map(source).Over(target); target.Value1.ShouldBe(111); target.Value2.ShouldBe(456); } } }
29.184874
86
0.522891
[ "MIT" ]
WeiiWang/AgileMapper
AgileMapper.UnitTests/WhenMappingOverComplexTypes.cs
3,475
C#
namespace SlackAPI.Models { public class OwnedStampedMessage { public string value { get; set; } public string creator { get; set; } public string last_set { get; set; } } }
23.333333
44
0.604762
[ "MIT" ]
xavierjefferson/SlackAPI
SlackAPI/Models/OwnedStampedMessage.cs
212
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interop; namespace WpfStylableWindow.StylableWindow { public static class SystemMenuManager { public static void ShowMenu(Window targetWindow, Point menuLocation) { if (targetWindow == null) throw new ArgumentNullException("TargetWindow is null."); int x, y; try { x = Convert.ToInt32(menuLocation.X); y = Convert.ToInt32(menuLocation.Y); } catch (OverflowException) { x = 0; y = 0; } uint WM_SYSCOMMAND = 0x112, TPM_LEFTALIGN = 0x0000, TPM_RETURNCMD = 0x0100; IntPtr window = new WindowInteropHelper(targetWindow).Handle; IntPtr wMenu = NativeMethods.GetSystemMenu(window, false); int command = NativeMethods.TrackPopupMenuEx(wMenu, TPM_LEFTALIGN | TPM_RETURNCMD, x, y, window, IntPtr.Zero); if (command == 0) return; NativeMethods.PostMessage(window, WM_SYSCOMMAND, new IntPtr(command), IntPtr.Zero); } } internal static class NativeMethods { [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] internal static extern int TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y, IntPtr hwnd, IntPtr lptpm); [DllImport("user32.dll")] internal static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] internal static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable); } }
31.903226
122
0.624368
[ "MIT" ]
ApanLoon/Hexalyser
src/Hexalyser/Views/Components/WpfStylableWindow/Behaviours/SystemMenuManager.cs
1,980
C#
using Shapes.Library.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace Shapes.Library {// backing field public class CircleAdv : IShape { protected double _radius; public virtual double Radius //virtual: subclasses can override this { get { return _radius * 1.01; } set { if (value < 0) { Console.WriteLine("Err: Radius cannot be negative"); } else { _radius = value; }; } } public virtual double GetPerimeter() => 2 * Math.PI * Radius; public virtual double Area => Radius * Math.PI * Radius; public virtual int Sides => 1; } }
25.387097
72
0.52859
[ "MIT" ]
1904-apr22-net/sadiki-code
Shapes/Shapes.Library/CircleAdv.cs
789
C#
using Gtk; using IFACARS.Types.Gtk; using UI = Gtk.Builder.ObjectAttribute; namespace IFACARS.Screens { public class InitialConnectionScreen : StackScreen { private const string _xmlName = "flight_initialConnection"; /* Glade objects */ [UI] private Stack initialConnectionScreenStack = null; [UI] private Button connection_continueSearchingButton = null; [UI] private Button connection_connectButton = null; public InitialConnectionScreen(Stack parentStack) : base(parentStack, _xmlName) { } public override void Init() { SwitchToDiscoverInstancesScreen(); SetupEvents(); } private void SetupEvents() { //create_startAnew.Clicked += (sender, args) => SwitchToFlightInfoScreen(); //create_fromBriefing.Clicked += (sender, args) => SwitchToFlightInfoScreen(); } private void SwitchToDiscoverInstancesScreen() { initialConnectionScreenStack.VisibleChildName = "connection_discoverInstances"; } private void SwitchToInstanceInfoScreen() { initialConnectionScreenStack.VisibleChildName = "connection_instanceInformation"; } private void SwitchToConnectScreen() { initialConnectionScreenStack.VisibleChildName = "connection_connect"; } } }
29.62
93
0.622552
[ "MIT" ]
if-tools/IFACARS
IFACARS/Screens/InitialConnectionScreen.cs
1,481
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; 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("Microsoft Azure Powershell")] [assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] [assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] [assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] // 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("a102cbe8-8a50-43b1-821d-72b42b9831a4")] // 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("4.5.0")] [assembly: AssemblyFileVersion("4.5.0")] #if SIGN [assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test")] #endif [assembly: CLSCompliant(false)]
50.25
411
0.73774
[ "MIT" ]
FonsecaSergio/azure-powershell
src/Storage/Commands.Storage/Properties/AssemblyInfo.cs
2,759
C#
namespace RecentRecordsDemo.Controllers { using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using EasyCaching.Core; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; using System; /// <summary> /// Triggered by scheduling system /// </summary> [Route("api/cal")] [ApiController] public class CalculatiionController : ControllerBase { private readonly ILogger _logger; private readonly IRedisCachingProvider _provider; public CalculatiionController(ILoggerFactory loggerFactory, IRedisCachingProvider provider) { _logger = loggerFactory.CreateLogger<CalculatiionController>(); _provider = provider; } // GET api/cal/ [HttpGet] public string Get() { var id = Guid.NewGuid().ToString("N"); _ = Task.Run(async () => await CalAsync(id)); return "ok"; } private async Task CalAsync(string id) { _logger.LogInformation($"{id} begin at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); var datasourceIds = GetAllDataSourceIds(); foreach (var item in datasourceIds) { try { var topN = await _provider.LRangeAsync<DataSourceInfo>($"info:{item}", 0, 99); var cost = topN.Average(x => x.Cost); var rate = topN.Count(x => x.IsSucceed) / 100; var score = GetScore(cost, rate); await _provider.HSetAsync($"dskpi", item, score.ToString()); } catch (Exception ex) { _logger.LogError(ex, $"{id} {item} calculate fail ..."); } } _logger.LogInformation($"{id} end at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); } private int GetScore(double cost, int rate) { return new Random().Next(1, 100); } private List<string> GetAllDataSourceIds() { return new List<string> { "100", "900" }; } } }
29.164557
100
0.521701
[ "MIT" ]
catcherwong-archive/2019
07/RecentRecordsDemo/RecentRecordsDemo/Controllers/CalculatiionController.cs
2,306
C#
using DBLayer; using System; using System.Collections.Generic; //using System.Data.SqlClient; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using WCFServiceCL; namespace FinalProjectFDM { public class Program { static void Main(string[] args) { /* DecathonGame decgame = new DecathonGame(); List<int> lotto = decgame.Lottery(); //foreach (var num in lotto) //{ // Console.WriteLine(num); //} List<int> userlotto = decgame.Userlottery(48, 35, 27, 11, 14, 8); if (decgame.Lotteryresult(lotto, userlotto) == true) { Console.WriteLine("You have won!"); } else { Console.WriteLine("You have lost. Better Luck Next Time."); } Console.Read(); */ /* //Trying Bet method. BetClass BC = new BetClass(); List<string> TryGame = BC.Bet(73, 5); Console.WriteLine("You "+TryGame[0] + ", your return is £"+TryGame[1]+"p"); Console.ReadLine(); */ /* //Testing service with a makeshift client: EndpointAddress endpoint = new EndpointAddress("http://trnlon11566:8081/Service"); IServe proxy = ChannelFactory<IServe>.CreateChannel(new BasicHttpBinding(), endpoint); Game game = new Game(); game.name = "Game1"; game.payout = 20; proxy.CreateGameServiceMethod(game); */ /* string one = Console.ReadLine(); int two = Console.Read(); decimal username = Convert.ToDecimal(one); //int password = Convert.ToDecimal(one); decimal answer = username / two; Console.WriteLine(answer); Console.ReadLine();*/ //string username = Console.ReadLine(); //string password = Console.ReadLine(); //SqlConnection SQLConnectioN = new SqlConnection(); } } }
30.378378
99
0.507562
[ "MIT" ]
Y2PM/2WeekProjectSecondVersion
FinalProjectFDM/Program.cs
2,251
C#
using UnityEngine; using System.Collections; public class RaycastMovement : MonoBehaviour { public GameObject raycastHolder; public GameObject player; public GameObject raycastIndicator; public float height = 2; public bool teleport = true; public float maxMoveDistance = 10; private bool moving = false; RaycastHit hit; float theDistance; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 forwardDir = raycastHolder.transform.TransformDirection (Vector3.forward) * 100; //Debug.DrawRay (raycastHolder.transform.position, forwardDir, Color.green); if (Physics.Raycast (raycastHolder.transform.position, (forwardDir), out hit)) { if (hit.collider.gameObject.tag == "movementCapable") { ManageIndicator (); if (hit.distance <= maxMoveDistance) { //If we are close enough //If the indicator isn't active already make it active. if (raycastIndicator.activeSelf == false) { raycastIndicator.SetActive (true); } if (Input.GetMouseButtonDown (0)) { if (teleport) { teleportMove (hit.point); } else { DashMove (hit.point); } } } else { if (raycastIndicator.activeSelf == true) { raycastIndicator.SetActive (false); } } } } } public void ManageIndicator() { if (!teleport) { if (moving != true) { raycastIndicator.transform.position = hit.point; raycastIndicator.transform.rotation = Quaternion.Euler(0f, raycastHolder.transform.rotation.eulerAngles.y, 0f); } if(Vector3.Distance(raycastIndicator.transform.position, player.transform.position) <= 2.5) { moving = false; } } else { raycastIndicator.transform.position = hit.point; raycastIndicator.transform.rotation = Quaternion.Euler(0f, raycastHolder.transform.rotation.eulerAngles.y, 0f); } } public void DashMove(Vector3 location) { moving = true; iTween.MoveTo (player, iTween.Hash ( "position", new Vector3 (location.x, location.y + height, location.z), "time", .2F, "easetype", "linear" ) ); } public void teleportMove(Vector3 location) { player.transform.position = new Vector3 (location.x, location.y + height, location.z); } }
26.157303
127
0.664519
[ "Apache-2.0" ]
Nick0108/Museum_VR
Assets/Scripts/RaycastMovement.cs
2,330
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.OperationalInsights.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Display metadata associated with the operation. /// </summary> public partial class OperationDisplay { /// <summary> /// Initializes a new instance of the OperationDisplay class. /// </summary> public OperationDisplay() { CustomInit(); } /// <summary> /// Initializes a new instance of the OperationDisplay class. /// </summary> /// <param name="provider">Service provider: Microsoft /// OperationsManagement.</param> /// <param name="resource">Resource on which the operation is performed /// etc.</param> /// <param name="operation">Type of operation: get, read, delete, /// etc.</param> /// <param name="description">Description of operation</param> public OperationDisplay(string provider = default(string), string resource = default(string), string operation = default(string), string description = default(string)) { Provider = provider; Resource = resource; Operation = operation; Description = description; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets service provider: Microsoft OperationsManagement. /// </summary> [JsonProperty(PropertyName = "provider")] public string Provider { get; set; } /// <summary> /// Gets or sets resource on which the operation is performed etc. /// </summary> [JsonProperty(PropertyName = "resource")] public string Resource { get; set; } /// <summary> /// Gets or sets type of operation: get, read, delete, etc. /// </summary> [JsonProperty(PropertyName = "operation")] public string Operation { get; set; } /// <summary> /// Gets or sets description of operation /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } } }
33.987342
175
0.605214
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/operationalinsights/Microsoft.Azure.Management.OperationalInsights/src/Generated/Models/OperationDisplay.cs
2,685
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/d3d10.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.Windows; namespace TerraFX.Interop.DirectX; public unsafe partial struct D3D10_BLEND_DESC { public BOOL AlphaToCoverageEnable; [NativeTypeName("BOOL [8]")] public _BlendEnable_e__FixedBuffer BlendEnable; public D3D10_BLEND SrcBlend; public D3D10_BLEND DestBlend; public D3D10_BLEND_OP BlendOp; public D3D10_BLEND SrcBlendAlpha; public D3D10_BLEND DestBlendAlpha; public D3D10_BLEND_OP BlendOpAlpha; [NativeTypeName("UINT8 [8]")] public fixed byte RenderTargetWriteMask[8]; public partial struct _BlendEnable_e__FixedBuffer { public BOOL e0; public BOOL e1; public BOOL e2; public BOOL e3; public BOOL e4; public BOOL e5; public BOOL e6; public BOOL e7; public ref BOOL this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref AsSpan()[index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<BOOL> AsSpan() => MemoryMarshal.CreateSpan(ref e0, 8); } }
25.966102
145
0.681462
[ "MIT" ]
JeremyKuhne/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d10/D3D10_BLEND_DESC.cs
1,534
C#
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace ZiggyCreatures.Caching.Fusion.Tests { public static class SingleLevelTestsExtMethods { public static FusionCacheEntryOptions SetFactoryTimeoutsMs(this FusionCacheEntryOptions options, int? softTimeoutMs = null, int? hardTimeoutMs = null, bool? keepTimedOutFactoryResult = null) { if (softTimeoutMs is object) options.FactorySoftTimeout = TimeSpan.FromMilliseconds(softTimeoutMs.Value); if (hardTimeoutMs is object) options.FactoryHardTimeout = TimeSpan.FromMilliseconds(hardTimeoutMs.Value); if (keepTimedOutFactoryResult is object) options.AllowTimedOutFactoryBackgroundCompletion = keepTimedOutFactoryResult.Value; return options; } } public class SingleLevelTests { [Fact] public void CannotAssignNullToDefaultEntryOptions() { Assert.Throws<ArgumentNullException>(() => { var foo = new FusionCacheOptions() { DefaultEntryOptions = null }; }); } [Fact] public async Task ReturnsStaleDataWhenFactoryFailsWithFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); await Task.Delay(1_100); var newValue = await cache.GetOrSetAsync<int>("foo", async _ => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Assert.Equal(initialValue, newValue); } } [Fact] public void ReturnsStaleDataWhenFactoryFailsWithFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Thread.Sleep(1_100); var newValue = cache.GetOrSet<int>("foo", _ => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Assert.Equal(initialValue, newValue); } } [Fact] public async Task ThrowsWhenFactoryThrowsWithoutFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); await Task.Delay(1_100); await Assert.ThrowsAnyAsync<Exception>(async () => { var newValue = await cache.GetOrSetAsync<int>("foo", async _ => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(false)); }); } } [Fact] public void ThrowsWhenFactoryThrowsWithoutFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Thread.Sleep(1_100); Assert.ThrowsAny<Exception>(() => { var newValue = cache.GetOrSet<int>("foo", _ => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = false }); }); } } [Fact] public async Task ThrowsOnFactoryHardTimeoutWithoutStaleDataAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { await Assert.ThrowsAsync<SyntheticTimeoutException>(async () => { var value = await cache.GetOrSetAsync<int>("foo", async _ => { await Task.Delay(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(2_000, 100)); }); } } [Fact] public void ThrowsOnFactoryHardTimeoutWithoutStaleData() { using (var cache = new FusionCache(new FusionCacheOptions())) { Assert.Throws<SyntheticTimeoutException>(() => { var value = cache.GetOrSet<int>("foo", _ => { Thread.Sleep(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(2_000, 100)); }); } } [Fact] public async Task ReturnsStaleDataWhenFactorySoftTimeoutWithFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); await Task.Delay(1_100); var newValue = await cache.GetOrSetAsync<int>("foo", async _ => { await Task.Delay(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100)); Assert.Equal(initialValue, newValue); } } [Fact] public void ReturnsStaleDataWhenFactorySoftTimeoutWithFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Thread.Sleep(1_100); var newValue = cache.GetOrSet<int>("foo", _ => { Thread.Sleep(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100)); Assert.Equal(initialValue, newValue); } } [Fact] public async Task DoesNotSoftTimeoutWithoutStaleDataAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => { await Task.Delay(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100)); Assert.Equal(21, initialValue); } } [Fact] public void DoesNotSoftTimeoutWithoutStaleData() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => { Thread.Sleep(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100)); Assert.Equal(21, initialValue); } } [Fact] public async Task DoesHardTimeoutEvenWithoutStaleDataAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { await Assert.ThrowsAnyAsync<Exception>(async () => { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => { await Task.Delay(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100, 500)); }); } } [Fact] public void DoesHardTimeoutEvenWithoutStaleData() { using (var cache = new FusionCache(new FusionCacheOptions())) { Assert.ThrowsAny<Exception>(() => { var initialValue = cache.GetOrSet<int>("foo", _ => { Thread.Sleep(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100, 500)); }); } } [Fact] public async Task ReturnsStaleDataWhenFactoryHitHardTimeoutWithFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { await cache.SetAsync<int>("foo", 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); await Task.Delay(1_100); var newValue = await cache.GetOrSetAsync<int>("foo", async _ => { await Task.Delay(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100, 500)); Assert.Equal(42, newValue); } } [Fact] public void ReturnsStaleDataWhenFactoryHitHardTimeoutWithFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { cache.Set<int>("foo", 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Thread.Sleep(1_100); var newValue = cache.GetOrSet<int>("foo", _ => { Thread.Sleep(1_000); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(100, 500)); Assert.Equal(42, newValue); } } [Fact] public async Task SetOverwritesAnExistingValueAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; var newValue = 21; cache.Set<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); cache.Set<int>("foo", newValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); var actualValue = await cache.GetOrDefaultAsync<int>("foo", -1, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); Assert.Equal(newValue, actualValue); } } [Fact] public void SetOverwritesAnExistingValue() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; var newValue = 21; cache.Set<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); cache.Set<int>("foo", newValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); var actualValue = cache.GetOrDefault<int>("foo", -1, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); Assert.Equal(newValue, actualValue); } } [Fact] public async Task GetOrSetDoesNotOverwriteANonExpiredValueAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); var newValue = await cache.GetOrSetAsync<int>("foo", async _ => 21, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); Assert.Equal(initialValue, newValue); } } [Fact] public void GetOrSetDoesNotOverwriteANonExpiredValue() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); var newValue = cache.GetOrSet<int>("foo", _ => 21, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); Assert.Equal(initialValue, newValue); } } [Fact] public async Task DoesNotReturnStaleDataIfFactorySucceedsAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = await cache.GetOrSetAsync<int>("foo", async _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); await Task.Delay(1_500); var newValue = await cache.GetOrSetAsync<int>("foo", async _ => 21, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Assert.NotEqual(initialValue, newValue); } } [Fact] public void DoesNotReturnStaleDataIfFactorySucceeds() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = cache.GetOrSet<int>("foo", _ => 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Thread.Sleep(1_500); var newValue = cache.GetOrSet<int>("foo", _ => 21, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Assert.NotEqual(initialValue, newValue); } } [Fact] public async Task GetOrDefaultDoesReturnStaleDataWithFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; await cache.SetAsync<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); await Task.Delay(1_500); var newValue = await cache.GetOrDefaultAsync<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Assert.Equal(initialValue, newValue); } } [Fact] public void GetOrDefaultDoesReturnStaleDataWithFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; cache.Set<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Thread.Sleep(1_500); var newValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); Assert.Equal(initialValue, newValue); } } [Fact] public async Task GetOrDefaultDoesNotReturnStaleDataWithoutFailSafeAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; await cache.SetAsync<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = true }); await Task.Delay(1_500); var newValue = await cache.GetOrDefaultAsync<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)) { IsFailSafeEnabled = false }); Assert.NotEqual(initialValue, newValue); } } [Fact] public void GetOrDefaultDoesNotReturnStaleWithoutFailSafe() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = 42; cache.Set<int>("foo", initialValue, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Thread.Sleep(1_500); var newValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(false)); Assert.NotEqual(initialValue, newValue); } } [Fact] public async Task FactoryTimedOutButSuccessfulDoesUpdateCachedValueAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { await cache.SetAsync<int>("foo", 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true, TimeSpan.FromMinutes(1))); var initialValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true, TimeSpan.FromMinutes(1))); await Task.Delay(1_500); var middleValue = await cache.GetOrSetAsync<int>("foo", async ct => { await Task.Delay(2_000); ct.ThrowIfCancellationRequested(); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(500)); var interstitialValue = await cache.GetOrDefaultAsync<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); await Task.Delay(3_000); var finalValue = await cache.GetOrDefaultAsync<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Assert.Equal(42, initialValue); Assert.Equal(42, middleValue); Assert.Equal(42, interstitialValue); Assert.Equal(21, finalValue); } } [Fact] public void FactoryTimedOutButSuccessfulDoesUpdateCachedValue() { using (var cache = new FusionCache(new FusionCacheOptions())) { cache.Set<int>("foo", 42, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true, TimeSpan.FromMinutes(1))); var initialValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true, TimeSpan.FromMinutes(1))); Thread.Sleep(1_500); var middleValue = cache.GetOrSet<int>("foo", ct => { Thread.Sleep(2_000); ct.ThrowIfCancellationRequested(); return 21; }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true).SetFactoryTimeoutsMs(500)); var interstitialValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Thread.Sleep(3_000); var finalValue = cache.GetOrDefault<int>("foo", options: new FusionCacheEntryOptions(TimeSpan.FromSeconds(1)).SetFailSafe(true)); Assert.Equal(42, initialValue); Assert.Equal(42, middleValue); Assert.Equal(42, interstitialValue); Assert.Equal(21, finalValue); } } [Fact] public async Task TryGetReturnsCorrectlyAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var res1 = await cache.TryGetAsync<int>("foo"); await cache.SetAsync<int>("foo", 42); var res2 = await cache.TryGetAsync<int>("foo"); Assert.False(res1.HasValue); Assert.Throws<InvalidOperationException>(() => { var foo = res1.Value; }); Assert.True(res2.HasValue); Assert.Equal(42, res2.Value); } } [Fact] public void TryGetReturnsCorrectly() { using (var cache = new FusionCache(new FusionCacheOptions())) { var res1 = cache.TryGet<int>("foo"); cache.Set<int>("foo", 42); var res2 = cache.TryGet<int>("foo"); Assert.False(res1.HasValue); Assert.Throws<InvalidOperationException>(() => { var foo = res1.Value; }); Assert.True(res2.HasValue); Assert.Equal(42, res2.Value); } } [Fact] public async Task CancelingAnOperationActuallyCancelsItAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { int res = -1; var sw = Stopwatch.StartNew(); var outerCancelDelayMs = 500; var factoryDelayMs = 2_000; await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { var cts = new CancellationTokenSource(outerCancelDelayMs); res = await cache.GetOrSetAsync<int>("foo", async ct => { await Task.Delay(factoryDelayMs); ct.ThrowIfCancellationRequested(); return 42; }, options => options.SetDurationSec(60), cts.Token); }); sw.Stop(); Assert.Equal(-1, res); // TODO: MAYBE DON'T RELY ON ELAPSED TIME Assert.True(sw.ElapsedMilliseconds > outerCancelDelayMs, "Elapsed is lower or equal than outer cancel"); Assert.True(sw.ElapsedMilliseconds < factoryDelayMs, "Elapsed is greater or equal than factory delay"); } } [Fact] public void CancelingAnOperationActuallyCancelsIt() { using (var cache = new FusionCache(new FusionCacheOptions())) { int res = -1; var sw = Stopwatch.StartNew(); var outerCancelDelayMs = 500; var factoryDelayMs = 2_000; Assert.ThrowsAny<OperationCanceledException>(() => { var cts = new CancellationTokenSource(outerCancelDelayMs); res = cache.GetOrSet<int>("foo", ct => { Thread.Sleep(factoryDelayMs); ct.ThrowIfCancellationRequested(); return 42; }, options => options.SetDurationSec(60), cts.Token); }); sw.Stop(); Assert.Equal(-1, res); // TODO: MAYBE DON'T RELY ON ELAPSED TIME Assert.True(sw.ElapsedMilliseconds > outerCancelDelayMs, "Elapsed is lower or equal than outer cancel"); Assert.True(sw.ElapsedMilliseconds < factoryDelayMs, "Elapsed is greater or equal than factory delay"); } } [Fact] public async Task HandlesFlexibleSimpleTypeConversionsAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = (object)42; await cache.SetAsync("foo", initialValue, TimeSpan.FromHours(24)); var newValue = await cache.GetOrDefaultAsync<int>("foo"); Assert.Equal(initialValue, newValue); } } [Fact] public void HandlesFlexibleSimpleTypeConversions() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = (object)42; cache.Set("foo", initialValue, TimeSpan.FromHours(24)); var newValue = cache.GetOrDefault<int>("foo"); Assert.Equal(initialValue, newValue); } } [Fact] public async Task HandlesFlexibleComplexTypeConversionsAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = (object)SampleComplexObject.CreateRandom(); await cache.SetAsync("foo", initialValue, TimeSpan.FromHours(24)); var newValue = await cache.GetOrDefaultAsync<SampleComplexObject>("foo"); Assert.NotNull(newValue); } } [Fact] public void HandlesFlexibleComplexTypeConversions() { using (var cache = new FusionCache(new FusionCacheOptions())) { var initialValue = (object)SampleComplexObject.CreateRandom(); cache.Set("foo", initialValue, TimeSpan.FromHours(24)); var newValue = cache.GetOrDefault<SampleComplexObject>("foo"); Assert.NotNull(newValue); } } [Fact] public async Task GetOrDefaultDoesNotSetAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var foo = await cache.GetOrDefaultAsync<int>("foo", 42, opt => opt.SetDuration(TimeSpan.FromHours(24))); var bar = await cache.GetOrDefaultAsync<int>("foo", 21, opt => opt.SetDuration(TimeSpan.FromHours(24))); var baz = await cache.TryGetAsync<int>("foo", opt => opt.SetDuration(TimeSpan.FromHours(24))); Assert.Equal(42, foo); Assert.Equal(21, bar); Assert.False(baz.HasValue); } } [Fact] public void GetOrDefaultDoesNotSet() { using (var cache = new FusionCache(new FusionCacheOptions())) { var foo = cache.GetOrDefault<int>("foo", 42, opt => opt.SetDuration(TimeSpan.FromHours(24))); var bar = cache.GetOrDefault<int>("foo", 21, opt => opt.SetDuration(TimeSpan.FromHours(24))); var baz = cache.TryGet<int>("foo", opt => opt.SetDuration(TimeSpan.FromHours(24))); Assert.Equal(42, foo); Assert.Equal(21, bar); Assert.False(baz.HasValue); } } [Fact] public async Task GetOrSetWithDefaultValueWorksAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var foo = 42; await cache.GetOrSetAsync<int>("foo", foo, TimeSpan.FromHours(24)); var bar = await cache.GetOrDefaultAsync<int>("foo", 21); Assert.Equal(foo, bar); } } [Fact] public void GetOrSetWithDefaultValueWorks() { using (var cache = new FusionCache(new FusionCacheOptions())) { var foo = 42; cache.GetOrSet<int>("foo", foo, TimeSpan.FromHours(24)); var bar = cache.GetOrDefault<int>("foo", 21); Assert.Equal(foo, bar); } } [Fact] public async Task ThrottleDurationWorksCorrectlyAsync() { using (var cache = new FusionCache(new FusionCacheOptions())) { var duration = TimeSpan.FromSeconds(1); var throttleDuration = TimeSpan.FromSeconds(3); // SET THE VALUE (WITH FAIL-SAFE ENABLED) await cache.SetAsync("foo", 42, opt => opt.SetDuration(duration).SetFailSafe(true, throttleDuration: throttleDuration)); // LET IT EXPIRE await Task.Delay(duration + TimeSpan.FromSeconds(1)).ConfigureAwait(false); // CHECK EXPIRED (WITHOUT FAIL-SAFE) var nope = await cache.TryGetAsync<int>("foo", opt => opt.SetFailSafe(false)); // ACTIVATE FAIL-SAFE AND RE-STORE THE VALUE WITH THROTTLE DURATION var throttled1 = await cache.GetOrDefaultAsync("foo", 1, opt => opt.SetFailSafe(true, throttleDuration: throttleDuration)); // WAIT A LITTLE BIT (LESS THAN THE DURATION) await Task.Delay(100).ConfigureAwait(false); // GET THE THROTTLED (NON EXPIRED) VALUE var throttled2 = await cache.GetOrDefaultAsync("foo", 2, opt => opt.SetFailSafe(false)); // LET THE THROTTLE DURATION PASS await Task.Delay(throttleDuration).ConfigureAwait(false); // FALLBACK TO THE DEFAULT VALUE var default3 = await cache.GetOrDefaultAsync("foo", 3, opt => opt.SetFailSafe(false)); Assert.False(nope.HasValue); Assert.Equal(42, throttled1); Assert.Equal(42, throttled2); Assert.Equal(3, default3); } } [Fact] public void ThrottleDurationWorksCorrectly() { using (var cache = new FusionCache(new FusionCacheOptions())) { var duration = TimeSpan.FromSeconds(1); var throttleDuration = TimeSpan.FromSeconds(3); // SET THE VALUE (WITH FAIL-SAFE ENABLED) cache.Set("foo", 42, opt => opt.SetDuration(duration).SetFailSafe(true, throttleDuration: throttleDuration)); // LET IT EXPIRE Thread.Sleep(duration + TimeSpan.FromSeconds(1)); // CHECK EXPIRED (WITHOUT FAIL-SAFE) var nope = cache.TryGet<int>("foo", opt => opt.SetFailSafe(false)); // ACTIVATE FAIL-SAFE AND RE-STORE THE VALUE WITH THROTTLE DURATION var throttled1 = cache.GetOrDefault("foo", 1, opt => opt.SetFailSafe(true, throttleDuration: throttleDuration)); // WAIT A LITTLE BIT (LESS THAN THE DURATION) Thread.Sleep(100); // GET THE THROTTLED (NON EXPIRED) VALUE var throttled2 = cache.GetOrDefault("foo", 2, opt => opt.SetFailSafe(false)); // LET THE THROTTLE DURATION PASS Thread.Sleep(throttleDuration); // FALLBACK TO THE DEFAULT VALUE var default3 = cache.GetOrDefault("foo", 3, opt => opt.SetFailSafe(false)); Assert.False(nope.HasValue); Assert.Equal(42, throttled1); Assert.Equal(42, throttled2); Assert.Equal(3, default3); } } } }
39.165854
246
0.711836
[ "MIT" ]
Jaxelr/ZiggyCreatures.FusionCache
tests/ZiggyCreatures.FusionCache.Tests/SingleLevelTests.cs
24,089
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// CallbackBasic /// </summary> [DataContract] public partial class CallbackBasic : IEquatable<CallbackBasic> { /// <summary> /// The connection state of this communication. /// </summary> /// <value>The connection state of this communication.</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum StateEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Alerting for "alerting" /// </summary> [EnumMember(Value = "alerting")] Alerting, /// <summary> /// Enum Dialing for "dialing" /// </summary> [EnumMember(Value = "dialing")] Dialing, /// <summary> /// Enum Contacting for "contacting" /// </summary> [EnumMember(Value = "contacting")] Contacting, /// <summary> /// Enum Offering for "offering" /// </summary> [EnumMember(Value = "offering")] Offering, /// <summary> /// Enum Connected for "connected" /// </summary> [EnumMember(Value = "connected")] Connected, /// <summary> /// Enum Disconnected for "disconnected" /// </summary> [EnumMember(Value = "disconnected")] Disconnected, /// <summary> /// Enum Terminated for "terminated" /// </summary> [EnumMember(Value = "terminated")] Terminated, /// <summary> /// Enum Scheduled for "scheduled" /// </summary> [EnumMember(Value = "scheduled")] Scheduled, /// <summary> /// Enum None for "none" /// </summary> [EnumMember(Value = "none")] None } /// <summary> /// The direction of the call /// </summary> /// <value>The direction of the call</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum DirectionEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Inbound for "inbound" /// </summary> [EnumMember(Value = "inbound")] Inbound, /// <summary> /// Enum Outbound for "outbound" /// </summary> [EnumMember(Value = "outbound")] Outbound } /// <summary> /// System defined string indicating what caused the communication to disconnect. Will be null until the communication disconnects. /// </summary> /// <value>System defined string indicating what caused the communication to disconnect. Will be null until the communication disconnects.</value> [JsonConverter(typeof(UpgradeSdkEnumConverter))] public enum DisconnectTypeEnum { /// <summary> /// Your SDK version is out of date and an unknown enum value was encountered. /// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk" /// in the Package Manager Console /// </summary> [EnumMember(Value = "OUTDATED_SDK_VERSION")] OutdatedSdkVersion, /// <summary> /// Enum Endpoint for "endpoint" /// </summary> [EnumMember(Value = "endpoint")] Endpoint, /// <summary> /// Enum Client for "client" /// </summary> [EnumMember(Value = "client")] Client, /// <summary> /// Enum System for "system" /// </summary> [EnumMember(Value = "system")] System, /// <summary> /// Enum Timeout for "timeout" /// </summary> [EnumMember(Value = "timeout")] Timeout, /// <summary> /// Enum Transfer for "transfer" /// </summary> [EnumMember(Value = "transfer")] Transfer, /// <summary> /// Enum Transferconference for "transfer.conference" /// </summary> [EnumMember(Value = "transfer.conference")] Transferconference, /// <summary> /// Enum Transferconsult for "transfer.consult" /// </summary> [EnumMember(Value = "transfer.consult")] Transferconsult, /// <summary> /// Enum Transferforward for "transfer.forward" /// </summary> [EnumMember(Value = "transfer.forward")] Transferforward, /// <summary> /// Enum Transfernoanswer for "transfer.noanswer" /// </summary> [EnumMember(Value = "transfer.noanswer")] Transfernoanswer, /// <summary> /// Enum Transfernotavailable for "transfer.notavailable" /// </summary> [EnumMember(Value = "transfer.notavailable")] Transfernotavailable, /// <summary> /// Enum Transportfailure for "transport.failure" /// </summary> [EnumMember(Value = "transport.failure")] Transportfailure, /// <summary> /// Enum Error for "error" /// </summary> [EnumMember(Value = "error")] Error, /// <summary> /// Enum Peer for "peer" /// </summary> [EnumMember(Value = "peer")] Peer, /// <summary> /// Enum Other for "other" /// </summary> [EnumMember(Value = "other")] Other, /// <summary> /// Enum Spam for "spam" /// </summary> [EnumMember(Value = "spam")] Spam, /// <summary> /// Enum Uncallable for "uncallable" /// </summary> [EnumMember(Value = "uncallable")] Uncallable } /// <summary> /// The connection state of this communication. /// </summary> /// <value>The connection state of this communication.</value> [DataMember(Name="state", EmitDefaultValue=false)] public StateEnum? State { get; set; } /// <summary> /// The direction of the call /// </summary> /// <value>The direction of the call</value> [DataMember(Name="direction", EmitDefaultValue=false)] public DirectionEnum? Direction { get; set; } /// <summary> /// System defined string indicating what caused the communication to disconnect. Will be null until the communication disconnects. /// </summary> /// <value>System defined string indicating what caused the communication to disconnect. Will be null until the communication disconnects.</value> [DataMember(Name="disconnectType", EmitDefaultValue=false)] public DisconnectTypeEnum? DisconnectType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="CallbackBasic" /> class. /// </summary> /// <param name="State">The connection state of this communication..</param> /// <param name="Id">A globally unique identifier for this communication..</param> /// <param name="Segments">The time line of the participant&#39;s callback, divided into activity segments..</param> /// <param name="Direction">The direction of the call.</param> /// <param name="Held">True if this call is held and the person on this side hears silence..</param> /// <param name="DisconnectType">System defined string indicating what caused the communication to disconnect. Will be null until the communication disconnects..</param> /// <param name="StartHoldTime">The timestamp the callback was placed on hold in the cloud clock if the callback is currently on hold. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param> /// <param name="DialerPreview">The preview data to be used when this callback is a Preview..</param> /// <param name="Voicemail">The voicemail data to be used when this callback is an ACD voicemail..</param> /// <param name="CallbackNumbers">The phone number(s) to use to place the callback..</param> /// <param name="CallbackUserName">The name of the user requesting a callback..</param> /// <param name="ScriptId">The UUID of the script to use..</param> /// <param name="ExternalCampaign">True if the call for the callback uses external dialing..</param> /// <param name="SkipEnabled">True if the ability to skip a callback should be enabled..</param> /// <param name="TimeoutSeconds">The number of seconds before the system automatically places a call for a callback. 0 means the automatic placement is disabled..</param> /// <param name="StartAlertingTime">The timestamp the communication has when it is first put into an alerting state. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param> /// <param name="ConnectedTime">The timestamp when this communication was connected in the cloud clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param> /// <param name="DisconnectedTime">The timestamp when this communication disconnected from the conversation in the provider clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param> /// <param name="CallbackScheduledTime">The timestamp when this communication is scheduled in the provider clock. If this value is missing it indicates the callback will be placed immediately. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param> /// <param name="AutomatedCallbackConfigId">The id of the config for automatically placing the callback (and handling the disposition). If null, the callback will not be placed automatically but routed to an agent as per normal..</param> /// <param name="Provider">The source provider for the callback..</param> /// <param name="PeerId">The id of the peer communication corresponding to a matching leg for this communication..</param> /// <param name="Wrapup">Call wrap up or disposition data..</param> /// <param name="AfterCallWork">After-call work for the communication..</param> /// <param name="AfterCallWorkRequired">Indicates if after-call work is required for a communication. Only used when the ACW Setting is Agent Requested..</param> /// <param name="CallerId">The phone number displayed to recipients of the phone call. The value should conform to the E164 format..</param> /// <param name="CallerIdName">The name displayed to recipients of the phone call..</param> public CallbackBasic(StateEnum? State = null, string Id = null, List<Segment> Segments = null, DirectionEnum? Direction = null, bool? Held = null, DisconnectTypeEnum? DisconnectType = null, DateTime? StartHoldTime = null, DialerPreview DialerPreview = null, Voicemail Voicemail = null, List<string> CallbackNumbers = null, string CallbackUserName = null, string ScriptId = null, bool? ExternalCampaign = null, bool? SkipEnabled = null, int? TimeoutSeconds = null, DateTime? StartAlertingTime = null, DateTime? ConnectedTime = null, DateTime? DisconnectedTime = null, DateTime? CallbackScheduledTime = null, string AutomatedCallbackConfigId = null, string Provider = null, string PeerId = null, Wrapup Wrapup = null, AfterCallWork AfterCallWork = null, bool? AfterCallWorkRequired = null, string CallerId = null, string CallerIdName = null) { this.State = State; this.Id = Id; this.Segments = Segments; this.Direction = Direction; this.Held = Held; this.DisconnectType = DisconnectType; this.StartHoldTime = StartHoldTime; this.DialerPreview = DialerPreview; this.Voicemail = Voicemail; this.CallbackNumbers = CallbackNumbers; this.CallbackUserName = CallbackUserName; this.ScriptId = ScriptId; this.ExternalCampaign = ExternalCampaign; this.SkipEnabled = SkipEnabled; this.TimeoutSeconds = TimeoutSeconds; this.StartAlertingTime = StartAlertingTime; this.ConnectedTime = ConnectedTime; this.DisconnectedTime = DisconnectedTime; this.CallbackScheduledTime = CallbackScheduledTime; this.AutomatedCallbackConfigId = AutomatedCallbackConfigId; this.Provider = Provider; this.PeerId = PeerId; this.Wrapup = Wrapup; this.AfterCallWork = AfterCallWork; this.AfterCallWorkRequired = AfterCallWorkRequired; this.CallerId = CallerId; this.CallerIdName = CallerIdName; } /// <summary> /// A globally unique identifier for this communication. /// </summary> /// <value>A globally unique identifier for this communication.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The time line of the participant&#39;s callback, divided into activity segments. /// </summary> /// <value>The time line of the participant&#39;s callback, divided into activity segments.</value> [DataMember(Name="segments", EmitDefaultValue=false)] public List<Segment> Segments { get; set; } /// <summary> /// True if this call is held and the person on this side hears silence. /// </summary> /// <value>True if this call is held and the person on this side hears silence.</value> [DataMember(Name="held", EmitDefaultValue=false)] public bool? Held { get; set; } /// <summary> /// The timestamp the callback was placed on hold in the cloud clock if the callback is currently on hold. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>The timestamp the callback was placed on hold in the cloud clock if the callback is currently on hold. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="startHoldTime", EmitDefaultValue=false)] public DateTime? StartHoldTime { get; set; } /// <summary> /// The preview data to be used when this callback is a Preview. /// </summary> /// <value>The preview data to be used when this callback is a Preview.</value> [DataMember(Name="dialerPreview", EmitDefaultValue=false)] public DialerPreview DialerPreview { get; set; } /// <summary> /// The voicemail data to be used when this callback is an ACD voicemail. /// </summary> /// <value>The voicemail data to be used when this callback is an ACD voicemail.</value> [DataMember(Name="voicemail", EmitDefaultValue=false)] public Voicemail Voicemail { get; set; } /// <summary> /// The phone number(s) to use to place the callback. /// </summary> /// <value>The phone number(s) to use to place the callback.</value> [DataMember(Name="callbackNumbers", EmitDefaultValue=false)] public List<string> CallbackNumbers { get; set; } /// <summary> /// The name of the user requesting a callback. /// </summary> /// <value>The name of the user requesting a callback.</value> [DataMember(Name="callbackUserName", EmitDefaultValue=false)] public string CallbackUserName { get; set; } /// <summary> /// The UUID of the script to use. /// </summary> /// <value>The UUID of the script to use.</value> [DataMember(Name="scriptId", EmitDefaultValue=false)] public string ScriptId { get; set; } /// <summary> /// True if the call for the callback uses external dialing. /// </summary> /// <value>True if the call for the callback uses external dialing.</value> [DataMember(Name="externalCampaign", EmitDefaultValue=false)] public bool? ExternalCampaign { get; set; } /// <summary> /// True if the ability to skip a callback should be enabled. /// </summary> /// <value>True if the ability to skip a callback should be enabled.</value> [DataMember(Name="skipEnabled", EmitDefaultValue=false)] public bool? SkipEnabled { get; set; } /// <summary> /// The number of seconds before the system automatically places a call for a callback. 0 means the automatic placement is disabled. /// </summary> /// <value>The number of seconds before the system automatically places a call for a callback. 0 means the automatic placement is disabled.</value> [DataMember(Name="timeoutSeconds", EmitDefaultValue=false)] public int? TimeoutSeconds { get; set; } /// <summary> /// The timestamp the communication has when it is first put into an alerting state. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>The timestamp the communication has when it is first put into an alerting state. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="startAlertingTime", EmitDefaultValue=false)] public DateTime? StartAlertingTime { get; set; } /// <summary> /// The timestamp when this communication was connected in the cloud clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>The timestamp when this communication was connected in the cloud clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="connectedTime", EmitDefaultValue=false)] public DateTime? ConnectedTime { get; set; } /// <summary> /// The timestamp when this communication disconnected from the conversation in the provider clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>The timestamp when this communication disconnected from the conversation in the provider clock. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="disconnectedTime", EmitDefaultValue=false)] public DateTime? DisconnectedTime { get; set; } /// <summary> /// The timestamp when this communication is scheduled in the provider clock. If this value is missing it indicates the callback will be placed immediately. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z /// </summary> /// <value>The timestamp when this communication is scheduled in the provider clock. If this value is missing it indicates the callback will be placed immediately. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value> [DataMember(Name="callbackScheduledTime", EmitDefaultValue=false)] public DateTime? CallbackScheduledTime { get; set; } /// <summary> /// The id of the config for automatically placing the callback (and handling the disposition). If null, the callback will not be placed automatically but routed to an agent as per normal. /// </summary> /// <value>The id of the config for automatically placing the callback (and handling the disposition). If null, the callback will not be placed automatically but routed to an agent as per normal.</value> [DataMember(Name="automatedCallbackConfigId", EmitDefaultValue=false)] public string AutomatedCallbackConfigId { get; set; } /// <summary> /// The source provider for the callback. /// </summary> /// <value>The source provider for the callback.</value> [DataMember(Name="provider", EmitDefaultValue=false)] public string Provider { get; set; } /// <summary> /// The id of the peer communication corresponding to a matching leg for this communication. /// </summary> /// <value>The id of the peer communication corresponding to a matching leg for this communication.</value> [DataMember(Name="peerId", EmitDefaultValue=false)] public string PeerId { get; set; } /// <summary> /// Call wrap up or disposition data. /// </summary> /// <value>Call wrap up or disposition data.</value> [DataMember(Name="wrapup", EmitDefaultValue=false)] public Wrapup Wrapup { get; set; } /// <summary> /// After-call work for the communication. /// </summary> /// <value>After-call work for the communication.</value> [DataMember(Name="afterCallWork", EmitDefaultValue=false)] public AfterCallWork AfterCallWork { get; set; } /// <summary> /// Indicates if after-call work is required for a communication. Only used when the ACW Setting is Agent Requested. /// </summary> /// <value>Indicates if after-call work is required for a communication. Only used when the ACW Setting is Agent Requested.</value> [DataMember(Name="afterCallWorkRequired", EmitDefaultValue=false)] public bool? AfterCallWorkRequired { get; set; } /// <summary> /// The phone number displayed to recipients of the phone call. The value should conform to the E164 format. /// </summary> /// <value>The phone number displayed to recipients of the phone call. The value should conform to the E164 format.</value> [DataMember(Name="callerId", EmitDefaultValue=false)] public string CallerId { get; set; } /// <summary> /// The name displayed to recipients of the phone call. /// </summary> /// <value>The name displayed to recipients of the phone call.</value> [DataMember(Name="callerIdName", EmitDefaultValue=false)] public string CallerIdName { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CallbackBasic {\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Segments: ").Append(Segments).Append("\n"); sb.Append(" Direction: ").Append(Direction).Append("\n"); sb.Append(" Held: ").Append(Held).Append("\n"); sb.Append(" DisconnectType: ").Append(DisconnectType).Append("\n"); sb.Append(" StartHoldTime: ").Append(StartHoldTime).Append("\n"); sb.Append(" DialerPreview: ").Append(DialerPreview).Append("\n"); sb.Append(" Voicemail: ").Append(Voicemail).Append("\n"); sb.Append(" CallbackNumbers: ").Append(CallbackNumbers).Append("\n"); sb.Append(" CallbackUserName: ").Append(CallbackUserName).Append("\n"); sb.Append(" ScriptId: ").Append(ScriptId).Append("\n"); sb.Append(" ExternalCampaign: ").Append(ExternalCampaign).Append("\n"); sb.Append(" SkipEnabled: ").Append(SkipEnabled).Append("\n"); sb.Append(" TimeoutSeconds: ").Append(TimeoutSeconds).Append("\n"); sb.Append(" StartAlertingTime: ").Append(StartAlertingTime).Append("\n"); sb.Append(" ConnectedTime: ").Append(ConnectedTime).Append("\n"); sb.Append(" DisconnectedTime: ").Append(DisconnectedTime).Append("\n"); sb.Append(" CallbackScheduledTime: ").Append(CallbackScheduledTime).Append("\n"); sb.Append(" AutomatedCallbackConfigId: ").Append(AutomatedCallbackConfigId).Append("\n"); sb.Append(" Provider: ").Append(Provider).Append("\n"); sb.Append(" PeerId: ").Append(PeerId).Append("\n"); sb.Append(" Wrapup: ").Append(Wrapup).Append("\n"); sb.Append(" AfterCallWork: ").Append(AfterCallWork).Append("\n"); sb.Append(" AfterCallWorkRequired: ").Append(AfterCallWorkRequired).Append("\n"); sb.Append(" CallerId: ").Append(CallerId).Append("\n"); sb.Append(" CallerIdName: ").Append(CallerIdName).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, Formatting = Formatting.Indented }); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CallbackBasic); } /// <summary> /// Returns true if CallbackBasic instances are equal /// </summary> /// <param name="other">Instance of CallbackBasic to be compared</param> /// <returns>Boolean</returns> public bool Equals(CallbackBasic other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Segments == other.Segments || this.Segments != null && this.Segments.SequenceEqual(other.Segments) ) && ( this.Direction == other.Direction || this.Direction != null && this.Direction.Equals(other.Direction) ) && ( this.Held == other.Held || this.Held != null && this.Held.Equals(other.Held) ) && ( this.DisconnectType == other.DisconnectType || this.DisconnectType != null && this.DisconnectType.Equals(other.DisconnectType) ) && ( this.StartHoldTime == other.StartHoldTime || this.StartHoldTime != null && this.StartHoldTime.Equals(other.StartHoldTime) ) && ( this.DialerPreview == other.DialerPreview || this.DialerPreview != null && this.DialerPreview.Equals(other.DialerPreview) ) && ( this.Voicemail == other.Voicemail || this.Voicemail != null && this.Voicemail.Equals(other.Voicemail) ) && ( this.CallbackNumbers == other.CallbackNumbers || this.CallbackNumbers != null && this.CallbackNumbers.SequenceEqual(other.CallbackNumbers) ) && ( this.CallbackUserName == other.CallbackUserName || this.CallbackUserName != null && this.CallbackUserName.Equals(other.CallbackUserName) ) && ( this.ScriptId == other.ScriptId || this.ScriptId != null && this.ScriptId.Equals(other.ScriptId) ) && ( this.ExternalCampaign == other.ExternalCampaign || this.ExternalCampaign != null && this.ExternalCampaign.Equals(other.ExternalCampaign) ) && ( this.SkipEnabled == other.SkipEnabled || this.SkipEnabled != null && this.SkipEnabled.Equals(other.SkipEnabled) ) && ( this.TimeoutSeconds == other.TimeoutSeconds || this.TimeoutSeconds != null && this.TimeoutSeconds.Equals(other.TimeoutSeconds) ) && ( this.StartAlertingTime == other.StartAlertingTime || this.StartAlertingTime != null && this.StartAlertingTime.Equals(other.StartAlertingTime) ) && ( this.ConnectedTime == other.ConnectedTime || this.ConnectedTime != null && this.ConnectedTime.Equals(other.ConnectedTime) ) && ( this.DisconnectedTime == other.DisconnectedTime || this.DisconnectedTime != null && this.DisconnectedTime.Equals(other.DisconnectedTime) ) && ( this.CallbackScheduledTime == other.CallbackScheduledTime || this.CallbackScheduledTime != null && this.CallbackScheduledTime.Equals(other.CallbackScheduledTime) ) && ( this.AutomatedCallbackConfigId == other.AutomatedCallbackConfigId || this.AutomatedCallbackConfigId != null && this.AutomatedCallbackConfigId.Equals(other.AutomatedCallbackConfigId) ) && ( this.Provider == other.Provider || this.Provider != null && this.Provider.Equals(other.Provider) ) && ( this.PeerId == other.PeerId || this.PeerId != null && this.PeerId.Equals(other.PeerId) ) && ( this.Wrapup == other.Wrapup || this.Wrapup != null && this.Wrapup.Equals(other.Wrapup) ) && ( this.AfterCallWork == other.AfterCallWork || this.AfterCallWork != null && this.AfterCallWork.Equals(other.AfterCallWork) ) && ( this.AfterCallWorkRequired == other.AfterCallWorkRequired || this.AfterCallWorkRequired != null && this.AfterCallWorkRequired.Equals(other.AfterCallWorkRequired) ) && ( this.CallerId == other.CallerId || this.CallerId != null && this.CallerId.Equals(other.CallerId) ) && ( this.CallerIdName == other.CallerIdName || this.CallerIdName != null && this.CallerIdName.Equals(other.CallerIdName) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Segments != null) hash = hash * 59 + this.Segments.GetHashCode(); if (this.Direction != null) hash = hash * 59 + this.Direction.GetHashCode(); if (this.Held != null) hash = hash * 59 + this.Held.GetHashCode(); if (this.DisconnectType != null) hash = hash * 59 + this.DisconnectType.GetHashCode(); if (this.StartHoldTime != null) hash = hash * 59 + this.StartHoldTime.GetHashCode(); if (this.DialerPreview != null) hash = hash * 59 + this.DialerPreview.GetHashCode(); if (this.Voicemail != null) hash = hash * 59 + this.Voicemail.GetHashCode(); if (this.CallbackNumbers != null) hash = hash * 59 + this.CallbackNumbers.GetHashCode(); if (this.CallbackUserName != null) hash = hash * 59 + this.CallbackUserName.GetHashCode(); if (this.ScriptId != null) hash = hash * 59 + this.ScriptId.GetHashCode(); if (this.ExternalCampaign != null) hash = hash * 59 + this.ExternalCampaign.GetHashCode(); if (this.SkipEnabled != null) hash = hash * 59 + this.SkipEnabled.GetHashCode(); if (this.TimeoutSeconds != null) hash = hash * 59 + this.TimeoutSeconds.GetHashCode(); if (this.StartAlertingTime != null) hash = hash * 59 + this.StartAlertingTime.GetHashCode(); if (this.ConnectedTime != null) hash = hash * 59 + this.ConnectedTime.GetHashCode(); if (this.DisconnectedTime != null) hash = hash * 59 + this.DisconnectedTime.GetHashCode(); if (this.CallbackScheduledTime != null) hash = hash * 59 + this.CallbackScheduledTime.GetHashCode(); if (this.AutomatedCallbackConfigId != null) hash = hash * 59 + this.AutomatedCallbackConfigId.GetHashCode(); if (this.Provider != null) hash = hash * 59 + this.Provider.GetHashCode(); if (this.PeerId != null) hash = hash * 59 + this.PeerId.GetHashCode(); if (this.Wrapup != null) hash = hash * 59 + this.Wrapup.GetHashCode(); if (this.AfterCallWork != null) hash = hash * 59 + this.AfterCallWork.GetHashCode(); if (this.AfterCallWorkRequired != null) hash = hash * 59 + this.AfterCallWorkRequired.GetHashCode(); if (this.CallerId != null) hash = hash * 59 + this.CallerId.GetHashCode(); if (this.CallerIdName != null) hash = hash * 59 + this.CallerIdName.GetHashCode(); return hash; } } } }
40.347518
847
0.527986
[ "MIT" ]
F-V-L/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/CallbackBasic.cs
39,823
C#
namespace Pandv.AriesDoc { public class DocConfig { public string RamlVersion { get; set; } public string StartupClassName { get; set; } public string BaseUrl { get; set; } public string DocDirectory { get; set; } public string PublishDllDirectory { get; set; } public bool IsRelativePath { get; set; } public string XmlCommentsFile { get; set; } } }
32.230769
55
0.620525
[ "MIT" ]
CodeBabyBear/AriesDoc
src/dotnet-aries-doc/DocConfig.cs
421
C#
/* * MIT License * * Copyright (c) Microsoft Corporation. * * 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.ComponentModel.DataAnnotations; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; #nullable enable namespace Microsoft.Playwright { public class RouteFulfillOptions { public RouteFulfillOptions() { } public RouteFulfillOptions(RouteFulfillOptions clone) { if (clone == null) return; Body = clone.Body; BodyBytes = clone.BodyBytes; ContentType = clone.ContentType; Headers = clone.Headers; Path = clone.Path; Status = clone.Status; } /// <summary><para>Optional response body as text.</para></summary> [JsonPropertyName("body")] public string? Body { get; set; } /// <summary><para>Optional response body as raw bytes.</para></summary> [JsonPropertyName("bodyBytes")] public byte[]? BodyBytes { get; set; } /// <summary><para>If set, equals to setting <c>Content-Type</c> response header.</para></summary> [JsonPropertyName("contentType")] public string? ContentType { get; set; } /// <summary><para>Response headers. Header values will be converted to a string.</para></summary> [JsonPropertyName("headers")] public IEnumerable<KeyValuePair<string, string>>? Headers { get; set; } /// <summary> /// <para> /// File path to respond with. The content type will be inferred from file extension. /// If <c>path</c> is a relative path, then it is resolved relative to the current working /// directory. /// </para> /// </summary> [JsonPropertyName("path")] public string? Path { get; set; } /// <summary><para>Response status code, defaults to <c>200</c>.</para></summary> [JsonPropertyName("status")] public int? Status { get; set; } } } #nullable disable
36.566667
106
0.674871
[ "MIT" ]
Archish27/playwright-dotnet
src/Playwright/API/Generated/Options/RouteFulfillOptions.cs
3,291
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Task1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Task1")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("E48CE94A-F6A7-4050-B8ED-C80AE94AB6D8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.371429
84
0.739389
[ "MIT" ]
mariiamk/CSharp2018-2019
1module/Sr_1/Task1/Properties/AssemblyInfo.cs
1,346
C#
/*---------------------------------------------------------------- Copyright (C) 2015 Senparc 文件名:TenPayV3InfoCollection.cs 文件功能描述:微信支付V3信息集合,Key为商户号(MchId) 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using Senparc.Weixin.Exceptions; namespace Senparc.Weixin.MP.TenPayLibV3 { /// <summary> /// 微信支付信息集合,Key为商户号(MchId) /// </summary> public class TenPayV3InfoCollection : Dictionary<string, TenPayV3Info> { /// <summary> /// 微信支付信息集合,Key为商户号(MchId) /// </summary> public static TenPayV3InfoCollection Data = new TenPayV3InfoCollection(); public TenPayV3InfoCollection() : base(StringComparer.OrdinalIgnoreCase) { } public new TenPayV3Info this[string key] { get { if (!ContainsKey(key)) { throw new WeixinException(string.Format("TenPayV3InfoCollection尚未注册Mch:{0}", key)); } return base[key]; } set { base[key] = value; } } /// <summary> /// 注册TenPayV3Info信息 /// </summary> /// <param name="tenPayV3Info"></param> public static void Register(TenPayV3Info tenPayV3Info) { Data[tenPayV3Info.MchId] = tenPayV3Info; } } }
26.666667
103
0.503947
[ "MIT" ]
rentianhua/surfboard
Source/Foundation/Wechat/Senparc.Weixin.MP/TenPayLibV3/TenPayV3InfoCollection.cs
1,690
C#
namespace GitHub { using GitHub.App_Start; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutomapperConfiguration.Initialize(); } } }
30.136364
70
0.675716
[ "MIT" ]
carlitosd19/GigHubNew
GitHub/Global.asax.cs
665
C#
using Abp.AutoMapper; using FuelWerx.Generic; using System; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; using System.Runtime.CompilerServices; namespace FuelWerx.Generic.Dto { [AutoMapTo(new System.Type[] { typeof(Address) })] public class AddressDto { public virtual string City { get; set; } public virtual string ContactName { get; set; } [ForeignKey("CountryId")] public CountryDto Country { get; set; } public virtual int CountryId { get; set; } [ForeignKey("CountryRegionId")] public CountryRegionDto CountryRegion { get; set; } public virtual int? CountryRegionId { get; set; } public virtual long Id { get; set; } public virtual bool IsActive { get; set; } public virtual double? Latitude { get; set; } public DbGeography Location { get; set; } public virtual double? Longitude { get; set; } public virtual long OwnerId { get; set; } public virtual string OwnerType { get; set; } public virtual string PostalCode { get; set; } public virtual string PrimaryAddress { get; set; } public virtual string SecondaryAddress { get; set; } public virtual int TenantId { get; set; } public virtual string Type { get; set; } public AddressDto() { } } }
11.338583
51
0.621528
[ "MIT" ]
zberg007/fuelwerx
src/FuelWerx.Application/Generic/Dto/AddressDto.cs
1,440
C#
namespace MoreChests.Models { using System.Collections.Generic; internal class ChestData : ChestConfig { public int Depth { get; set; } public string Description { get; set; } public HashSet<string> DisabledFeatures { get; set; } public string DisplayName { get; set; } public Dictionary<string, bool> FilterItems { get; set; } public int Frames { get; set; } public string Image { get; set; } public float OpenNearby { get; set; } public bool PlayerColor { get; set; } public bool PlayerConfig { get; set; } } }
33.888889
65
0.614754
[ "MIT" ]
ImJustMatt/ExpandedStorage
MoreChests/Models/ChestData.cs
612
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using DwollaV2; using DwollaV2.SerializableTypes; namespace dwolla.net.test { [TestClass] public class ContactsTest { public Contacts c = new Contacts(); [TestMethod] public void TestGet() { var result = c.Get(); Assert.IsInstanceOfType(result, typeof(List<Contact>)); } [TestMethod] public void TestNearby() { var result = c.Nearby(0, 0); Assert.IsInstanceOfType(result, typeof(List<UserNearby>)); } } }
19.896552
64
0.67591
[ "Unlicense" ]
501st-alpha1/dwolla.net-v2
dwolla.net.test/ContactsTest.cs
579
C#
using System.Windows.Automation; using TestStack.White.UIItems.Actions; namespace TestStack.White.UIItems.TableItems { public class TableRowHeader : UIItem { protected TableRowHeader() {} public TableRowHeader(AutomationElement automationElement, ActionListener actionListener) : base(automationElement, actionListener) {} } }
33.181818
143
0.745205
[ "Apache-2.0", "MIT" ]
JakeGinnivan/White
src/TestStack.White/UIItems/TableItems/TableRowHeader.cs
355
C#
using Microsoft.AspNetCore.Http; using System.Linq; namespace WalkingTec.Mvvm.Core.Extensions { public static class HttpContextExtention { /// <summary> /// 客户端 Ip 头 /// </summary> public const string REMOTE_IP_HEADER = "X-Forwarded-For"; public static string GetRemoteIpAddress(this HttpContext self) { var proxyIp = self.Request?.Headers?[REMOTE_IP_HEADER].FirstOrDefault(); if (!string.IsNullOrEmpty(proxyIp)) { return proxyIp; } else { return self.Connection.RemoteIpAddress.ToString(); } } } }
24.535714
84
0.558952
[ "MIT" ]
WolfyCoder/WalkingTec.Mvvm
src/WalkingTec.Mvvm.Core/Extensions/SystemExtensions/HttpContextExtention.cs
697
C#
// Decompiled with JetBrains decompiler // Type: HalconDotNet.HBarCode // Assembly: halcondotnetxl, Version=17.12.0.0, Culture=neutral, PublicKeyToken=4973bed59ddbf2b8 // MVID: 39799324-2494-4A83-8C57-2731D25BAE81 // Assembly location: C:\Program Files\MVTec\HALCON-17.12-Progress\bin\dotnet35\halcondotnetxl.dll using System; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; namespace HalconDotNet { /// <summary>Represents an instance of a bar code reader.</summary> [Serializable] public class HBarCode : HTool, ISerializable, ICloneable { [EditorBrowsable(EditorBrowsableState.Never)] public HBarCode() : base(HTool.UNDEF) { } [EditorBrowsable(EditorBrowsableState.Never)] public HBarCode(IntPtr handle) : base(handle) { } internal static int LoadNew(IntPtr proc, int parIndex, int err, out HBarCode obj) { obj = new HBarCode(HTool.UNDEF); return obj.Load(proc, parIndex, err); } internal static int LoadNew(IntPtr proc, int parIndex, int err, out HBarCode[] obj) { HTuple tuple; err = HTuple.LoadNew(proc, parIndex, err, out tuple); obj = new HBarCode[tuple.Length]; for (int index = 0; index < tuple.Length; ++index) obj[index] = new HBarCode(tuple[index].IP); return err; } /// <summary> /// Read a bar code model from a file and create a new model. /// Modified instance represents: Handle of the bar code model. /// </summary> /// <param name="fileName">Name of the bar code model file. Default: "bar_code_model.bcm"</param> public HBarCode(string fileName) { IntPtr proc = HalconAPI.PreCall(1988); HalconAPI.StoreS(proc, 0, fileName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Create a model of a bar code reader. /// Modified instance represents: Handle for using and accessing the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that can be adjusted for the bar code model. Default: []</param> /// <param name="genParamValue">Values of the generic parameters that can be adjusted for the bar code model. Default: []</param> public HBarCode(HTuple genParamName, HTuple genParamValue) { IntPtr proc = HalconAPI.PreCall(2001); HalconAPI.Store(proc, 0, genParamName); HalconAPI.Store(proc, 1, genParamValue); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(genParamName); HalconAPI.UnpinTuple(genParamValue); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Create a model of a bar code reader. /// Modified instance represents: Handle for using and accessing the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that can be adjusted for the bar code model. Default: []</param> /// <param name="genParamValue">Values of the generic parameters that can be adjusted for the bar code model. Default: []</param> public HBarCode(string genParamName, double genParamValue) { IntPtr proc = HalconAPI.PreCall(2001); HalconAPI.StoreS(proc, 0, genParamName); HalconAPI.StoreD(proc, 1, genParamValue); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { HSerializedItem hserializedItem = this.SerializeBarCodeModel(); byte[] numArray = (byte[])hserializedItem; hserializedItem.Dispose(); info.AddValue("data", (object)numArray, typeof(byte[])); } [EditorBrowsable(EditorBrowsableState.Never)] public HBarCode(SerializationInfo info, StreamingContext context) { HSerializedItem serializedItemHandle = new HSerializedItem((byte[])info.GetValue("data", typeof(byte[]))); this.DeserializeBarCodeModel(serializedItemHandle); serializedItemHandle.Dispose(); } public void Serialize(Stream stream) { this.SerializeBarCodeModel().Serialize(stream); } public static HBarCode Deserialize(Stream stream) { HBarCode hbarCode = new HBarCode(); hbarCode.DeserializeBarCodeModel(HSerializedItem.Deserialize(stream)); return hbarCode; } object ICloneable.Clone() { return (object)this.Clone(); } public HBarCode Clone() { HSerializedItem serializedItemHandle = this.SerializeBarCodeModel(); HBarCode hbarCode = new HBarCode(); hbarCode.DeserializeBarCodeModel(serializedItemHandle); serializedItemHandle.Dispose(); return hbarCode; } /// <summary> /// Deserialize a bar code model. /// Modified instance represents: Handle of the bar code model. /// </summary> /// <param name="serializedItemHandle">Handle of the serialized item.</param> public void DeserializeBarCodeModel(HSerializedItem serializedItemHandle) { this.Dispose(); IntPtr proc = HalconAPI.PreCall(1986); HalconAPI.Store(proc, 0, (HTool)serializedItemHandle); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); GC.KeepAlive((object)serializedItemHandle); } /// <summary> /// Serialize a bar code model. /// Instance represents: Handle of the bar code model. /// </summary> /// <returns>Handle of the serialized item.</returns> public HSerializedItem SerializeBarCodeModel() { IntPtr proc = HalconAPI.PreCall(1987); this.Store(proc, 0); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HSerializedItem hserializedItem; int procResult = HSerializedItem.LoadNew(proc, 0, err, out hserializedItem); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return hserializedItem; } /// <summary> /// Read a bar code model from a file and create a new model. /// Modified instance represents: Handle of the bar code model. /// </summary> /// <param name="fileName">Name of the bar code model file. Default: "bar_code_model.bcm"</param> public void ReadBarCodeModel(string fileName) { this.Dispose(); IntPtr proc = HalconAPI.PreCall(1988); HalconAPI.StoreS(proc, 0, fileName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Write a bar code model to a file. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="fileName">Name of the bar code model file. Default: "bar_code_model.bcm"</param> public void WriteBarCodeModel(string fileName) { IntPtr proc = HalconAPI.PreCall(1989); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, fileName); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Access iconic objects that were created during the search or decoding of bar code symbols. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="candidateHandle">Indicating the bar code results respectively candidates for which the data is required. Default: "all"</param> /// <param name="objectName">Name of the iconic object to return. Default: "candidate_regions"</param> /// <returns>Objects that are created as intermediate results during the detection or evaluation of bar codes.</returns> public HObject GetBarCodeObject(HTuple candidateHandle, string objectName) { IntPtr proc = HalconAPI.PreCall(1990); this.Store(proc, 0); HalconAPI.Store(proc, 1, candidateHandle); HalconAPI.StoreS(proc, 2, objectName); HalconAPI.InitOCT(proc, 1); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(candidateHandle); HObject hobject; int procResult = HObject.LoadNew(proc, 1, err, out hobject); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return hobject; } /// <summary> /// Access iconic objects that were created during the search or decoding of bar code symbols. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="candidateHandle">Indicating the bar code results respectively candidates for which the data is required. Default: "all"</param> /// <param name="objectName">Name of the iconic object to return. Default: "candidate_regions"</param> /// <returns>Objects that are created as intermediate results during the detection or evaluation of bar codes.</returns> public HObject GetBarCodeObject(string candidateHandle, string objectName) { IntPtr proc = HalconAPI.PreCall(1990); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, candidateHandle); HalconAPI.StoreS(proc, 2, objectName); HalconAPI.InitOCT(proc, 1); int err = HalconAPI.CallProcedure(proc); HObject hobject; int procResult = HObject.LoadNew(proc, 1, err, out hobject); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return hobject; } /// <summary> /// Get the alphanumerical results that were accumulated during the decoding of bar code symbols. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="candidateHandle">Indicating the bar code results respectively candidates for which the data is required. Default: "all"</param> /// <param name="resultName">Names of the resulting data to return. Default: "decoded_types"</param> /// <returns>List with the results.</returns> public HTuple GetBarCodeResult(HTuple candidateHandle, string resultName) { IntPtr proc = HalconAPI.PreCall(1991); this.Store(proc, 0); HalconAPI.Store(proc, 1, candidateHandle); HalconAPI.StoreS(proc, 2, resultName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(candidateHandle); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Get the alphanumerical results that were accumulated during the decoding of bar code symbols. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="candidateHandle">Indicating the bar code results respectively candidates for which the data is required. Default: "all"</param> /// <param name="resultName">Names of the resulting data to return. Default: "decoded_types"</param> /// <returns>List with the results.</returns> public HTuple GetBarCodeResult(string candidateHandle, string resultName) { IntPtr proc = HalconAPI.PreCall(1991); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, candidateHandle); HalconAPI.StoreS(proc, 2, resultName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Decode bar code symbols within a rectangle. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="image">Input image.</param> /// <param name="codeType">Type of the searched bar code. Default: "EAN-13"</param> /// <param name="row">Row index of the center. Default: 50.0</param> /// <param name="column">Column index of the center. Default: 100.0</param> /// <param name="phi">Orientation of rectangle in radians. Default: 0.0</param> /// <param name="length1">Half of the length of the rectangle along the reading direction of the bar code. Default: 200.0</param> /// <param name="length2">Half of the length of the rectangle perpendicular to the reading direction of the bar code. Default: 100.0</param> /// <returns>Data strings of all successfully decoded bar codes.</returns> public HTuple DecodeBarCodeRectangle2( HImage image, HTuple codeType, HTuple row, HTuple column, HTuple phi, HTuple length1, HTuple length2) { IntPtr proc = HalconAPI.PreCall(1992); this.Store(proc, 0); HalconAPI.Store(proc, 1, (HObjectBase)image); HalconAPI.Store(proc, 1, codeType); HalconAPI.Store(proc, 2, row); HalconAPI.Store(proc, 3, column); HalconAPI.Store(proc, 4, phi); HalconAPI.Store(proc, 5, length1); HalconAPI.Store(proc, 6, length2); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(codeType); HalconAPI.UnpinTuple(row); HalconAPI.UnpinTuple(column); HalconAPI.UnpinTuple(phi); HalconAPI.UnpinTuple(length1); HalconAPI.UnpinTuple(length2); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); GC.KeepAlive((object)image); return tuple; } /// <summary> /// Decode bar code symbols within a rectangle. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="image">Input image.</param> /// <param name="codeType">Type of the searched bar code. Default: "EAN-13"</param> /// <param name="row">Row index of the center. Default: 50.0</param> /// <param name="column">Column index of the center. Default: 100.0</param> /// <param name="phi">Orientation of rectangle in radians. Default: 0.0</param> /// <param name="length1">Half of the length of the rectangle along the reading direction of the bar code. Default: 200.0</param> /// <param name="length2">Half of the length of the rectangle perpendicular to the reading direction of the bar code. Default: 100.0</param> /// <returns>Data strings of all successfully decoded bar codes.</returns> public string DecodeBarCodeRectangle2( HImage image, string codeType, double row, double column, double phi, double length1, double length2) { IntPtr proc = HalconAPI.PreCall(1992); this.Store(proc, 0); HalconAPI.Store(proc, 1, (HObjectBase)image); HalconAPI.StoreS(proc, 1, codeType); HalconAPI.StoreD(proc, 2, row); HalconAPI.StoreD(proc, 3, column); HalconAPI.StoreD(proc, 4, phi); HalconAPI.StoreD(proc, 5, length1); HalconAPI.StoreD(proc, 6, length2); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); string stringValue; int procResult = HalconAPI.LoadS(proc, 0, err, out stringValue); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); GC.KeepAlive((object)image); return stringValue; } /// <summary> /// Detect and read bar code symbols in an image. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="image">Input image. If the image has a reduced domain, the barcode search is reduced to that domain. This usually reduces the runtime of the operator. However, if the barcode is not fully inside the domain, the barcode cannot be decoded correctly.</param> /// <param name="codeType">Type of the searched bar code. Default: "auto"</param> /// <param name="decodedDataStrings">Data strings of all successfully decoded bar codes.</param> /// <returns>Regions of the successfully decoded bar code symbols.</returns> public HRegion FindBarCode(HImage image, HTuple codeType, out HTuple decodedDataStrings) { IntPtr proc = HalconAPI.PreCall(1993); this.Store(proc, 0); HalconAPI.Store(proc, 1, (HObjectBase)image); HalconAPI.Store(proc, 1, codeType); HalconAPI.InitOCT(proc, 1); HalconAPI.InitOCT(proc, 0); int err1 = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(codeType); HRegion hregion; int err2 = HRegion.LoadNew(proc, 1, err1, out hregion); int procResult = HTuple.LoadNew(proc, 0, err2, out decodedDataStrings); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); GC.KeepAlive((object)image); return hregion; } /// <summary> /// Detect and read bar code symbols in an image. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="image">Input image. If the image has a reduced domain, the barcode search is reduced to that domain. This usually reduces the runtime of the operator. However, if the barcode is not fully inside the domain, the barcode cannot be decoded correctly.</param> /// <param name="codeType">Type of the searched bar code. Default: "auto"</param> /// <param name="decodedDataStrings">Data strings of all successfully decoded bar codes.</param> /// <returns>Regions of the successfully decoded bar code symbols.</returns> public HRegion FindBarCode(HImage image, string codeType, out string decodedDataStrings) { IntPtr proc = HalconAPI.PreCall(1993); this.Store(proc, 0); HalconAPI.Store(proc, 1, (HObjectBase)image); HalconAPI.StoreS(proc, 1, codeType); HalconAPI.InitOCT(proc, 1); HalconAPI.InitOCT(proc, 0); int err1 = HalconAPI.CallProcedure(proc); HRegion hregion; int err2 = HRegion.LoadNew(proc, 1, err1, out hregion); int procResult = HalconAPI.LoadS(proc, 0, err2, out decodedDataStrings); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); GC.KeepAlive((object)image); return hregion; } /// <summary> /// Get the names of the parameters that can be used in set_bar_code* and get_bar_code* operators for a given bar code model /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="properties">Properties of the parameters. Default: "trained_general"</param> /// <returns>Names of the generic parameters.</returns> public HTuple QueryBarCodeParams(string properties) { IntPtr proc = HalconAPI.PreCall(1994); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, properties); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Get parameters that are used by the bar code reader when processing a specific bar code type. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="codeTypes">Names of the bar code types for which parameters should be queried. Default: "EAN-13"</param> /// <param name="genParamName">Names of the generic parameters that are to be queried for the bar code model. Default: "check_char"</param> /// <returns>Values of the generic parameters.</returns> public HTuple GetBarCodeParamSpecific(HTuple codeTypes, HTuple genParamName) { IntPtr proc = HalconAPI.PreCall(1995); this.Store(proc, 0); HalconAPI.Store(proc, 1, codeTypes); HalconAPI.Store(proc, 2, genParamName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(codeTypes); HalconAPI.UnpinTuple(genParamName); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Get parameters that are used by the bar code reader when processing a specific bar code type. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="codeTypes">Names of the bar code types for which parameters should be queried. Default: "EAN-13"</param> /// <param name="genParamName">Names of the generic parameters that are to be queried for the bar code model. Default: "check_char"</param> /// <returns>Values of the generic parameters.</returns> public HTuple GetBarCodeParamSpecific(string codeTypes, string genParamName) { IntPtr proc = HalconAPI.PreCall(1995); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, codeTypes); HalconAPI.StoreS(proc, 2, genParamName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Get one or several parameters that describe the bar code model. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that are to be queried for the bar code model. Default: "element_size_min"</param> /// <returns>Values of the generic parameters.</returns> public HTuple GetBarCodeParam(HTuple genParamName) { IntPtr proc = HalconAPI.PreCall(1996); this.Store(proc, 0); HalconAPI.Store(proc, 1, genParamName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(genParamName); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Get one or several parameters that describe the bar code model. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that are to be queried for the bar code model. Default: "element_size_min"</param> /// <returns>Values of the generic parameters.</returns> public HTuple GetBarCodeParam(string genParamName) { IntPtr proc = HalconAPI.PreCall(1996); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, genParamName); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HTuple tuple; int procResult = HTuple.LoadNew(proc, 0, err, out tuple); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); return tuple; } /// <summary> /// Set selected parameters of the bar code model for selected bar code types /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="codeTypes">Names of the bar code types for which parameters should be set. Default: "EAN-13"</param> /// <param name="genParamName">Names of the generic parameters that shall be adjusted for finding and decoding bar codes. Default: "check_char"</param> /// <param name="genParamValue">Values of the generic parameters that are adjusted for finding and decoding bar codes. Default: "absent"</param> public void SetBarCodeParamSpecific( HTuple codeTypes, HTuple genParamName, HTuple genParamValue) { IntPtr proc = HalconAPI.PreCall(1997); this.Store(proc, 0); HalconAPI.Store(proc, 1, codeTypes); HalconAPI.Store(proc, 2, genParamName); HalconAPI.Store(proc, 3, genParamValue); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(codeTypes); HalconAPI.UnpinTuple(genParamName); HalconAPI.UnpinTuple(genParamValue); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Set selected parameters of the bar code model for selected bar code types /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="codeTypes">Names of the bar code types for which parameters should be set. Default: "EAN-13"</param> /// <param name="genParamName">Names of the generic parameters that shall be adjusted for finding and decoding bar codes. Default: "check_char"</param> /// <param name="genParamValue">Values of the generic parameters that are adjusted for finding and decoding bar codes. Default: "absent"</param> public void SetBarCodeParamSpecific( string codeTypes, string genParamName, HTuple genParamValue) { IntPtr proc = HalconAPI.PreCall(1997); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, codeTypes); HalconAPI.StoreS(proc, 2, genParamName); HalconAPI.Store(proc, 3, genParamValue); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(genParamValue); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Set selected parameters of the bar code model. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that shall be adjusted for finding and decoding bar codes. Default: "element_size_min"</param> /// <param name="genParamValue">Values of the generic parameters that are adjusted for finding and decoding bar codes. Default: 8</param> public void SetBarCodeParam(HTuple genParamName, HTuple genParamValue) { IntPtr proc = HalconAPI.PreCall(1998); this.Store(proc, 0); HalconAPI.Store(proc, 1, genParamName); HalconAPI.Store(proc, 2, genParamValue); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(genParamName); HalconAPI.UnpinTuple(genParamValue); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Set selected parameters of the bar code model. /// Instance represents: Handle of the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that shall be adjusted for finding and decoding bar codes. Default: "element_size_min"</param> /// <param name="genParamValue">Values of the generic parameters that are adjusted for finding and decoding bar codes. Default: 8</param> public void SetBarCodeParam(string genParamName, double genParamValue) { IntPtr proc = HalconAPI.PreCall(1998); this.Store(proc, 0); HalconAPI.StoreS(proc, 1, genParamName); HalconAPI.StoreD(proc, 2, genParamValue); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Create a model of a bar code reader. /// Modified instance represents: Handle for using and accessing the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that can be adjusted for the bar code model. Default: []</param> /// <param name="genParamValue">Values of the generic parameters that can be adjusted for the bar code model. Default: []</param> public void CreateBarCodeModel(HTuple genParamName, HTuple genParamValue) { this.Dispose(); IntPtr proc = HalconAPI.PreCall(2001); HalconAPI.Store(proc, 0, genParamName); HalconAPI.Store(proc, 1, genParamValue); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); HalconAPI.UnpinTuple(genParamName); HalconAPI.UnpinTuple(genParamValue); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } /// <summary> /// Create a model of a bar code reader. /// Modified instance represents: Handle for using and accessing the bar code model. /// </summary> /// <param name="genParamName">Names of the generic parameters that can be adjusted for the bar code model. Default: []</param> /// <param name="genParamValue">Values of the generic parameters that can be adjusted for the bar code model. Default: []</param> public void CreateBarCodeModel(string genParamName, double genParamValue) { this.Dispose(); IntPtr proc = HalconAPI.PreCall(2001); HalconAPI.StoreS(proc, 0, genParamName); HalconAPI.StoreD(proc, 1, genParamValue); HalconAPI.InitOCT(proc, 0); int err = HalconAPI.CallProcedure(proc); int procResult = this.Load(proc, 0, err); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } protected override void ClearHandleResource() { IntPtr proc = HalconAPI.PreCall(2000); this.Store(proc, 0); int procResult = HalconAPI.CallProcedure(proc); HalconAPI.PostCall(proc, procResult); GC.KeepAlive((object)this); } } }
48.083824
280
0.610637
[ "Apache-2.0" ]
archerkyd/OpenHalcon
HalconDotNet/HalconDotNet/HBarCode.cs
32,699
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.RazorPages; namespace MyAnimeWorld.App.Areas.Identity.Pages.Account { [AllowAnonymous] public class LockoutModel : PageModel { public void OnGet() { } } }
19.368421
55
0.717391
[ "MIT" ]
kirrcho/Project
MyAnimeWorld.App/Areas/Identity/Pages/Account/Lockout.cshtml.cs
370
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CodeFirstDotNetCore.Models { public class Student { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string CreationUser { get; set; } public DateTime CreationDateTime { get; set; } public string LastUpdateUser { get; set; } public DateTime LastModifiedDateTime { get; set; } } }
25.95
58
0.655106
[ "MIT" ]
shahedbd/CodeFirstASPDotNetCore
Sln.CodeFirstDotNetCore/CodeFirstDotNetCore/Models/Student.cs
521
C#
using System; using System.IO; using System.Text; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Crypto.Generators { /** * Password hashing scheme BCrypt, * designed by Niels Provos and David Mazières, using the * String format and the Base64 encoding * of the reference implementation on OpenBSD */ public class OpenBsdBCrypt { private static readonly byte[] EncodingTable = // the Bcrypts encoding table for OpenBSD { (byte)'.', (byte)'/', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9' }; /* * set up the decoding table. */ private static readonly byte[] DecodingTable = new byte[128]; private static readonly string DefaultVersion = "2y"; private static readonly ISet AllowedVersions = new HashSet(); static OpenBsdBCrypt() { // Presently just the Bcrypt versions. AllowedVersions.Add("2a"); AllowedVersions.Add("2y"); AllowedVersions.Add("2b"); for (int i = 0; i < DecodingTable.Length; i++) { DecodingTable[i] = (byte)0xff; } for (int i = 0; i < EncodingTable.Length; i++) { DecodingTable[EncodingTable[i]] = (byte)i; } } public OpenBsdBCrypt() { } /** * Creates a 60 character Bcrypt String, including * version, cost factor, salt and hash, separated by '$' * * @param version the version, 2y,2b or 2a. (2a is not backwards compatible.) * @param cost the cost factor, treated as an exponent of 2 * @param salt a 16 byte salt * @param password the password * @return a 60 character Bcrypt String */ private static string CreateBcryptString(string version, byte[] password, byte[] salt, int cost) { if (!AllowedVersions.Contains(version)) throw new ArgumentException("Version " + version + " is not accepted by this implementation.", "version"); StringBuilder sb = new StringBuilder(60); sb.Append('$'); sb.Append(version); sb.Append('$'); sb.Append(cost < 10 ? ("0" + cost) : cost.ToString()); sb.Append('$'); sb.Append(EncodeData(salt)); byte[] key = BCrypt.Generate(password, salt, cost); sb.Append(EncodeData(key)); return sb.ToString(); } /** * Creates a 60 character Bcrypt String, including * version, cost factor, salt and hash, separated by '$' using version * '2y'. * * @param cost the cost factor, treated as an exponent of 2 * @param salt a 16 byte salt * @param password the password * @return a 60 character Bcrypt String */ public static string Generate(char[] password, byte[] salt, int cost) { return Generate(DefaultVersion, password, salt, cost); } /** * Creates a 60 character Bcrypt String, including * version, cost factor, salt and hash, separated by '$' * * @param version the version, may be 2b, 2y or 2a. (2a is not backwards compatible.) * @param cost the cost factor, treated as an exponent of 2 * @param salt a 16 byte salt * @param password the password * @return a 60 character Bcrypt String */ public static string Generate(string version, char[] password, byte[] salt, int cost) { if (!AllowedVersions.Contains(version)) throw new ArgumentException("Version " + version + " is not accepted by this implementation.", "version"); if (password == null) throw new ArgumentNullException("password"); if (salt == null) throw new ArgumentNullException("salt"); if (salt.Length != 16) throw new DataLengthException("16 byte salt required: " + salt.Length); if (cost < 4 || cost > 31) // Minimum rounds: 16, maximum 2^31 throw new ArgumentException("Invalid cost factor.", "cost"); byte[] psw = Strings.ToUtf8ByteArray(password); // 0 termination: byte[] tmp = new byte[psw.Length >= 72 ? 72 : psw.Length + 1]; int copyLen = System.Math.Min(psw.Length, tmp.Length); Array.Copy(psw, 0, tmp, 0, copyLen); Array.Clear(psw, 0, psw.Length); string rv = CreateBcryptString(version, tmp, salt, cost); Array.Clear(tmp, 0, tmp.Length); return rv; } /** * Checks if a password corresponds to a 60 character Bcrypt String * * @param bcryptString a 60 character Bcrypt String, including * version, cost factor, salt and hash, * separated by '$' * @param password the password as an array of chars * @return true if the password corresponds to the * Bcrypt String, otherwise false */ public static bool CheckPassword(string bcryptString, char[] password) { // validate bcryptString: if (bcryptString.Length != 60) throw new DataLengthException("Bcrypt String length: " + bcryptString.Length + ", 60 required."); if (bcryptString[0] != '$' || bcryptString[3] != '$' || bcryptString[6] != '$') throw new ArgumentException("Invalid Bcrypt String format.", "bcryptString"); string version = bcryptString.Substring(1, 2); if (!AllowedVersions.Contains(version)) throw new ArgumentException("Bcrypt version '" + version + "' is not supported by this implementation", "bcryptString"); int cost = 0; try { cost = Int32.Parse(bcryptString.Substring(4, 2)); } catch (Exception nfe) { throw new ArgumentException("Invalid cost factor: " + bcryptString.Substring(4, 2), "bcryptString", nfe); } if (cost < 4 || cost > 31) throw new ArgumentException("Invalid cost factor: " + cost + ", 4 < cost < 31 expected."); // check password: if (password == null) throw new ArgumentNullException("Missing password."); int start = bcryptString.LastIndexOf('$') + 1, end = bcryptString.Length - 31; byte[] salt = DecodeSaltString(bcryptString.Substring(start, end - start)); string newBcryptString = Generate(version, password, salt, cost); return bcryptString.Equals(newBcryptString); } /* * encode the input data producing a Bcrypt base 64 string. * * @param a byte representation of the salt or the password * @return the Bcrypt base64 string */ private static string EncodeData(byte[] data) { if (data.Length != 24 && data.Length != 16) // 192 bit key or 128 bit salt expected throw new DataLengthException("Invalid length: " + data.Length + ", 24 for key or 16 for salt expected"); bool salt = false; if (data.Length == 16)//salt { salt = true; byte[] tmp = new byte[18];// zero padding Array.Copy(data, 0, tmp, 0, data.Length); data = tmp; } else // key { data[data.Length - 1] = (byte)0; } MemoryStream mOut = new MemoryStream(); int len = data.Length; uint a1, a2, a3; int i; for (i = 0; i < len; i += 3) { a1 = data[i]; a2 = data[i + 1]; a3 = data[i + 2]; mOut.WriteByte(EncodingTable[(a1 >> 2) & 0x3f]); mOut.WriteByte(EncodingTable[((a1 << 4) | (a2 >> 4)) & 0x3f]); mOut.WriteByte(EncodingTable[((a2 << 2) | (a3 >> 6)) & 0x3f]); mOut.WriteByte(EncodingTable[a3 & 0x3f]); } string result = Strings.FromByteArray(mOut.ToArray()); int resultLen = salt ? 22 // truncate padding : result.Length - 1; return result.Substring(0, resultLen); } /* * decodes the bcrypt base 64 encoded SaltString * * @param a 22 character Bcrypt base 64 encoded String * @return the 16 byte salt * @exception DataLengthException if the length * of parameter is not 22 * @exception InvalidArgumentException if the parameter * contains a value other than from Bcrypts base 64 encoding table */ private static byte[] DecodeSaltString(string saltString) { char[] saltChars = saltString.ToCharArray(); MemoryStream mOut = new MemoryStream(16); byte b1, b2, b3, b4; if (saltChars.Length != 22)// bcrypt salt must be 22 (16 bytes) throw new DataLengthException("Invalid base64 salt length: " + saltChars.Length + " , 22 required."); // check string for invalid characters: for (int i = 0; i < saltChars.Length; i++) { int value = saltChars[i]; if (value > 122 || value < 46 || (value > 57 && value < 65)) throw new ArgumentException("Salt string contains invalid character: " + value, "saltString"); } // Padding: add two '\u0000' char[] tmp = new char[22 + 2]; Array.Copy(saltChars, 0, tmp, 0, saltChars.Length); saltChars = tmp; int len = saltChars.Length; for (int i = 0; i < len; i += 4) { b1 = DecodingTable[saltChars[i]]; b2 = DecodingTable[saltChars[i + 1]]; b3 = DecodingTable[saltChars[i + 2]]; b4 = DecodingTable[saltChars[i + 3]]; mOut.WriteByte((byte)((b1 << 2) | (b2 >> 4))); mOut.WriteByte((byte)((b2 << 4) | (b3 >> 2))); mOut.WriteByte((byte)((b3 << 6) | b4)); } byte[] saltBytes = mOut.ToArray(); // truncate: byte[] tmpSalt = new byte[16]; Array.Copy(saltBytes, 0, tmpSalt, 0, tmpSalt.Length); saltBytes = tmpSalt; return saltBytes; } } }
38.390728
136
0.519752
[ "MIT" ]
alextolp/bc-csharp
crypto/src/crypto/generators/OpenBsdBCrypt.cs
11,597
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace Wanghzh.Prism { public static class CollectionExtensions { public static Collection<T> AddRange<T>(this Collection<T> collection, IEnumerable<T> items) { if (collection == null) throw new System.ArgumentNullException("collection"); if (items == null) throw new System.ArgumentNullException("items"); foreach (var each in items) { collection.Add(each); } return collection; } } }
30.789474
100
0.615385
[ "CC0-1.0" ]
598235031/Prism
Prism/CollectionExtensions.cs
585
C#
using System; using HttpReports; using HttpReports.Dashboard; using HttpReports.Dashboard.Implements; using HttpReports.Dashboard.Services; using HttpReports.Dashboard.Services.Language; using HttpReports.Dashboard.Services.Quartz; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Options; using Quartz.Spi; namespace Microsoft.Extensions.DependencyInjection { public static class DependencyInjectionExtensions { public static IHttpReportsBuilder AddHttpReportsDashboard(this IServiceCollection services) { IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>().GetSection("HttpReportsDashboard"); services.AddOptions(); services.Configure<DashboardOptions>(configuration); return services.UseHttpReportsDashboardService(configuration); } public static IHttpReportsBuilder AddHttpReportsDashboard(this IServiceCollection services,Action<DashboardOptions> options) { IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>().GetSection("HttpReportsDashboard"); services.AddOptions(); services.Configure<DashboardOptions>(options); return services.UseHttpReportsDashboardService(configuration); } private static IHttpReportsBuilder UseHttpReportsDashboardService(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton<IModelCreator, DefaultModelCreator>(); services.AddSingleton<IAlarmService, AlarmService>(); services.AddSingleton<MonitorService>(); services.AddSingleton<ScheduleService>(); services.AddSingleton<ChineseLanguage>(); services.AddSingleton<EnglishLanguage>(); services.AddSingleton<LanguageService>(); services.AddMvcCore(x => { x.Filters.Add<GlobalAuthorizeFilter>(); }).AddViews(); ServiceContainer.provider = services.BuildServiceProvider(); return new HttpReportsBuilder(services, configuration); } public static IApplicationBuilder UseHttpReportsDashboard(this IApplicationBuilder app) { //ServiceContainer.provider = app.ApplicationServices as ServiceProvider; ConfigRoute(app); ConfigStaticFiles(app); var storage = app.ApplicationServices.GetRequiredService<IHttpReportsStorage>() ?? throw new ArgumentNullException("未正确配置存储方式"); storage.InitAsync().Wait(); app.ApplicationServices.GetService<ScheduleService>().InitAsync().Wait(); return app; } /// <summary> /// Add access to static resources on debug mode /// </summary> /// <param name="app"></param> private static void ConfigStaticFiles(IApplicationBuilder app) { if (System.IO.Directory.Exists(System.IO.Path.Combine(AppContext.BaseDirectory, @"wwwroot\HttpReportsStaticFiles"))) { app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(System.IO.Path.Combine(AppContext.BaseDirectory, @"wwwroot\HttpReportsStaticFiles")), RequestPath = new Microsoft.AspNetCore.Http.PathString("/HttpReportsStaticFiles") }); } } /// <summary> /// Configure user routing /// </summary> /// <param name="UseHome"></param> /// <param name="app"></param> private static void ConfigRoute(IApplicationBuilder app) { var options = app.ApplicationServices.GetRequiredService<IOptions<DashboardOptions>>().Value; app.Use(async (context, next) => { if (context.Request.Path.HasValue) { if (context.Request.Path.Value.ToLower() == (options.UseHome ? "/" : "dashboard")) { context.Request.Path = "/HttpReports"; } } await next(); }); } } }
34.007752
145
0.636426
[ "MIT" ]
fawdlstty/HttpReports
src/HttpReports.Dashboard/DependencyInjectionExtensions.cs
4,407
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472) // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Represents a ribbon group text box. /// </summary> [ToolboxItem(false)] [ToolboxBitmap(typeof(KryptonRibbonGroupTextBox), "ToolboxBitmaps.KryptonRibbonGroupTextBox.bmp")] [Designer(typeof(ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTextBoxDesigner))] [DesignerCategory("code")] [DesignTimeVisible(false)] [DefaultEvent("TextChanged")] [DefaultProperty("Text")] public class KryptonRibbonGroupTextBox : KryptonRibbonGroupItem { #region Instance Fields private bool _visible; private bool _enabled; private string _keyTip; private GroupItemSize _itemSizeCurrent; #endregion #region Events /// <summary> /// Occurs when the value of the Text property changes. /// </summary> [Description("Occurs when the value of the Text property changes.")] [Category("Property Changed")] public event EventHandler TextChanged; /// <summary> /// Occurs when the control receives focus. /// </summary> [Browsable(false)] public event EventHandler GotFocus; /// <summary> /// Occurs when the control loses focus. /// </summary> [Browsable(false)] public event EventHandler LostFocus; /// <summary> /// Occurs when a key is pressed while the control has focus. /// </summary> [Description("Occurs when a key is pressed while the control has focus.")] [Category("Key")] public event KeyPressEventHandler KeyPress; /// <summary> /// Occurs when a key is released while the control has focus. /// </summary> [Description("Occurs when a key is released while the control has focus.")] [Category("Key")] public event KeyEventHandler KeyUp; /// <summary> /// Occurs when a key is pressed while the control has focus. /// </summary> [Description("Occurs when a key is pressed while the control has focus.")] [Category("Key")] public event KeyEventHandler KeyDown; /// <summary> /// Occurs before the KeyDown event when a key is pressed while focus is on this control. /// </summary> [Description("Occurs before the KeyDown event when a key is pressed while focus is on this control.")] [Category("Key")] public event PreviewKeyDownEventHandler PreviewKeyDown; /// <summary> /// Occurs when the value of the AcceptsTab property changes. /// </summary> [Description("Occurs when the value of the AcceptsTab property changes.")] [Category("Property Changed")] public event EventHandler AcceptsTabChanged; /// <summary> /// Occurs when the value of the HideSelection property changes. /// </summary> [Description("Occurs when the value of the HideSelection property changes.")] [Category("Property Changed")] public event EventHandler HideSelectionChanged; /// <summary> /// Occurs when the value of the TextAlign property changes. /// </summary> [Description("Occurs when the value of the TextAlign property changes.")] [Category("Property Changed")] public event EventHandler TextAlignChanged; /// <summary> /// Occurs when the value of the Modified property changes. /// </summary> [Description("Occurs when the value of the Modified property changes.")] [Category("Property Changed")] public event EventHandler ModifiedChanged; /// <summary> /// Occurs when the value of the Multiline property changes. /// </summary> [Description("Occurs when the value of the Multiline property changes.")] [Category("Property Changed")] public event EventHandler MultilineChanged; /// <summary> /// Occurs when the value of the ReadOnly property changes. /// </summary> [Description("Occurs when the value of the ReadOnly property changes.")] [Category("Property Changed")] public event EventHandler ReadOnlyChanged; /// <summary> /// Occurs after the value of a property has changed. /// </summary> [Category("Ribbon")] [Description("Occurs after the value of a property has changed.")] public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when the design time context menu is requested. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public event MouseEventHandler DesignTimeContextMenu; internal event EventHandler MouseEnterControl; internal event EventHandler MouseLeaveControl; #endregion #region Identity /// <summary> /// Initialise a new instance of the KryptonRibbonGroupTextBox class. /// </summary> public KryptonRibbonGroupTextBox() { // Default fields _visible = true; _enabled = true; _itemSizeCurrent = GroupItemSize.Medium; ShortcutKeys = Keys.None; _keyTip = "X"; // Create the actual text box control and set initial settings TextBox = new KryptonTextBox { InputControlStyle = InputControlStyle.Ribbon, AlwaysActive = false, MinimumSize = new Size(121, 0), MaximumSize = new Size(121, 0), TabStop = false }; // Hook into events to expose via this container TextBox.AcceptsTabChanged += OnTextBoxAcceptsTabChanged; TextBox.TextAlignChanged += OnTextBoxTextAlignChanged; TextBox.TextChanged += OnTextBoxTextChanged; TextBox.HideSelectionChanged += OnTextBoxHideSelectionChanged; TextBox.ModifiedChanged += OnTextBoxModifiedChanged; TextBox.MultilineChanged += OnTextBoxMultilineChanged; TextBox.ReadOnlyChanged += OnTextBoxReadOnlyChanged; TextBox.GotFocus += OnTextBoxGotFocus; TextBox.LostFocus += OnTextBoxLostFocus; TextBox.KeyDown += OnTextBoxKeyDown; TextBox.KeyUp += OnTextBoxKeyUp; TextBox.KeyPress += OnTextBoxKeyPress; TextBox.PreviewKeyDown += OnTextBoxPreviewKeyDown; // Ensure we can track mouse events on the text box MonitorControl(TextBox); } /// <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) { if (TextBox != null) { UnmonitorControl(TextBox); TextBox.Dispose(); TextBox = null; } } base.Dispose(disposing); } #endregion #region Public /// <summary> /// Gets access to the owning ribbon control. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override KryptonRibbon Ribbon { set { base.Ribbon = value; if (value != null) { // Use the same palette in the text box as the ribbon, plus we need // to know when the ribbon palette changes so we can reflect that change TextBox.Palette = Ribbon.GetResolvedPalette(); Ribbon.PaletteChanged += OnRibbonPaletteChanged; } } } /// <summary> /// Gets and sets the shortcut key combination. /// </summary> [Localizable(true)] [Category("Behavior")] [Description("Shortcut key combination to set focus to the text box.")] public Keys ShortcutKeys { get; set; } private bool ShouldSerializeShortcutKeys() { return (ShortcutKeys != Keys.None); } /// <summary> /// Resets the ShortcutKeys property to its default value. /// </summary> public void ResetShortcutKeys() { ShortcutKeys = Keys.None; } /// <summary> /// Access to the actual embedded KryptonTextBox instance. /// </summary> [Description("Access to the actual embedded KryptonTextBox instance.")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public KryptonTextBox TextBox { get; private set; } /// <summary> /// Gets and sets the key tip for the ribbon group text box. /// </summary> [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("Ribbon group text box key tip.")] [DefaultValue("X")] public string KeyTip { get => _keyTip; set { if (string.IsNullOrEmpty(value)) { value = "X"; } _keyTip = value.ToUpper(); } } /// <summary> /// Gets and sets the visible state of the text box. /// </summary> [Bindable(true)] [Category("Behavior")] [Description("Determines whether the text box is visible or hidden.")] [DefaultValue(true)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override bool Visible { get => _visible; set { if (value != _visible) { _visible = value; OnPropertyChanged("Visible"); } } } /// <summary> /// Make the ribbon group textbox visible. /// </summary> public void Show() { Visible = true; } /// <summary> /// Make the ribbon group textbox hidden. /// </summary> public void Hide() { Visible = false; } /// <summary> /// Gets and sets the enabled state of the group text box. /// </summary> [Bindable(true)] [Category("Behavior")] [Description("Determines whether the group text box is enabled.")] [DefaultValue(true)] public bool Enabled { get => _enabled; set { if (_enabled != value) { _enabled = value; OnPropertyChanged("Enabled"); } } } /// <summary> /// Gets or sets the minimum size of the control. /// </summary> [Category("Layout")] [Description("Specifies the minimum size of the control.")] [DefaultValue(typeof(Size), "121, 0")] public Size MinimumSize { get => TextBox.MinimumSize; set => TextBox.MinimumSize = value; } /// <summary> /// Gets or sets the maximum size of the control. /// </summary> [Category("Layout")] [Description("Specifies the maximum size of the control.")] [DefaultValue(typeof(Size), "121, 0")] public Size MaximumSize { get => TextBox.MaximumSize; set => TextBox.MaximumSize = value; } /// <summary> /// Gets and sets the text associated with the control. /// </summary> [Category("Appearance")] [Description("Text associated with the control.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] public string Text { get => TextBox.Text; set => TextBox.Text = value; } /// <summary> /// Gets or sets the lines of text in a multiline edit, as an array of String values. /// </summary> [Category("Appearance")] [Description("The lines of text in a multiline edit, as an array of String values.")] [Editor("System.Windows.Forms.Design.StringArrayEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [MergableProperty(false)] [Localizable(true)] public string[] Lines { get => TextBox.Lines; set => TextBox.Lines = value; } /// <summary> /// Gets or sets, for multiline edit controls, which scroll bars will be shown for this control. /// </summary> [Category("Appearance")] [Description("Indicates, for multiline edit controls, which scroll bars will be shown for this control.")] [DefaultValue(typeof(ScrollBars), "None")] [Localizable(true)] public ScrollBars ScrollBars { get => TextBox.ScrollBars; set => TextBox.ScrollBars = value; } /// <summary> /// Gets or sets how the text should be aligned for edit controls. /// </summary> [Category("Appearance")] [Description("Indicates how the text should be aligned for edit controls.")] [DefaultValue(typeof(HorizontalAlignment), "Left")] [Localizable(true)] public HorizontalAlignment TextAlign { get => TextBox.TextAlign; set => TextBox.TextAlign = value; } /// <summary> /// Gets and sets the associated context menu strip. /// </summary> [Category("Behavior")] [Description("The shortcut to display when the user right-clicks the control.")] [DefaultValue(null)] public ContextMenuStrip ContextMenuStrip { get => TextBox.ContextMenuStrip; set => TextBox.ContextMenuStrip = value; } /// <summary> /// Gets and sets the KryptonContextMenu for showing when the text box is right clicked. /// </summary> [Category("Behavior")] [Description("KryptonContextMenu to be shown when the text box is right clicked.")] [DefaultValue(null)] public KryptonContextMenu KryptonContextMenu { get => TextBox.KryptonContextMenu; set => TextBox.KryptonContextMenu = value; } /// <summary> /// Indicates if lines are automatically word-wrapped for multiline edit controls. /// </summary> [Category("Behavior")] [Description("Indicates if lines are automatically word-wrapped for multiline edit controls.")] [DefaultValue(true)] [Localizable(true)] public bool WordWrap { get => TextBox.WordWrap; set => TextBox.WordWrap = value; } /// <summary> /// Gets and sets whether the text in the control can span more than one line. /// </summary> [Category("Behavior")] [Description("Control whether the text in the control can span more than one line.")] [RefreshProperties(RefreshProperties.All)] [DefaultValue(false)] [Localizable(true)] public bool Multiline { get => TextBox.Multiline; set => TextBox.Multiline = value; } /// <summary> /// Gets or sets a value indicating if return characters are accepted as input for multiline edit controls. /// </summary> [Category("Behavior")] [Description("Indicates if return characters are accepted as input for multiline edit controls.")] [DefaultValue(false)] public bool AcceptsReturn { get => TextBox.AcceptsReturn; set => TextBox.AcceptsReturn = value; } /// <summary> /// Gets or sets a value indicating if tab characters are accepted as input for multiline edit controls. /// </summary> [Category("Behavior")] [Description("Indicates if tab characters are accepted as input for multiline edit controls.")] [DefaultValue(false)] public bool AcceptsTab { get => TextBox.AcceptsTab; set => TextBox.AcceptsTab = value; } /// <summary> /// Gets or sets a value indicating if all the characters should be left alone or converted to uppercase or lowercase. /// </summary> [Category("Behavior")] [Description("Indicates if all the characters should be left alone or converted to uppercase or lowercase.")] [DefaultValue(typeof(CharacterCasing), "Normal")] public CharacterCasing CharacterCasing { get => TextBox.CharacterCasing; set => TextBox.CharacterCasing = value; } /// <summary> /// Gets or sets a value indicating that the selection should be hidden when the edit control loses focus. /// </summary> [Category("Behavior")] [Description("Indicates that the selection should be hidden when the edit control loses focus.")] [DefaultValue(true)] public bool HideSelection { get => TextBox.HideSelection; set => TextBox.HideSelection = value; } /// <summary> /// Gets or sets the maximum number of characters that can be entered into the edit control. /// </summary> [Category("Behavior")] [Description("Specifies the maximum number of characters that can be entered into the edit control.")] [DefaultValue(32767)] [Localizable(true)] public int MaxLength { get => TextBox.MaxLength; set => TextBox.MaxLength = value; } /// <summary> /// Gets or sets a value indicating whether the text in the edit control can be changed or not. /// </summary> [Category("Behavior")] [Description("Controls whether the text in the edit control can be changed or not.")] [RefreshProperties(RefreshProperties.Repaint)] [DefaultValue(false)] public bool ReadOnly { get => TextBox.ReadOnly; set => TextBox.ReadOnly = value; } /// <summary> /// Gets or sets a value indicating whether shortcuts defined for the control are enabled. /// </summary> [Category("Behavior")] [Description("Indicates whether shortcuts defined for the control are enabled.")] [DefaultValue(true)] public bool ShortcutsEnabled { get => TextBox.ShortcutsEnabled; set => TextBox.ShortcutsEnabled = value; } /// <summary> /// Gets or sets a the character to display for password input for single-line edit controls. /// </summary> [Category("Behavior")] [Description("Indicates the character to display for password input for single-line edit controls.")] [RefreshProperties(RefreshProperties.Repaint)] [DefaultValue('\0')] [Localizable(true)] public char PasswordChar { get => TextBox.PasswordChar; set => TextBox.PasswordChar = value; } /// <summary> /// Gets or sets a value indicating if the text in the edit control should appear as the default password character. /// </summary> [Category("Behavior")] [Description("Indicates if the text in the edit control should appear as the default password character.")] [RefreshProperties(RefreshProperties.Repaint)] [DefaultValue(false)] public bool UseSystemPasswordChar { get => TextBox.UseSystemPasswordChar; set => TextBox.UseSystemPasswordChar = value; } /// <summary> /// Gets or sets the StringCollection to use when the AutoCompleteSource property is set to CustomSource. /// </summary> [Description("The StringCollection to use when the AutoCompleteSource property is set to CustomSource.")] [Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [EditorBrowsable(EditorBrowsableState.Always)] [Localizable(true)] [Browsable(true)] public AutoCompleteStringCollection AutoCompleteCustomSource { get => TextBox.AutoCompleteCustomSource; set => TextBox.AutoCompleteCustomSource = value; } /// <summary> /// Gets or sets the text completion behavior of the textbox. /// </summary> [Description("Indicates the text completion behavior of the textbox.")] [DefaultValue(typeof(AutoCompleteMode), "None")] [EditorBrowsable(EditorBrowsableState.Always)] [Browsable(true)] public AutoCompleteMode AutoCompleteMode { get => TextBox.AutoCompleteMode; set => TextBox.AutoCompleteMode = value; } /// <summary> /// Gets or sets the autocomplete source, which can be one of the values from AutoCompleteSource enumeration. /// </summary> [Description("The autocomplete source, which can be one of the values from AutoCompleteSource enumeration.")] [DefaultValue(typeof(AutoCompleteSource), "None")] [EditorBrowsable(EditorBrowsableState.Always)] [Browsable(true)] public AutoCompleteSource AutoCompleteSource { get => TextBox.AutoCompleteSource; set => TextBox.AutoCompleteSource = value; } /// <summary> /// Gets and sets a value indicating if tooltips should be displayed for button specs. /// </summary> [Category("Visuals")] [Description("Should tooltips be displayed for button specs.")] [DefaultValue(false)] public bool AllowButtonSpecToolTips { get => TextBox.AllowButtonSpecToolTips; set => TextBox.AllowButtonSpecToolTips = value; } /// <summary> /// Gets the collection of button specifications. /// </summary> [Category("Visuals")] [Description("Collection of button specifications.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonTextBox.TextBoxButtonSpecCollection ButtonSpecs => TextBox.ButtonSpecs; /// <summary> /// Gets a value indicating whether the user can undo the previous operation in a rich text box control. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CanUndo => TextBox.CanUndo; /// <summary> /// Gets a value indicating whether the contents have changed since last last. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Modified => TextBox.Modified; /// <summary> /// Gets and sets the selected text within the control. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string SelectedText { get => TextBox.SelectedText; set => TextBox.SelectedText = value; } /// <summary> /// Gets and sets the selection length for the selected area. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int SelectionLength { get => TextBox.SelectionLength; set => TextBox.SelectionLength = value; } /// <summary> /// Gets and sets the starting point of text selected in the control. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int SelectionStart { get => TextBox.SelectionStart; set => TextBox.SelectionStart = value; } /// <summary> /// Gets the length of text in the control. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TextLength => TextBox.TextLength; /// <summary> /// Appends text to the current text of a rich text box. /// </summary> /// <param name="text">The text to append to the current contents of the text box.</param> public void AppendText(string text) { TextBox.AppendText(text); } /// <summary> /// Clears all text from the text box control. /// </summary> public void Clear() { TextBox.Clear(); } /// <summary> /// Clears information about the most recent operation from the undo buffer of the rich text box. /// </summary> public void ClearUndo() { TextBox.ClearUndo(); } /// <summary> /// Copies the current selection in the text box to the Clipboard. /// </summary> public void Copy() { TextBox.Copy(); } /// <summary> /// Moves the current selection in the text box to the Clipboard. /// </summary> public void Cut() { TextBox.Cut(); } /// <summary> /// Replaces the current selection in the text box with the contents of the Clipboard. /// </summary> public void Paste() { TextBox.Paste(); } /// <summary> /// Scrolls the contents of the control to the current caret position. /// </summary> public void ScrollToCaret() { TextBox.ScrollToCaret(); } /// <summary> /// Selects a range of text in the control. /// </summary> /// <param name="start">The position of the first character in the current text selection within the text box.</param> /// <param name="length">The number of characters to select.</param> public void Select(int start, int length) { TextBox.Select(start, length); } /// <summary> /// Selects all text in the control. /// </summary> public void SelectAll() { TextBox.SelectAll(); } /// <summary> /// Undoes the last edit operation in the text box. /// </summary> public void Undo() { TextBox.Undo(); } /// <summary> /// Specifies that the value of the SelectionLength property is zero so that no characters are selected in the control. /// </summary> public void DeselectAll() { TextBox.DeselectAll(); } /// <summary> /// Retrieves the character that is closest to the specified location within the control. /// </summary> /// <param name="pt">The location from which to seek the nearest character.</param> /// <returns>The character at the specified location.</returns> public int GetCharFromPosition(Point pt) { return TextBox.GetCharFromPosition(pt); } /// <summary> /// Retrieves the index of the character nearest to the specified location. /// </summary> /// <param name="pt">The location to search.</param> /// <returns>The zero-based character index at the specified location.</returns> public int GetCharIndexFromPosition(Point pt) { return TextBox.GetCharIndexFromPosition(pt); } /// <summary> /// Retrieves the index of the first character of a given line. /// </summary> /// <param name="lineNumber">The line for which to get the index of its first character.</param> /// <returns>The zero-based character index in the specified line.</returns> public int GetFirstCharIndexFromLine(int lineNumber) { return TextBox.GetFirstCharIndexFromLine(lineNumber); } /// <summary> /// Retrieves the index of the first character of the current line. /// </summary> /// <returns>The zero-based character index in the current line.</returns> public int GetFirstCharIndexOfCurrentLine() { return TextBox.GetFirstCharIndexOfCurrentLine(); } /// <summary> /// Retrieves the line number from the specified character position within the text of the RichTextBox control. /// </summary> /// <param name="index">The character index position to search.</param> /// <returns>The zero-based line number in which the character index is located.</returns> public int GetLineFromCharIndex(int index) { return TextBox.GetLineFromCharIndex(index); } /// <summary> /// Retrieves the location within the control at the specified character index. /// </summary> /// <param name="index">The index of the character for which to retrieve the location.</param> /// <returns>The location of the specified character.</returns> public Point GetPositionFromCharIndex(int index) { return TextBox.GetPositionFromCharIndex(index); } /// <summary> /// Gets and sets the maximum allowed size of the item. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeMaximum { get { return GroupItemSize.Large; } set { } } /// <summary> /// Gets and sets the minimum allowed size of the item. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeMinimum { get { return GroupItemSize.Small; } set { } } /// <summary> /// Gets and sets the current item size. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override GroupItemSize ItemSizeCurrent { get => _itemSizeCurrent; set { if (_itemSizeCurrent != value) { _itemSizeCurrent = value; OnPropertyChanged("ItemSizeCurrent"); } } } /// <summary> /// Creates an appropriate view element for this item. /// </summary> /// <param name="ribbon">Reference to the owning ribbon control.</param> /// <param name="needPaint">Delegate for notifying changes in display.</param> /// <returns>ViewBase derived instance.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override ViewBase CreateView(KryptonRibbon ribbon, NeedPaintHandler needPaint) { return new ViewDrawRibbonGroupTextBox(ribbon, this, needPaint); } /// <summary> /// Gets and sets the associated designer. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public IKryptonDesignObject TextBoxDesigner { get; set; } /// <summary> /// Internal design time properties. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] public ViewBase TextBoxView { get; set; } #endregion #region Protected Virtual /// <summary> /// Raises the TextChanged event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } /// <summary> /// Raises the GotFocus event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnGotFocus(EventArgs e) { GotFocus?.Invoke(this, e); } /// <summary> /// Raises the LostFocus event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnLostFocus(EventArgs e) { LostFocus?.Invoke(this, e); } /// <summary> /// Raises the KeyDown event. /// </summary> /// <param name="e">An KeyEventArgs containing the event data.</param> protected virtual void OnKeyDown(KeyEventArgs e) { KeyDown?.Invoke(this, e); } /// <summary> /// Raises the KeyUp event. /// </summary> /// <param name="e">An KeyEventArgs containing the event data.</param> protected virtual void OnKeyUp(KeyEventArgs e) { KeyUp?.Invoke(this, e); } /// <summary> /// Raises the KeyPress event. /// </summary> /// <param name="e">An KeyPressEventArgs containing the event data.</param> protected virtual void OnKeyPress(KeyPressEventArgs e) { KeyPress?.Invoke(this, e); } /// <summary> /// Raises the PreviewKeyDown event. /// </summary> /// <param name="e">An PreviewKeyDownEventArgs containing the event data.</param> protected virtual void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { PreviewKeyDown?.Invoke(this, e); } /// <summary> /// Raises the AcceptsTabChanged event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnAcceptsTabChanged(EventArgs e) { AcceptsTabChanged?.Invoke(this, e); } /// <summary> /// Raises the TextAlignChanged event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnTextAlignChanged(EventArgs e) { TextAlignChanged?.Invoke(this, e); } /// <summary> /// Raises the HideSelectionChanged event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnHideSelectionChanged(EventArgs e) { HideSelectionChanged?.Invoke(this, e); } /// <summary> /// Raises the ModifiedChanged event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnModifiedChanged(EventArgs e) { ModifiedChanged?.Invoke(this, e); } /// <summary> /// Raises the MultilineChanged event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnMultilineChanged(EventArgs e) { MultilineChanged?.Invoke(this, e); } /// <summary> /// Raises the ReadOnlyChanged event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected virtual void OnReadOnlyChanged(EventArgs e) { ReadOnlyChanged?.Invoke(this, e); } /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">Name of property that has changed.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Internal internal Control LastParentControl { get; set; } internal KryptonTextBox LastTextBox { get; set; } internal NeedPaintHandler ViewPaintDelegate { get; set; } internal void OnDesignTimeContextMenu(MouseEventArgs e) { DesignTimeContextMenu?.Invoke(this, e); } internal override bool ProcessCmdKey(ref Message msg, Keys keyData) { // Only interested in key processing if this control definition // is enabled and itself and all parents are also visible if (Enabled && ChainVisible) { // Do we have a shortcut definition for ourself? if (ShortcutKeys != Keys.None) { // Does it match the incoming key combination? if (ShortcutKeys == keyData) { // Can the text box take the focus if ((LastTextBox != null) && (LastTextBox.CanFocus)) { LastTextBox.TextBox.Focus(); } return true; } } } return false; } #endregion #region Implementation private void MonitorControl(KryptonTextBox c) { c.MouseEnter += OnControlEnter; c.MouseLeave += OnControlLeave; c.TrackMouseEnter += OnControlEnter; c.TrackMouseLeave += OnControlLeave; } private void UnmonitorControl(KryptonTextBox c) { c.MouseEnter -= OnControlEnter; c.MouseLeave -= OnControlLeave; c.TrackMouseEnter -= OnControlEnter; c.TrackMouseLeave -= OnControlLeave; } private void OnControlEnter(object sender, EventArgs e) { MouseEnterControl?.Invoke(this, e); } private void OnControlLeave(object sender, EventArgs e) { MouseLeaveControl?.Invoke(this, e); } private void OnPaletteNeedPaint(object sender, NeedLayoutEventArgs e) { // Pass request onto the view provided paint delegate ViewPaintDelegate?.Invoke(this, e); } private void OnTextBoxAcceptsTabChanged(object sender, EventArgs e) { OnAcceptsTabChanged(e); } private void OnTextBoxTextChanged(object sender, EventArgs e) { OnTextChanged(e); } private void OnTextBoxTextAlignChanged(object sender, EventArgs e) { OnTextAlignChanged(e); } private void OnTextBoxHideSelectionChanged(object sender, EventArgs e) { OnHideSelectionChanged(e); } private void OnTextBoxModifiedChanged(object sender, EventArgs e) { OnModifiedChanged(e); } private void OnTextBoxMultilineChanged(object sender, EventArgs e) { OnMultilineChanged(e); } private void OnTextBoxReadOnlyChanged(object sender, EventArgs e) { OnReadOnlyChanged(e); } private void OnTextBoxGotFocus(object sender, EventArgs e) { OnGotFocus(e); } private void OnTextBoxLostFocus(object sender, EventArgs e) { OnLostFocus(e); } private void OnTextBoxKeyPress(object sender, KeyPressEventArgs e) { OnKeyPress(e); } private void OnTextBoxKeyUp(object sender, KeyEventArgs e) { OnKeyUp(e); } private void OnTextBoxKeyDown(object sender, KeyEventArgs e) { OnKeyDown(e); } private void OnTextBoxPreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { OnPreviewKeyDown(e); } private void OnRibbonPaletteChanged(object sender, EventArgs e) { TextBox.Palette = Ribbon.GetResolvedPalette(); } #endregion } }
35.382696
185
0.580461
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.472
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Group Contents/KryptonRibbonGroupTextBox.cs
42,533
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. namespace Microsoft.VisualBasic.Activities { using System; using System.Globalization; using System.Reflection; using System.Activities.Expressions; using System.Xaml; using System.Xml.Linq; public class VisualBasicImportReference : IEquatable<VisualBasicImportReference> { static AssemblyNameEqualityComparer equalityComparer = new AssemblyNameEqualityComparer(); AssemblyName assemblyName; string assemblyNameString; int hashCode; string import; public VisualBasicImportReference() { } public string Assembly { get => this.assemblyNameString; set { if (value == null) { this.assemblyName = null; this.assemblyNameString = null; } else { // FileLoadException thrown from this ctor indicates invalid assembly name this.assemblyName = new AssemblyName(value); this.assemblyNameString = this.assemblyName.FullName; } this.EarlyBoundAssembly = null; } } public string Import { get => this.import; set { if (value != null) { this.import = value.Trim(); this.hashCode = this.import.ToUpperInvariant().GetHashCode(); } else { this.import = null; this.hashCode = 0; } this.EarlyBoundAssembly = null; } } internal AssemblyName AssemblyName { get { return this.assemblyName; } } internal XNamespace Xmlns { get; set; } // for the short-cut assembly resolution // from VBImportReference.AssemblyName ==> System.Reflection.Assembly // this is an internal state that implies the context in which a VB assembly resolution is progressing // once VB extracted this Assembly object to pass onto the compiler, // it must explicitly set this property back to null. // Clone() will also explicitly set this property of the new to null to prevent users from inadvertently // creating a copy of VBImportReference that might not resolve to the assembly of his or her intent. internal Assembly EarlyBoundAssembly { get; set; } internal VisualBasicImportReference Clone() { VisualBasicImportReference toReturn = (VisualBasicImportReference)this.MemberwiseClone(); toReturn.EarlyBoundAssembly = null; // Also make a clone of the AssemblyName. toReturn.assemblyName = (AssemblyName) this.assemblyName.Clone(); return toReturn; } public override int GetHashCode() { return this.hashCode; } public bool Equals(VisualBasicImportReference other) { if (other == null) { return false; } if (Object.ReferenceEquals(this, other)) { return true; } if (this.EarlyBoundAssembly != other.EarlyBoundAssembly) { return false; } // VB does case insensitive comparisons for imports if (string.Compare(this.Import, other.Import, StringComparison.OrdinalIgnoreCase) != 0) { return false; } // now compare the assemblies if (this.AssemblyName == null && other.AssemblyName == null) { return true; } else if (this.AssemblyName == null && other.AssemblyName != null) { return false; } else if (this.AssemblyName != null && other.AssemblyName == null) { return false; } return equalityComparer.Equals(this.AssemblyName, other.AssemblyName); } internal void GenerateXamlNamespace(INamespacePrefixLookup namespaceLookup) { // promote reference to xmlns declaration string xamlNamespace = null; if (this.Xmlns != null && !string.IsNullOrEmpty(this.Xmlns.NamespaceName)) { xamlNamespace = this.Xmlns.NamespaceName; } else { xamlNamespace = string.Format(CultureInfo.InvariantCulture, "clr-namespace:{0};assembly={1}", this.Import, this.Assembly); } // we don't need the return value since we just want to register the namespace/assembly pair namespaceLookup.LookupPrefix(xamlNamespace); } } }
32.236025
138
0.539692
[ "MIT" ]
GaryPlattenburg/CoreWF
src/UiPath.Workflow/Microsoft/VisualBasic/Activities/VisualBasicImportReference.cs
5,192
C#
using Newtonsoft.Json; namespace YouZan.Open.Api.Entry.Response.Crm { public class CrmCustomerPointsIncreaseResponse { /// <summary> /// 是否成功兼容Iron此为string的'true','false' /// </summary> [JsonProperty("is_success")] public string IsSuccess { get; set; } } }
22.214286
50
0.617363
[ "MIT" ]
gokeiyou/YouZanYunOpenSDK
YouZanYunOpenSDK/Api/Entry/Response/Crm/CrmCustomerPointsIncreaseResponse.cs
331
C#
// GE Aviation Systems LLC licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace GEAviation.Fabrica.Definition { /// <summary> /// This class is used to collect and provide Part information about a /// <see cref="Type"/> that is intended to be a Fabrica Part. /// </summary> public class PartSpecification : IPartSpecification { /// <summary> /// This constant is used to encapsulate flags for "all instance members that are public or non-public". /// </summary> private const BindingFlags cAllInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; /// <summary> /// The name of the Part. /// </summary> public string Name { get; private set; } /// <summary> /// The implementing type of the Part. /// </summary> public Type PartType { get; private set; } /// <summary> /// The developer-provided description of the part. May be null/empty. /// </summary> public string PartDescription { get; private set; } /// <summary> /// This value indicates if the part the specification represents /// is a Part Locator (true) or is not (false). /// </summary> public bool IsPartLocator { get; private set; } = false; /// <summary> /// If <see cref="IsPartLocator"/> is true, this will contain /// the scheme that the locator can handle. <see cref="string.Empty"/> /// otherwise. /// </summary> public string PartLocationScheme { get; private set; } = String.Empty; /// <summary> /// A collection of all of the Properties of the Part Type that are /// intended to be loaded by Fabrica. /// </summary> public IDictionary<string, Type> Properties { get; private set; } /// <summary> /// A collection of all of the Required Properties of the Part Type that are /// intended to be loaded by Fabrica. This will be either the same as, or a subset of, the /// <see cref="PartSpecification.Properties"/> collection. /// </summary> public IDictionary<string, Type> RequiredProperties { get; private set; } /// <summary> /// A collection of developer-provided descriptions for the Part's Properties. /// The keys of this collection will be the same as the keys in the <see cref="PartSpecification.Properties"/> /// collection, however this collection may only have a subset of those keys (or none at all). /// </summary> public IDictionary<string, string> PropertyDescriptions { get; private set; } /// <summary> /// Returns the default (unnamed) part constructor for the part this specification describes. /// </summary> public IPartConstructorInfo DefaultConstructor { get; private set; } /// <summary> /// Returns a dictionary of named part constructors for the part this specification describes. /// </summary> public IDictionary<string, IPartConstructorInfo> NamedPartConstructors { get; private set; } = new Dictionary<string, IPartConstructorInfo>(); /// <summary> /// Concrete implementation of the <see cref="IPartConstructorInfo"/> interface. /// </summary> public class PartConstructorInfo : IPartConstructorInfo { /// <summary> /// The constructor to call to use this PartConstructor. /// </summary> public ConstructorInfo Constructor { get; internal set; } /// <summary> /// A collection of all of the Features (dependencies) of the Part Type that are /// intended to be loaded by Fabrica. This includes both /// </summary> public IDictionary<string, Type> Features { get; internal set; } = new Dictionary<string, Type>(); /// <summary> /// A collection of all of the Required Features (dependencies) of the Part Type that are /// intended to be loaded by Fabrica. This will be either the same as, or a subset of, the /// <see cref="PartConstructorInfo.Features"/> collection. /// </summary> public IDictionary<string, Type> RequiredFeatures { get; internal set; } = new Dictionary<string, Type>(); /// <summary> /// A collection of developer-provided descriptions for the Part's Features. /// The keys of this collection will be the same as the keys in the <see cref="PartConstructorInfo.Features"/> /// collection, however this collection may only have a subset of those keys (or none at all). /// </summary> public IDictionary<string, string> FeatureDescriptions { get; internal set; } = new Dictionary<string, string>(); /// <summary> /// The order that the features must appear in order to call the constructor. /// </summary> public IList<string> FeatureOrder { get; internal set; } = new List<string>(); } /// <summary> /// This method will instantiate an instance of the Part this <see cref="PartSpecification"/> /// represents using the provided Features and Properties. All Required Features and Properties must be /// provided. /// </summary> /// <param name="aFeatures"> /// A collection of Feature Part instances containing, at a minimum, those Features listed in /// the <see cref="PartSpecification.RequiredFeatures"/> collection, and being assignable to /// the types of those features. The keys must exactly match those provided in either the /// <see cref="PartSpecification.Features"/> or <see cref="PartSpecification.RequiredFeatures"/> /// collections. /// </param> /// <param name="aProperties"> /// A collection of Property values containing, at a minimum, values for those Properties listed in /// the <see cref="PartSpecification.RequiredProperties"/> collection. The keys must exactly match /// those provided in either the <see cref="PartSpecification.Features"/> or /// <see cref="PartSpecification.RequiredFeatures"/> collections. /// </param> /// <exception cref="AggregateException"> /// Thrown when mutliple exceptions have happened in this method. See <see cref="AggregateException.InnerExceptions"/> /// for all exceptions that occurred. This may only contain one Exception if that Exception occurred /// in a context where multiple Exceptions may happen. /// </exception> /// <exception cref="MissingFeatureOrPropertyException"> /// Thrown if any of the Part's required Features or Properties were not provided a value in the /// arguments of this function. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if either function argument was null, or if the value for a Part's required feature or /// property was null. /// </exception> /// <exception cref="TypeMismatchException"> /// Thrown if the value given for a particular feature or property is incompatible with the /// target feature or property. /// </exception> /// <exception cref="InvalidPartSpecificationException"> /// Thrown if the Part Specification contains a read-only Property exposed via Fabrica and a value /// for that property was provided as an argument to this function, but that property is read-only. /// </exception> /// <exception cref="FailedPartInstantiationException"> /// Thrown if the reflective instantiation of the part fails for uncontrolled reasons. /// The InnerException may contain further information. /// </exception> /// <returns> /// If all required Features were provided, non-null and assignable to those features' type; and /// all required Properties were provided, non-null and convertible to those properties' types; a /// valid instance of the object will be returned. If any requirement was not met or incompatible, /// an <see cref="AggregateException"/> will be thrown with as many relevant inner exceptions as /// could be detected. /// </returns> public object instantiatePart( IDictionary<string, object> aFeatures, IDictionary<string, object> aProperties ) { return instantiatePart( null, aFeatures, aProperties ); } /// <summary> /// This method will instantiate an instance of the Part this <see cref="PartSpecification"/> /// represents using the provided Features and Properties. All Required Features and Properties must be /// provided. /// </summary> /// <param name="aConstructorName"> /// The name of the Part Constructor to use when instantiating the part. If this value is /// null, empty or whitespace, the default part constructor will be used. /// </param> /// <param name="aFeatures"> /// A collection of Feature Part instances containing, at a minimum, those Features listed in /// the <see cref="PartSpecification.RequiredFeatures"/> collection, and being assignable to /// the types of those features. The keys must exactly match those provided in either the /// <see cref="PartSpecification.Features"/> or <see cref="PartSpecification.RequiredFeatures"/> /// collections. /// </param> /// <param name="aProperties"> /// A collection of Property values containing, at a minimum, values for those Properties listed in /// the <see cref="PartSpecification.RequiredProperties"/> collection. The keys must exactly match /// those provided in either the <see cref="PartSpecification.Features"/> or /// <see cref="PartSpecification.RequiredFeatures"/> collections. /// </param> /// <exception cref="AggregateException"> /// Thrown when mutliple exceptions have happened in this method. See <see cref="AggregateException.InnerExceptions"/> /// for all exceptions that occurred. This may only contain one Exception if that Exception occurred /// in a context where multiple Exceptions may happen. /// </exception> /// <exception cref="MissingFeatureOrPropertyException"> /// Thrown if any of the Part's required Features or Properties were not provided a value in the /// arguments of this function. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if either function argument was null, or if the value for a Part's required feature or /// property was null. /// </exception> /// <exception cref="TypeMismatchException"> /// Thrown if the value given for a particular feature or property is incompatible with the /// target feature or property. /// </exception> /// <exception cref="InvalidPartSpecificationException"> /// Thrown if the Part Specification contains a read-only Property exposed via Fabrica and a value /// for that property was provided as an argument to this function, but that property is read-only. /// </exception> /// <exception cref="FailedPartInstantiationException"> /// Thrown if the reflective instantiation of the part fails for uncontrolled reasons. /// The InnerException may contain further information. /// </exception> /// <returns> /// If all required Features were provided, non-null and assignable to those features' type; and /// all required Properties were provided, non-null and convertible to those properties' types; a /// valid instance of the object will be returned. If any requirement was not met or incompatible, /// an <see cref="AggregateException"/> will be thrown with as many relevant inner exceptions as /// could be detected. /// </returns> public object instantiatePart( string aConstructorName, IDictionary<string, object> aFeatures, IDictionary<string, object> aProperties ) { List<Exception> lExceptions = new List<Exception>(); var lApprovedFeatureValues = new Dictionary<string, object>(); var lApprovedPropertyValues = new Dictionary<string, object>(); if ( this.PartType.IsGenericTypeDefinition ) { // There's a chance that the part type is actually a generic type definition (e.g. IList<T>), // not a fully-formed generic type (e.g. IList<string>). Fabrica cannot instantiate // or fully analyze the features/properties of a generic type definition. throw new InvalidOperationException( $"Cannot instantiate this part specification. The Part type '{PartType.Name}' is a generic definition." ); } IPartConstructorInfo lConstructorInfo = null; if ( !string.IsNullOrWhiteSpace( aConstructorName ) ) { if ( !this.NamedPartConstructors.ContainsKey( aConstructorName ) ) { throw new InvalidOperationException( $"Cannot instantiate this part specification. The Part Constructor '{aConstructorName}' was not found." ); } lConstructorInfo = this.NamedPartConstructors[aConstructorName]; } else { if ( this.DefaultConstructor == null ) { throw new InvalidOperationException( $"Cannot instantiate this part specification. Default constructor requested, but doesn't exist." ); } lConstructorInfo = this.DefaultConstructor; } // Parse/Validate privided Features if ( aFeatures == null ) { lExceptions.Add( new ArgumentNullException( nameof( aFeatures ) ) ); } else { // Check for required features that were not provided // a value by the caller. var lMissingFeaturesExceptions = lConstructorInfo.RequiredFeatures.Where( aItem => !aFeatures.ContainsKey( aItem.Key ) ) .Select( aItem => MissingFeatureOrPropertyException.createStandard( aItem.Key ) ); lExceptions.AddRange( lMissingFeaturesExceptions ); // Validate provided features. foreach ( var lFeature in aFeatures ) { if ( lConstructorInfo.Features.ContainsKey( lFeature.Key ) ) { var lFeaturePart = lFeature.Value; var lExpectedType = lConstructorInfo.Features[lFeature.Key]; // Null feature values are OK if they are for optional features. if ( lFeaturePart == null && lConstructorInfo.RequiredFeatures.ContainsKey( lFeature.Key ) ) { lExceptions.Add( new ArgumentNullException( $"Feature '{lFeature.Key}' value cannot be null." ) ); } // Attempt to apply implicit/explicit casting else if ( tryUserDefinedCasting( lFeature.Value, lExpectedType, out var lCastedObject ) ) { lApprovedFeatureValues[lFeature.Key] = lCastedObject; } // Attempt to auto-convert a string value to the feature's type. else if ( lFeaturePart is string lFeatureValueString && !lExpectedType.IsInstanceOfType( lFeaturePart ) ) { var lConverter = TypeDescriptor.GetConverter( lExpectedType ); try { var lConvertedValue = lConverter.ConvertFromString( lFeatureValueString ); lApprovedFeatureValues[lFeature.Key] = lConvertedValue; } catch ( Exception ) { lExceptions.Add( new TypeMismatchException( $"Could not convert feature '{lFeature.Key}' constant value '{lFeatureValueString}' to type '{lExpectedType.Name}'." ) ); } } // Null feature values don't really have a type to check, since it's an object reference, // but if it's non-null, the object has to be assignable to the target feature type. else if ( lFeaturePart != null && !lExpectedType.IsInstanceOfType( lFeaturePart ) ) { lExceptions.Add( new TypeMismatchException( lFeature.Key, lExpectedType, lFeaturePart.GetType() ) ); } // If everything went great, add it to the "approved" list. else { lApprovedFeatureValues[lFeature.Key] = lFeature.Value; } } } } // Parse/Validate privided Properties if ( aProperties == null ) { lExceptions.Add( new ArgumentNullException( nameof( aProperties ) ) ); } else { var lMissingPropertiesExceptions = RequiredProperties.Where( aItem => !aProperties.ContainsKey( aItem.Key ) ) .Select( aItem => MissingFeatureOrPropertyException.createStandard( aItem.Key ) ); lExceptions.AddRange( lMissingPropertiesExceptions ); // Validate provided properties. foreach ( var lProperty in aProperties ) { if ( Properties.ContainsKey( lProperty.Key ) ) { var lPropertyValue = lProperty.Value; var lExpectedType = Properties[lProperty.Key]; // Null values are OK if they are for optional properties. if ( lPropertyValue == null && RequiredProperties.ContainsKey( lProperty.Key ) ) { lExceptions.Add( new ArgumentNullException( $"Property '{lProperty.Key}' value cannot be null." ) ); } // Null property values don't really have a type to check, since it's an object reference, // but if it's non-null, the object has to be assignable to the target feature type. else if ( lPropertyValue != null ) { if ( lPropertyValue.GetType() == lExpectedType ) { lApprovedPropertyValues[lProperty.Key] = lPropertyValue; } // Attempt to apply implicit/explicit casting else if ( tryUserDefinedCasting( lProperty.Value, lExpectedType, out var lCastedObject ) ) { lApprovedPropertyValues[lProperty.Key] = lCastedObject; } else if ( lPropertyValue is string lPropertyValueString ) { // Type checking here is trickier, since the property mechanism // accepts just "Strings" and hopes that they can be converted to // the expected type. var lConverter = TypeDescriptor.GetConverter( lExpectedType ); try { var lConvertedValue = lConverter.ConvertFromString( lPropertyValueString ); lApprovedPropertyValues[lProperty.Key] = lConvertedValue; } catch ( Exception ) { lExceptions.Add( new TypeMismatchException( $"Could not convert property '{lProperty.Key}' value '{lPropertyValue}' to type '{lExpectedType.Name}'." ) ); } } } } } } // Trying to give users as many exceptions at once to reduce debugging. // Throwing here to protect the remainder of the method. if ( lExceptions.Any() ) { throw new AggregateException( lExceptions ); } // Build the constructor argument list. List<object> lConstructorArguments = new List<object>(); foreach ( var lFeature in lConstructorInfo.FeatureOrder ) { // The null behavior in here is important. It serves as // the mechanism to handle optional Features that were not // specified by the caller. object lFeatureValue = null; if ( lApprovedFeatureValues.ContainsKey( lFeature ) ) { lFeatureValue = lApprovedFeatureValues[lFeature]; } // If the caller didn't provide a value for this Feature // in the Feature order, use null instead, as the feature is optional. lConstructorArguments.Add( lFeatureValue ); } object lInstantiatedPart = null; try { // Construct the object. lInstantiatedPart = lConstructorInfo.Constructor.Invoke( lConstructorArguments.ToArray() ); // This should be the same as this.PartType, but for safety, it's grabbed // from the actual object instance instead. Type lFinalPartType = lInstantiatedPart.GetType(); // Read through the target properties, and attempt to set them. foreach ( var lProperty in lApprovedPropertyValues ) { if ( lFinalPartType.GetProperty( lProperty.Key, cAllInstanceMembers ) is PropertyInfo lPropInfo && lPropInfo.GetSetMethod( true ) is MethodInfo lSetter ) { try { lSetter.Invoke( lInstantiatedPart, new[] { lProperty.Value } ); } catch ( Exception lException ) { // An exception here indicates a problem with calling "set" on the property. lExceptions.Add( lException ); } } // It's technically not possible to get into this else case. // I've left it here to indicate that I've thought about what // might happen, but the guards in createPartSpecification() eliminate // this as a possibility. Code is left out for statement coverage purposes. //else //{ // lExceptions.Add( new InvalidPartSpecificationException( $"Part Property '{lProperty.Key}' is read-only or could not be found." ) ); //} } // Any exceptions at this point indicate that the property setting phase has failed, // either completely or partially. As a result, instantiation has failed. // This prevents callers from receiving incomplete Parts. if ( lExceptions.Any() ) { throw new AggregateException( lExceptions ); } } catch ( Exception lException ) when ( !( lException is AggregateException ) ) { // Wrapped throw since this exception likely has more to do with // a mistake that Fabrica has made rather than that of the user. throw new FailedPartInstantiationException( this.Name, lException ); } if ( lInstantiatedPart is IPropertiesSetNotification lNotification ) { try { // Notify the object that its properties are set, if it wants to know // (i.e. has implemented the interface) lNotification.propertiesSet(); } catch ( Exception lException ) { throw new InvalidOperationException( "Instantiated part raised an exception during 'Property Set Notification'. See InnerException for details.", lException ); } } // Object is ready to go! return lInstantiatedPart; } /// <summary> /// This method can be used to determine if a particular type is intended to be /// a Fabrica Part. This method simply checks the Type for the existence of the /// <see cref="PartAttribute"/>. /// </summary> /// <param name="aPotentialPart"> /// The Type to check. /// </param> /// <returns> /// True if the Type is intended to be used within the Fabrica Part system, /// false otherwise. /// </returns> public static bool isPart( Type aPotentialPart ) { var lPartAttr = aPotentialPart.GetCustomAttributes( typeof( PartAttribute ), false ); return lPartAttr.Length > 0; } /// <summary> /// This static method will create a <see cref="PartSpecification"/> from the /// specified Type if that Type is a Fabrica Part. /// </summary> /// <param name="aPotentialPart"> /// The <see cref="Type"/> of the candidate Fabrica Part. /// </param> /// <returns> /// The <see cref="PartSpecification"/> for the specified Fabrica Part type or /// null if the specified type is not a Fabrica Part. /// </returns> public static IPartSpecification createPartSpecification( Type aPotentialPart ) { // Method to get the specified Attribute AttrType getAttribute<AttrType>( Func<Type, bool, object[]> aGetAttributesMethod ) { var lDescAttr = aGetAttributesMethod( typeof( AttrType ), false ); if ( lDescAttr.Length > 0 ) { return (AttrType)lDescAttr[0]; } return default( AttrType ); } // Method to get the value of the Description attribute of something, // or a nice default. string getDescription( Func<Type, bool, object[]> aGetAttributesMethod ) { var lDescAttr = getAttribute<DescriptionAttribute>( aGetAttributesMethod ); return lDescAttr?.Description; } if ( aPotentialPart == null ) { throw new ArgumentNullException( nameof( aPotentialPart ) ); } if ( isPart( aPotentialPart ) ) { PartSpecification lSpec = new PartSpecification(); // Get Part Info lSpec.Name = aPotentialPart.FullName; lSpec.PartType = aPotentialPart; lSpec.PartDescription = getDescription( aPotentialPart.GetCustomAttributes ); var lPartLocatorAttribute = getAttribute<PartLocatorAttribute>( aPotentialPart.GetCustomAttributes ); if ( !string.IsNullOrWhiteSpace( lPartLocatorAttribute?.LocatorScheme ) ) { lSpec.IsPartLocator = true; lSpec.PartLocationScheme = lPartLocatorAttribute.LocatorScheme; } var lConstructors = aPotentialPart.GetConstructors( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ) .Select( aConstructor => new { Constructor = aConstructor, Parameters = aConstructor.GetParameters() } ) .Where( aConstructor => aConstructor?.Parameters?.Count() >= 0 ); foreach ( var lConstructor in lConstructors ) { // The constructor to be used by Fabrica must be public and appropriately // marked with a PartConstructor attribute. if ( getAttribute<PartConstructorAttribute>( lConstructor.Constructor.GetCustomAttributes ) is PartConstructorAttribute lConstructorAttribute ) { PartConstructorInfo lNewConstructorInfo = new PartConstructorInfo(); // Prepare the collections for a new constructor, in case // a previous iteration of this loop found a partially defined // Part constructor. //lSpec.Features.Clear(); //lSpec.FeatureDescriptions.Clear(); //lSpec.RequiredFeatures.Clear(); //lSpec.mFeatureOrder.Clear(); foreach ( var lParameter in lConstructor.Parameters ) { var lFeatureAttr = getAttribute<FeatureAttribute>( lParameter.GetCustomAttributes ); // Every parameter in the constructor must be marked with a FeatureAttribute in // order to auto-construct it. If any don't have it, discard this constructor. if ( lFeatureAttr == null ) { throw new InvalidPartSpecificationException( $"Every parameter of a constructor marked with {nameof( PartConstructorAttribute )} must have a {nameof( FeatureAttribute )}." ); } var lDescription = getDescription( lParameter.GetCustomAttributes ); var lFeatureType = lParameter.ParameterType; lNewConstructorInfo.FeatureOrder.Add( lFeatureAttr.FeatureName ); lNewConstructorInfo.Features[lFeatureAttr.FeatureName] = lFeatureType; if ( !string.IsNullOrWhiteSpace( lDescription ) ) { lNewConstructorInfo.FeatureDescriptions[lFeatureAttr.FeatureName] = lDescription; } if ( lFeatureAttr.Required ) { lNewConstructorInfo.RequiredFeatures[lFeatureAttr.FeatureName] = lFeatureType; } } // This should also work in the case of a public parameterless constructor. if ( lNewConstructorInfo.FeatureOrder.Count == lConstructor.Parameters.Length ) { lNewConstructorInfo.Constructor = lConstructor.Constructor; } if ( !string.IsNullOrWhiteSpace( lConstructorAttribute.Name ) ) { // Named constructor if ( lSpec.NamedPartConstructors.ContainsKey( lConstructorAttribute.Name ) ) { throw new InvalidPartSpecificationException( $"Part '{aPotentialPart.Name}' has multiple part constructors with the name '{lConstructorAttribute.Name}'." ); } lSpec.NamedPartConstructors[lConstructorAttribute.Name] = lNewConstructorInfo; } else { // Default no-name if ( lSpec.DefaultConstructor != null ) { throw new InvalidPartSpecificationException( $"Part '{aPotentialPart.Name}' has multiple default (nameless) part constructors. Only one is allowed." ); } lSpec.DefaultConstructor = lNewConstructorInfo; } } } if ( lSpec.DefaultConstructor == null && lSpec.NamedPartConstructors.Count == 0 ) { throw new InvalidPartSpecificationException( $"Part '{aPotentialPart.Name}' requires at least one public constructor marked with a PartConstructorAttribute, with each parameter marked with a FeatureAttribute." ); } // Read properties. var lProperties = aPotentialPart.GetProperties( cAllInstanceMembers ); foreach ( var lProperty in lProperties ) { if ( getAttribute<PropertyAttribute>( lProperty.GetCustomAttributes ) is PropertyAttribute lPropertyAttribute ) { if ( !lProperty.CanWrite ) { throw new InvalidPartSpecificationException( $"Part property '{lProperty.Name}' must have a set accessor in order to be used as a Part Property." ); } lSpec.Properties[lProperty.Name] = lProperty.PropertyType; var lDescription = getDescription( lProperty.GetCustomAttributes ); if ( !string.IsNullOrWhiteSpace( lDescription ) ) { lSpec.PropertyDescriptions[lProperty.Name] = lDescription; } if ( lPropertyAttribute.Required ) { lSpec.RequiredProperties[lProperty.Name] = lProperty.PropertyType; } } } return lSpec; } throw new InvalidPartSpecificationException( $"Part '{aPotentialPart.Name}' is not marked with PartAttribute." ); } // Eliminating public parameterless constructor. private PartSpecification() { Properties = new Dictionary<string, Type>(); RequiredProperties = new Dictionary<string, Type>(); PropertyDescriptions = new Dictionary<string, string>(); } /// <summary> /// This method can be used to analyze an assembly for Types that are implemented in /// accordance with Fabrica Parts. /// </summary> /// <param name="aOwningAssemblies"> /// The collection of assemblies to search. /// </param> /// <param name="aPartDiscoveryExceptions"> /// An <see cref="AggregateException"/> containing any exceptions that occurred during the /// part discovery process. /// </param> /// <returns> /// A collection of <see cref="IPartSpecification"/> objects representing all valid parts /// found within the specified assemblies. /// </returns> public static IEnumerable<IPartSpecification> getSpecifications( IEnumerable<Assembly> aOwningAssemblies, out AggregateException aPartDiscoveryExceptions ) { aPartDiscoveryExceptions = null; if ( aOwningAssemblies == null ) { throw new ArgumentNullException( nameof( aOwningAssemblies ) ); } List<IPartSpecification> lSpecs = new List<IPartSpecification>(); List<Exception> lExceptions = new List<Exception>(); foreach ( var lAssembly in aOwningAssemblies ) { if ( lAssembly != null ) { var lTypes = lAssembly.GetTypes(); foreach ( var lType in lTypes ) { try { if ( isPart( lType ) ) { lSpecs.Add( createPartSpecification( lType ) ); } } catch ( Exception lException ) { lExceptions.Add( lException ); } } } } if ( lExceptions.Count > 0 ) { aPartDiscoveryExceptions = new AggregateException( "A part specification could not be generated for one or more parts.", lExceptions ); } return lSpecs; } /// <summary> /// This method can be used to analyze an assembly for Types that are implemented in /// accordance with Fabrica Parts. /// </summary> /// <param name="aOwningAssembly"> /// The assembly to search. /// </param> /// <param name="aPartDiscoveryExceptions"> /// An <see cref="AggregateException"/> containing any exceptions that occurred during the /// part discovery process. /// </param> /// <returns> /// A collection of <see cref="IPartSpecification"/> objects representing all valid parts /// found within the assembly. /// </returns> public static IEnumerable<IPartSpecification> getSpecifications( Assembly aOwningAssembly, out AggregateException aPartDiscoveryExceptions ) { return getSpecifications( new List<Assembly>() { aOwningAssembly }, out aPartDiscoveryExceptions ); } /// <summary> /// Attempts to cast an object to the specified type using implemented cast /// overloads (i.e. implicit/explicit cast operator overloads). If no compatible /// overload exists on either type, the method will return false. /// </summary> /// <param name="aObject"> /// The object to be casted. /// </param> /// <param name="aExpectedType"> /// The type to cast to. /// </param> /// <param name="aAsExpected"> /// If successful, the casted object. /// </param> /// <returns> /// True if the cast was successful, false otherwise. /// </returns> private static bool tryUserDefinedCasting( object aObject, Type aExpectedType, out object aAsExpected ) { // Find a cast method from aObject's Type. var lToMethod = aObject.GetType().GetMethods( BindingFlags.Public | BindingFlags.Static ) .Where( aMethod => { ParameterInfo lParam = aMethod.GetParameters().FirstOrDefault(); return lParam != null && lParam.ParameterType == aObject.GetType() && ( aMethod.Name == "op_Implicit" || aMethod.Name == "op_Explicit" ) && aExpectedType.IsAssignableFrom( aMethod.ReturnType ); } ).FirstOrDefault(); // Find a cast method from aExpectedType. var lFromMethod = aExpectedType.GetMethods( BindingFlags.Public | BindingFlags.Static ) .Where( aMethod => { ParameterInfo lParam = aMethod.GetParameters().FirstOrDefault(); return lParam != null && lParam.ParameterType == aObject.GetType() && ( aMethod.Name == "op_Implicit" || aMethod.Name == "op_Explicit" ) && aExpectedType.IsAssignableFrom( aMethod.ReturnType ); } ).FirstOrDefault(); var lMethod = lToMethod ?? lFromMethod; if ( lMethod != null ) { aAsExpected = lMethod.Invoke( null, new object[] { aObject } ); return true; } aAsExpected = null; return false; } } }
50.543665
232
0.553052
[ "MIT" ]
GEAviationSystems/fabrica
Source/Fabrica/Definition/PartSpecification.cs
41,094
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; using VRMShaders; namespace UniGLTF { /// <summary> /// ImporterContext の Load 結果の GltfModel /// /// Runtime でモデルを Destory したときに関連リソース(Texture, Material...などの UnityEngine.Object)を自動的に Destroy する。 /// </summary> public class RuntimeGltfInstance : MonoBehaviour, IResponsibilityForDestroyObjects { /// <summary> /// this is UniGLTF root gameObject /// </summary> public GameObject Root => (this != null) ? this.gameObject : null; /// <summary> /// Transforms with gltf node index. /// </summary> public IReadOnlyList<Transform> Nodes => _nodes; /// <summary> /// Runtime resources. /// ex. Material, Texture, AnimationClip, Mesh. /// </summary> public IReadOnlyList<(SubAssetKey, UnityEngine.Object)> RuntimeResources => _resources; /// <summary> /// Materials. /// </summary> public IReadOnlyList<Material> Materials => _materials; /// <summary> /// Textures. /// </summary> public IReadOnlyList<Texture> Textures => _textures; /// <summary> /// Animation Clips. /// </summary> public IReadOnlyList<AnimationClip> AnimationClips => _animationClips; /// <summary> /// Meshes. /// </summary> public IReadOnlyList<Mesh> Meshes => _meshes; /// <summary> /// Renderers. /// ex. MeshRenderer, SkinnedMeshRenderer. /// </summary> public IReadOnlyList<Renderer> Renderers => _renderers; /// <summary> /// Mesh Renderers. /// </summary> public IReadOnlyList<MeshRenderer> MeshRenderers => _meshRenderers; /// <summary> /// Skinned Mesh Renderers. /// </summary> public IReadOnlyList<SkinnedMeshRenderer> SkinnedMeshRenderers => _skinnedMeshRenderers; /// <summary> /// ShowMeshes の対象になる Renderer。 /// Destroy対象とは無関係なので、自由に操作して OK。 /// </summary> /// <typeparam name="Renderer"></typeparam> /// <returns></returns> public IList<Renderer> VisibleRenderers => _visibleRenderers; private readonly List<Transform> _nodes = new List<Transform>(); private readonly List<(SubAssetKey, UnityEngine.Object)> _resources = new List<(SubAssetKey, UnityEngine.Object)>(); private readonly List<Material> _materials = new List<Material>(); private readonly List<Texture> _textures = new List<Texture>(); private readonly List<AnimationClip> _animationClips = new List<AnimationClip>(); private readonly List<Mesh> _meshes = new List<Mesh>(); private readonly List<Renderer> _renderers = new List<Renderer>(); private readonly List<MeshRenderer> _meshRenderers = new List<MeshRenderer>(); private readonly List<SkinnedMeshRenderer> _skinnedMeshRenderers = new List<SkinnedMeshRenderer>(); private readonly List<Renderer> _visibleRenderers = new List<Renderer>(); public static RuntimeGltfInstance AttachTo(GameObject go, ImporterContext context) { var loaded = go.AddComponent<RuntimeGltfInstance>(); foreach (var node in context.Nodes) { // Maintain index order. loaded._nodes.Add(node); } context.TransferOwnership((k, o) => { if (o == null) return; loaded._resources.Add((k, o)); switch (o) { case Material material: loaded._materials.Add(material); break; case Texture texture: loaded._textures.Add(texture); break; case AnimationClip animationClip: loaded._animationClips.Add(animationClip); break; case Mesh mesh: loaded._meshes.Add(mesh); break; } }); foreach (var renderer in go.GetComponentsInChildren<Renderer>()) { loaded.AddRenderer(renderer); } return loaded; } public void AddRenderer(Renderer renderer) { _renderers.Add(renderer); VisibleRenderers.Add(renderer); switch (renderer) { case MeshRenderer meshRenderer: _meshRenderers.Add(meshRenderer); break; case SkinnedMeshRenderer skinnedMeshRenderer: _skinnedMeshRenderers.Add(skinnedMeshRenderer); break; } } public void ShowMeshes() { foreach (var r in VisibleRenderers) { r.enabled = true; } } public void EnableUpdateWhenOffscreen() { foreach (var skinnedMeshRenderer in SkinnedMeshRenderers) { skinnedMeshRenderer.updateWhenOffscreen = true; } } void OnDestroy() { Debug.Log("UnityResourceDestroyer.OnDestroy"); foreach (var (_, obj) in _resources) { UnityObjectDestoyer.DestroyRuntimeOrEditor(obj); } } public void TransferOwnership(TakeResponsibilityForDestroyObjectFunc take) { foreach (var (key, x) in _resources.ToArray()) { take(key, x); _resources.Remove((key, x)); } } public void Dispose() { if (this != null && this.gameObject != null) { UnityObjectDestoyer.DestroyRuntimeOrEditor(this.gameObject); } } } }
31.89418
124
0.544625
[ "MIT" ]
0b5vr/UniVRM
Assets/UniGLTF/Runtime/UniGLTF/RuntimeGltfInstance.cs
6,144
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Docker.DotNet.Models; using DockerVirtualBoxExpose.Common.Entities; using Serilog; namespace DockerVirtualBoxExpose.DockerAgent.Docker { public static class ExposedServiceLabelParser { public const string ExposedServiceLabel = "vm-expose"; public static IEnumerable<ExposedService> GetExposedServicesFromContainer(ContainerListResponse container) { var exposedPorts = GetExposedServiceLabelValue(container); if (string.IsNullOrWhiteSpace(exposedPorts)) { return GetAllExposedPorts(container); } return ParseExposedLabelValue(exposedPorts, container); } private static IEnumerable<ExposedService> ParseExposedLabelValue(string exposedPorts, ContainerListResponse container) { const char splitCharacter = ','; var stringPorts = RemoveAllWhitespaces(exposedPorts).Split(splitCharacter, StringSplitOptions.RemoveEmptyEntries); foreach (var stringPort in stringPorts) { if (!int.TryParse(stringPort, out var port)) { Log.Logger.Warning("The exposed port {port} for the container {container} couldn't be parsed!", stringPort, container.ID); continue; } yield return new ExposedService(container.ID, port); } } private static string GetExposedServiceLabelValue(ContainerListResponse container) { var exposedLabel = container.Labels?.FirstOrDefault(label => label.Key == ExposedServiceLabel); return exposedLabel?.Value; } private static IEnumerable<ExposedService> GetAllExposedPorts(ContainerListResponse container) { return container.Ports .Where(containerPort => !string.IsNullOrWhiteSpace(containerPort.IP)) .Select(containerPort => new ExposedService(container.ID, containerPort.PublicPort)); } private static string RemoveAllWhitespaces(string value) { return Regex.Replace(value, @"\s+", string.Empty); } } }
36.365079
142
0.656045
[ "MIT" ]
Marcel-Lambacher/docker-virtualbox-expose
src/DockerVirtualBoxExpose.DockerAgent/Docker/ExposedServiceLabelParser.cs
2,293
C#
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Globalization; namespace Xceed.Wpf.AvalonDock.Layout { [Serializable] public abstract class LayoutPositionableGroup<T> : LayoutGroup<T>, ILayoutPositionableElement, ILayoutPositionableElementWithActualSize where T : class, ILayoutElement { public LayoutPositionableGroup() { } GridLength _dockWidth = new GridLength(1.0, GridUnitType.Star); public GridLength DockWidth { get { return _dockWidth; } set { if (DockWidth != value) { RaisePropertyChanging("DockWidth"); _dockWidth = value; RaisePropertyChanged("DockWidth"); OnDockWidthChanged(); } } } protected virtual void OnDockWidthChanged() { } GridLength _dockHeight = new GridLength(1.0, GridUnitType.Star); public GridLength DockHeight { get { return _dockHeight; } set { if (DockHeight != value) { RaisePropertyChanging("DockHeight"); _dockHeight = value; RaisePropertyChanged("DockHeight"); OnDockHeightChanged(); } } } protected virtual void OnDockHeightChanged() { } #region AllowDuplicateContent private bool _allowDuplicateContent = true; /// <summary> /// Gets or sets the AllowDuplicateContent property. /// When this property is true, then the LayoutDocumentPane or LayoutAnchorablePane allows dropping /// duplicate content (according to its Title and ContentId). When this dependency property is false, /// then the LayoutDocumentPane or LayoutAnchorablePane hides the OverlayWindow.DropInto button to prevent dropping of duplicate content. /// </summary> public bool AllowDuplicateContent { get { return _allowDuplicateContent; } set { if (_allowDuplicateContent != value) { RaisePropertyChanging("AllowDuplicateContent"); _allowDuplicateContent = value; RaisePropertyChanged("AllowDuplicateContent"); } } } #endregion #region CanRepositionItems private bool _canRepositionItems = true; public bool CanRepositionItems { get { return _canRepositionItems; } set { if (_canRepositionItems != value) { RaisePropertyChanging("CanRepositionItems"); _canRepositionItems = value; RaisePropertyChanged("CanRepositionItems"); } } } #endregion #region DockMinWidth private double _dockMinWidth = 25.0; public double DockMinWidth { get { return _dockMinWidth; } set { if (_dockMinWidth != value) { MathHelper.AssertIsPositiveOrZero(value); RaisePropertyChanging("DockMinWidth"); _dockMinWidth = value; RaisePropertyChanged("DockMinWidth"); } } } #endregion #region DockMinHeight private double _dockMinHeight = 25.0; public double DockMinHeight { get { return _dockMinHeight; } set { if (_dockMinHeight != value) { MathHelper.AssertIsPositiveOrZero(value); RaisePropertyChanging("DockMinHeight"); _dockMinHeight = value; RaisePropertyChanged("DockMinHeight"); } } } #endregion #region FloatingWidth private double _floatingWidth = 0.0; public double FloatingWidth { get { return _floatingWidth; } set { if (_floatingWidth != value) { RaisePropertyChanging("FloatingWidth"); _floatingWidth = value; RaisePropertyChanged("FloatingWidth"); } } } #endregion #region FloatingHeight private double _floatingHeight = 0.0; public double FloatingHeight { get { return _floatingHeight; } set { if (_floatingHeight != value) { RaisePropertyChanging("FloatingHeight"); _floatingHeight = value; RaisePropertyChanged("FloatingHeight"); } } } #endregion #region FloatingLeft private double _floatingLeft = 0.0; public double FloatingLeft { get { return _floatingLeft; } set { if (_floatingLeft != value) { RaisePropertyChanging("FloatingLeft"); _floatingLeft = value; RaisePropertyChanged("FloatingLeft"); } } } #endregion #region FloatingTop private double _floatingTop = 0.0; public double FloatingTop { get { return _floatingTop; } set { if (_floatingTop != value) { RaisePropertyChanging("FloatingTop"); _floatingTop = value; RaisePropertyChanged("FloatingTop"); } } } #endregion #region IsMaximized private bool _isMaximized = false; public bool IsMaximized { get { return _isMaximized; } set { if (_isMaximized != value) { _isMaximized = value; RaisePropertyChanged("IsMaximized"); } } } #endregion [NonSerialized] double _actualWidth; double ILayoutPositionableElementWithActualSize.ActualWidth { get { return _actualWidth; } set { _actualWidth = value; } } [NonSerialized] double _actualHeight; double ILayoutPositionableElementWithActualSize.ActualHeight { get { return _actualHeight; } set { _actualHeight = value; } } public override void WriteXml(System.Xml.XmlWriter writer) { if (DockWidth.Value != 1.0 || !DockWidth.IsStar) writer.WriteAttributeString("DockWidth", _gridLengthConverter.ConvertToInvariantString(DockWidth)); if (DockHeight.Value != 1.0 || !DockHeight.IsStar) writer.WriteAttributeString("DockHeight", _gridLengthConverter.ConvertToInvariantString(DockHeight)); if (DockMinWidth != 25.0) writer.WriteAttributeString("DocMinWidth", DockMinWidth.ToString(CultureInfo.InvariantCulture)); if (DockMinHeight != 25.0) writer.WriteAttributeString("DockMinHeight", DockMinHeight.ToString(CultureInfo.InvariantCulture)); if (FloatingWidth != 0.0) writer.WriteAttributeString("FloatingWidth", FloatingWidth.ToString(CultureInfo.InvariantCulture)); if (FloatingHeight != 0.0) writer.WriteAttributeString("FloatingHeight", FloatingHeight.ToString(CultureInfo.InvariantCulture)); if (FloatingLeft != 0.0) writer.WriteAttributeString("FloatingLeft", FloatingLeft.ToString(CultureInfo.InvariantCulture)); if (FloatingTop != 0.0) writer.WriteAttributeString("FloatingTop", FloatingTop.ToString(CultureInfo.InvariantCulture)); if (IsMaximized) writer.WriteAttributeString("IsMaximized", IsMaximized.ToString()); base.WriteXml(writer); } static GridLengthConverter _gridLengthConverter = new GridLengthConverter(); public override void ReadXml(System.Xml.XmlReader reader) { if (reader.MoveToAttribute("DockWidth")) _dockWidth = (GridLength) _gridLengthConverter.ConvertFromInvariantString(reader.Value); if (reader.MoveToAttribute("DockHeight")) _dockHeight = (GridLength) _gridLengthConverter.ConvertFromInvariantString(reader.Value); if (reader.MoveToAttribute("DocMinWidth")) _dockMinWidth = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("DocMinHeight")) _dockMinHeight = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("FloatingWidth")) _floatingWidth = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("FloatingHeight")) _floatingHeight = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("FloatingLeft")) _floatingLeft = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("FloatingTop")) _floatingTop = double.Parse(reader.Value, CultureInfo.InvariantCulture); if (reader.MoveToAttribute("IsMaximized")) _isMaximized = bool.Parse(reader.Value); base.ReadXml(reader); } } }
27.373333
170
0.705675
[ "MIT" ]
trigger-death/ZeldaOracle
EditorLibraries/Xceed.Wpf.AvalonDock/Layout/LayoutPositionableGroup.cs
8,214
C#
// Url: https://leetcode.com/problems/basic-calculator-iv/ /* 770. Basic Calculator IV Hard Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"] An expression alternates chunks and symbols, with a space separating each chunk and symbol. A chunk is either an expression in parentheses, a variable, or a non-negative integer. A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x". Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, expression = "1 + 2 * 3" has an answer of ["7"]. The format of the output is as follows: For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like "b*a*c", only "a*b*c". Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, "a*a*b*c" has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] Terms (including constant terms) with coefficient 0 are not included. For example, an expression of "0" has an output of []. Examples: Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1] Output: ["-1*a","14"] Input: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12] Output: ["-1*pressure","5"] Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = [] Output: ["1*e*e","-64"] Input: expression = "7 - 7", evalvars = [], evalints = [] Output: [] Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = [] Output: ["5*a*b*c"] Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", evalvars = [], evalints = [] Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"] Note: expression will have length in range [1, 250]. evalvars, evalints will have equal lengths in range [0, 100]. */ using System; using System.Collections.Generic; namespace InterviewPreperationGuide.Core.LeetCode.problem770 { public class Solution { public void Init () { Console.WriteLine (); } // Time: O () // Space: O () public IList<string> BasicCalculatorIV (string expression, string[] evalvars, int[] evalints) { return null; } } }
51.031746
273
0.655365
[ "MIT" ]
tarunbatta/ipg
core/leetcode/770.cs
3,215
C#
using HarmonyLib; namespace DPS; #region Tracking attacks for DPS meter. [HarmonyPatch(typeof(Attack), nameof(Attack.Start))] public class Attack_Start { static void Postfix(Attack __instance, Humanoid character, bool __result, int ___m_currentAttackCainLevel) { if (__result && character == Player.m_localPlayer) { DPSMeter.Start(); var stamina = __instance.GetAttackStamina(); DPSMeter.AddStamina(stamina); DPSMeter.AddHit(); } } } [HarmonyPatch(typeof(Attack), nameof(Attack.OnAttackDone))] public class Attack_OnAttackDone { static void Postfix(Humanoid ___m_character) { if (___m_character == Player.m_localPlayer) DPSMeter.SetTime(); } } #endregion #region Tracking structure damage for DPS meter. [HarmonyPatch(typeof(Destructible), nameof(Destructible.RPC_Damage))] public class Destructible_RPC_Damage { static void Postfix(Destructible __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } [HarmonyPatch(typeof(MineRock), nameof(MineRock.RPC_Hit))] public class MineRock_RPC_Hit { static void Postfix(MineRock __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } [HarmonyPatch(typeof(WearNTear), nameof(WearNTear.RPC_Damage))] public class WearNTear_RPC_Damage { static void Postfix(WearNTear __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } [HarmonyPatch(typeof(MineRock5), nameof(MineRock5.DamageArea))] public class MineRock5_DamageArea { static void Postfix(MineRock5 __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } [HarmonyPatch(typeof(TreeBase), nameof(TreeBase.RPC_Damage))] public class TreeBase_RPC_Damage { static void Postfix(TreeBase __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } [HarmonyPatch(typeof(TreeLog), nameof(TreeLog.RPC_Damage))] public class TreeLog_RPC_Damage { static void Postfix(TreeLog __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddStructureDamage(hit, __instance); } } #endregion #region Tracking creature damage for DPS meter [HarmonyPatch(typeof(Character), nameof(Character.ApplyDamage))] public class Character_ApplyDamage { static void Prefix(Character __instance, HitData hit) { if (hit.GetAttacker() == Player.m_localPlayer) DPSMeter.AddDamage(hit, __instance); if (hit.GetAttacker() == null) DPSMeter.AddDot(hit); if (__instance == Player.m_localPlayer) DPSMeter.AddDamageTaken(hit); } } #endregion #region Tracking other things for DPS meter. [HarmonyPatch(typeof(Player), nameof(Player.UseStamina))] public class Player_UseStamina { static void Prefix(Player __instance, float v) { if (__instance == Player.m_localPlayer) DPSMeter.AddTotalStamina(v); } } #endregion
34.910112
110
0.747345
[ "Unlicense" ]
JereKuusela/valheim-dps
DPS/DPSTool.cs
3,107
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void CreateScalarInt64() { var test = new VectorCreate__CreateScalarInt64(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorCreate__CreateScalarInt64 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int64 value = TestLibrary.Generator.GetInt64(); Vector256<Int64> result = Vector256.CreateScalar(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int64 value = TestLibrary.Generator.GetInt64(); object result = typeof(Vector256) .GetMethod(nameof(Vector256.CreateScalar), new Type[] { typeof(Int64) }) .Invoke(null, new object[] { value }); ValidateResult((Vector256<Int64>)(result), value); } private void ValidateResult( Vector256<Int64> result, Int64 expectedValue, [CallerMemberName] string method = "" ) { Int64[] resultElements = new Int64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult( Int64[] resultElements, Int64 expectedValue, [CallerMemberName] string method = "" ) { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (resultElements[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation( $"Vector256.CreateScalar(Int64): {method} failed:" ); TestLibrary.TestFramework.LogInformation($" value: {expectedValue}"); TestLibrary.TestFramework.LogInformation( $" result: ({string.Join(", ", resultElements)})" ); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
33.588235
93
0.537903
[ "MIT" ]
belav/runtime
src/tests/JIT/HardwareIntrinsics/General/Vector256/CreateScalar.Int64.cs
3,997
C#
namespace Tailspin.Web.Survey.Shared.Tests.Models { using System; using System.Collections.Generic; using System.Linq; using System.Web.Script.Serialization; using Microsoft.VisualStudio.TestTools.UnitTesting; using Tailspin.Web.Survey.Shared.Models; [TestClass] public class SurveyAnswersSummaryFixture { [TestMethod] public void AddNewAnswerCallsMergeWith1AsTotalAnswers() { var surveyAnswersSummary = new StubSurveyAnswersSummary(); var surveyAnswer = new SurveyAnswer(); surveyAnswersSummary.AddNewAnswer(surveyAnswer); Assert.AreEqual(1, surveyAnswersSummary.MergeParameter.TotalAnswers); } [TestMethod] public void AddNew5StarsAnswerCallsMergeWithNewSummary() { var surveyAnswersSummary = new StubSurveyAnswersSummary(); var questionAnswer = new QuestionAnswer { QuestionType = QuestionType.FiveStars, QuestionText = "5 stars", Answer = "1" }; var surveyAnswer = new SurveyAnswer(); surveyAnswer.QuestionAnswers.Add(questionAnswer); surveyAnswersSummary.AddNewAnswer(surveyAnswer); var questionAnswersSummary = surveyAnswersSummary.MergeParameter.QuestionAnswersSummaries.First(); Assert.AreEqual("5 stars", questionAnswersSummary.QuestionText); Assert.AreEqual(QuestionType.FiveStars, questionAnswersSummary.QuestionType); Assert.AreEqual("1.00", questionAnswersSummary.AnswersSummary); } [TestMethod] public void AddNewMultipleChoiceAnswerCallsMergeWithNewSummary() { var surveyAnswersSummary = new StubSurveyAnswersSummary(); var questionAnswer = new QuestionAnswer { QuestionType = QuestionType.MultipleChoice, QuestionText = "multiple choice", Answer = "choice 1", PossibleAnswers = "possible answers" }; var surveyAnswer = new SurveyAnswer(); surveyAnswer.QuestionAnswers.Add(questionAnswer); surveyAnswersSummary.AddNewAnswer(surveyAnswer); var questionAnswersSummary = surveyAnswersSummary.MergeParameter.QuestionAnswersSummaries.First(); Assert.AreEqual("multiple choice", questionAnswersSummary.QuestionText); Assert.AreEqual("possible answers", questionAnswersSummary.PossibleAnswers); Assert.AreEqual(QuestionType.MultipleChoice, questionAnswersSummary.QuestionType); var actualSummary = new JavaScriptSerializer().Deserialize<Dictionary<string, int>>(questionAnswersSummary.AnswersSummary); Assert.AreEqual(1, actualSummary.Keys.Count); Assert.AreEqual(1, actualSummary["choice 1"]); } [TestMethod] public void MergeCopiesTheNewAnswersSummariesWhenThereAreNoPreviousAnswers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 0 }; var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(new QuestionAnswersSummary()); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(newSurveyAnswersSummary.QuestionAnswersSummaries, existingSurveyAnswersSummary.QuestionAnswersSummaries); } [TestMethod] public void MergeCopiesTotalAnswersWhenThereAreNoPreviousAnswers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 0 }; var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(new QuestionAnswersSummary()); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(1, existingSurveyAnswersSummary.TotalAnswers); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void MergeThrowsWhenTenantsAreNotEqual() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { Tenant = "tenant" }; var newSurveyAnswersSummary = new SurveyAnswersSummary { Tenant = "other tenant" }; existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void MergeThrowsWhenSlugNamesAreNotEqual() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { SlugName = "slug-name" }; var newSurveyAnswersSummary = new SurveyAnswersSummary { SlugName = "other-slug-name" }; existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); } [TestMethod] public void Merge5StarsAnswersCalculatesRatingAverageFor2Answers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var existingQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.FiveStars, AnswersSummary = "1", QuestionText = "question to merge" }; existingSurveyAnswersSummary.QuestionAnswersSummaries.Add(existingQuestionAnswersSummary); var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var newQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.FiveStars, AnswersSummary = "2", QuestionText = "question to merge" }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(newQuestionAnswersSummary); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(2, existingSurveyAnswersSummary.TotalAnswers); Assert.AreEqual(1, existingSurveyAnswersSummary.QuestionAnswersSummaries.Count); var questionAnswersSummary = existingSurveyAnswersSummary.QuestionAnswersSummaries.First(); Assert.AreEqual("question to merge", questionAnswersSummary.QuestionText); Assert.AreEqual(QuestionType.FiveStars, questionAnswersSummary.QuestionType); Assert.AreEqual("1.50", questionAnswersSummary.AnswersSummary); } [TestMethod] public void Merge5StarsAnswersCalculatesRatingAverageFor3Answers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 2 }; var existingQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.FiveStars, AnswersSummary = "1", QuestionText = "question to merge" }; existingSurveyAnswersSummary.QuestionAnswersSummaries.Add(existingQuestionAnswersSummary); var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var newQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.FiveStars, AnswersSummary = "2", QuestionText = "question to merge" }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(newQuestionAnswersSummary); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(3, existingSurveyAnswersSummary.TotalAnswers); Assert.AreEqual(1, existingSurveyAnswersSummary.QuestionAnswersSummaries.Count); var questionAnswersSummary = existingSurveyAnswersSummary.QuestionAnswersSummaries.First(); Assert.AreEqual("question to merge", questionAnswersSummary.QuestionText); Assert.AreEqual(QuestionType.FiveStars, questionAnswersSummary.QuestionType); Assert.AreEqual("1.33", questionAnswersSummary.AnswersSummary); } [TestMethod] public void MergeMultipleChoiceAnswersFor2DifferentAnswers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var existingQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.MultipleChoice, AnswersSummary = new JavaScriptSerializer().Serialize(new Dictionary<string, int> { { "choice 1", 1 } }), QuestionText = "question to merge" }; existingSurveyAnswersSummary.QuestionAnswersSummaries.Add(existingQuestionAnswersSummary); var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var newQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.MultipleChoice, AnswersSummary = new JavaScriptSerializer().Serialize(new Dictionary<string, int> { { "choice 2", 1 } }), QuestionText = "question to merge" }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(newQuestionAnswersSummary); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(2, existingSurveyAnswersSummary.TotalAnswers); Assert.AreEqual(1, existingSurveyAnswersSummary.QuestionAnswersSummaries.Count); var questionAnswersSummary = existingSurveyAnswersSummary.QuestionAnswersSummaries.First(); Assert.AreEqual("question to merge", questionAnswersSummary.QuestionText); Assert.AreEqual(QuestionType.MultipleChoice, questionAnswersSummary.QuestionType); var actualSummary = new JavaScriptSerializer().Deserialize<Dictionary<string, int>>(questionAnswersSummary.AnswersSummary); Assert.AreEqual(2, actualSummary.Keys.Count); Assert.AreEqual(1, actualSummary["choice 1"]); Assert.AreEqual(1, actualSummary["choice 2"]); } [TestMethod] public void MergeMultipleChoiceAnswersFor2SameAnswers() { var existingSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var existingQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.MultipleChoice, AnswersSummary = new JavaScriptSerializer().Serialize(new Dictionary<string, int> { { "choice 1", 1 } }), QuestionText = "question to merge" }; existingSurveyAnswersSummary.QuestionAnswersSummaries.Add(existingQuestionAnswersSummary); var newSurveyAnswersSummary = new SurveyAnswersSummary { TotalAnswers = 1 }; var newQuestionAnswersSummary = new QuestionAnswersSummary { QuestionType = QuestionType.MultipleChoice, AnswersSummary = new JavaScriptSerializer().Serialize(new Dictionary<string, int> { { "choice 1", 1 } }), QuestionText = "question to merge" }; newSurveyAnswersSummary.QuestionAnswersSummaries.Add(newQuestionAnswersSummary); existingSurveyAnswersSummary.MergeWith(newSurveyAnswersSummary); Assert.AreEqual(2, existingSurveyAnswersSummary.TotalAnswers); Assert.AreEqual(1, existingSurveyAnswersSummary.QuestionAnswersSummaries.Count); var questionAnswersSummary = existingSurveyAnswersSummary.QuestionAnswersSummaries.First(); Assert.AreEqual("question to merge", questionAnswersSummary.QuestionText); Assert.AreEqual(QuestionType.MultipleChoice, questionAnswersSummary.QuestionType); var actualSummary = new JavaScriptSerializer().Deserialize<Dictionary<string, int>>(questionAnswersSummary.AnswersSummary); Assert.AreEqual(1, actualSummary.Keys.Count); Assert.AreEqual(2, actualSummary["choice 1"]); } public class StubSurveyAnswersSummary : SurveyAnswersSummary { public SurveyAnswersSummary MergeParameter { get; set; } public override void MergeWith(SurveyAnswersSummary surveyAnswersSummary) { this.MergeParameter = surveyAnswersSummary; } } } }
43.358804
135
0.644855
[ "MIT" ]
msajidirfan/cloud-services-to-service-fabric
cloudservice/SourceCode/Tailspin/Tailspin.Web.Survey.Shared.Tests/Models/SurveyAnswersSummaryFixture.cs
13,053
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.School_Classes { public class Student : Human { private int grade; // Constructors public Student (int grade) { this.Grade = grade; } #region Properties public int Grade { get { return this.grade; } set { if (value < 2 || value > 6) { throw new Exception("student grade must be between 2 and 6"); } this.grade = value; } } #endregion } }
19.205128
81
0.455274
[ "MIT" ]
ekov1/TelerikAcademy-Exercises
alpha/C# OOP/OOP Principles - Part 1/01. School Classes/Student.cs
751
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MattEland.Shared.WPF.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MattEland.Shared.WPF.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.888889
186
0.611212
[ "MIT" ]
IntegerMan/MattEland.Shared
MattEland.Shared.WPF/Properties/Resources.Designer.cs
2,767
C#
using pst.encodables.ndb.blocks.subnode; using pst.interfaces; using pst.utilities; namespace pst.impl.ndb.subnodebtree { class SLEntriesFromSubnodeBlockExtractor : IExtractor<SubnodeBlock, SLEntry[]> { private readonly IDecoder<SLEntry> slEntryDecoder; public SLEntriesFromSubnodeBlockExtractor(IDecoder<SLEntry> slEntryDecoder) { this.slEntryDecoder = slEntryDecoder; } public SLEntry[] Extract(SubnodeBlock parameter) { return slEntryDecoder.DecodeMultipleItems(parameter.NumberOfEntries, 24, parameter.Entries); } } }
28.090909
104
0.703883
[ "MIT" ]
Clancey/PST
pst/pst/impl/ndb/subnodebtree/SLEntriesFromSubnodeBlockExtractor.cs
620
C#
using UnityEngine; using UnityEngine.UI; using MyBox; public class MaxScoreSlider : MonoBehaviour { [SerializeField, Tooltip("The slider when selected the max score"), MustBeAssigned] private Slider maxScoreSlider; [SerializeField, Tooltip("The text to show the currently selected max score"), MustBeAssigned] private Text maxScoreText; private void Awake() { int startSliderValueInt = (int)maxScoreSlider.value; maxScoreText.text = startSliderValueInt.ToString(); GlobalProperties.MaxScore = startSliderValueInt; maxScoreSlider.onValueChanged.AddListener(OnSliderValueChanged); } private void OnSliderValueChanged(float newValue) { int newValueInt = (int)newValue; maxScoreText.text = newValueInt.ToString(); GlobalProperties.MaxScore = newValueInt; } }
28.433333
98
0.725674
[ "MIT" ]
Kaynn-Cahya/SnapSlap
SnapSlap/Assets/Scripts/MaxScoreSlider.cs
855
C#
using System; using Kunicardus.Billboards.Core.ViewModels; using UIKit; using CoreGraphics; using HomeKit; using System.Collections.Generic; using Foundation; namespace iCunOS.BillBoards { public class AdViewCollection : UIView { // AdsListViewModel _viewModel; // AdView _oldAdView; // UIScrollView _scrollView; // CGRect _frame; // List<AdView> _adViews; public AdViewCollection (CGRect frame, AdsListViewModel viewModel, nfloat statusBarHeight) : base (frame) { // _viewModel = viewModel; // _frame = frame; // _adViews = new List<AdView> (); // _scrollView = new UIScrollView (new CGRect (0, 0, _frame.Width, _frame.Height)); // _scrollView.DecelerationRate = UIScrollView.DecelerationRateFast; // nfloat contentWidth = 0f; // for (int i = 0; i < _viewModel.Advertisments.Count; i++) { // // //adding advertisements // AdViewWrapper wrapper = new AdViewWrapper (new CGRect ((i * _frame.Width), 0, _frame.Width, _frame.Height), _viewModel.Advertisments [i]); // wrapper.Adview = new AdView (new CGRect (new CGPoint ((_frame.Width - AdView.DefaultSize.Width) / 2.0f, // (Frame.Height - AdView.DefaultSize.Height - statusBarHeight) / 2.0f // ), AdView.DefaultSize)); // // _adViews.Add (wrapper.Adview); // wrapper.AddSubview (wrapper.Adview); // // wrapper.Adview.IsActive |= i == 0; // // _scrollView.AddSubview (wrapper); // if (i == _viewModel.Advertisments.Count - 1) // contentWidth = wrapper.Frame.Right; // } // // _scrollView.ContentSize = new CGSize (contentWidth, frame.Height); // AddSubview (_scrollView); } } }
31.134615
144
0.688079
[ "MIT" ]
nininea2/unicard_app_base
Kunicardus.Billboards/iCunOS-BillBoards/VIews/Ads/AdViewCollection.cs
1,621
C#
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // TargetFrameworkVersion = 4.51 #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data; using System.Data.SqlClient; using System.Data.Entity.ModelConfiguration; using System.Threading; using System.Threading.Tasks; using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption; namespace PPDatabase { [GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.13.1.0")] public class FakeMyDbContext : IMyDbContext { public IDbSet<Estimation> Estimations { get; set; } public IDbSet<Round> Rounds { get; set; } public IDbSet<Table> Tables { get; set; } public IDbSet<User> Users { get; set; } public FakeMyDbContext() { Estimations = new FakeDbSet<Estimation>(); Rounds = new FakeDbSet<Round>(); Tables = new FakeDbSet<Table>(); Users = new FakeDbSet<User>(); } public int SaveChanges() { return 0; } public Task<int> SaveChangesAsync() { throw new NotImplementedException(); } public Task<int> SaveChangesAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); } // Stored Procedures } }
30.028571
102
0.650809
[ "MIT" ]
ignatandrei/MVCPlanningPoker
PlanningPoker2013/PPDatabase/FakeMyDbContext.cs
2,102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fhwk.Core.Tests.Model.ConfigModel { /// <summary> /// A base entity /// </summary> public class BaseEntityC { /// <summary> /// Gets the entity ID /// </summary> public virtual int ID { get; protected set; } } }
19.8
53
0.611111
[ "Apache-2.0" ]
HomeroThompson/firehawk
Source/Firehawk/Firehawk.Core.Tests/Model/ConfigModel/BaseEntityC.cs
398
C#
using App.Domain.Entities.Users; using DapperExtensions.Mapper; namespace App.Domain.DataRepository._Db { /// <summary> /// Mapping for user table /// </summary> public class UserMapper : ClassMapper<User> { public UserMapper() { Table("User"); Map(x => x.Company).Ignore(); Map(x => x.CompanyId).Ignore(); AutoMap(); } } }
22.157895
47
0.541568
[ "MIT" ]
EmitKnowledge/Signals-Boilerplate
20 Domain/23 Repository/App.Domain.DataRepository/_Db/DbMaps.cs
423
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1010_9fa6-e422bb07")] public void Method_1010_9fa6() { ii(0x1010_9fa6, 5); push(0x64); /* push 0x64 */ ii(0x1010_9fab, 5); call(Definitions.sys_check_available_stack_size, 0x5_bda2);/* call 0x10165d52 */ ii(0x1010_9fb0, 1); push(ebx); /* push ebx */ ii(0x1010_9fb1, 1); push(ecx); /* push ecx */ ii(0x1010_9fb2, 1); push(esi); /* push esi */ ii(0x1010_9fb3, 1); push(edi); /* push edi */ ii(0x1010_9fb4, 1); push(ebp); /* push ebp */ ii(0x1010_9fb5, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x1010_9fb7, 6); sub(esp, 0x3c); /* sub esp, 0x3c */ ii(0x1010_9fbd, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x1010_9fc0, 3); mov(memb[ss, ebp - 4], dl); /* mov [ebp-0x4], dl */ ii(0x1010_9fc3, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_9fc7, 3); imul(eax, eax, 0x18); /* imul eax, eax, 0x18 */ ii(0x1010_9fca, 5); mov(edx, 0x101b_a0e4); /* mov edx, 0x101ba0e4 */ ii(0x1010_9fcf, 2); add(edx, eax); /* add edx, eax */ ii(0x1010_9fd1, 3); mov(memd[ss, ebp - 12], edx); /* mov [ebp-0xc], edx */ ii(0x1010_9fd4, 4); cmp(memb[ss, ebp - 4], 0x30); /* cmp byte [ebp-0x4], 0x30 */ ii(0x1010_9fd8, 2); if(jl(0x1010_9fe6, 0xc)) goto l_0x1010_9fe6;/* jl 0x10109fe6 */ ii(0x1010_9fda, 5); mov(eax, 1); /* mov eax, 0x1 */ ii(0x1010_9fdf, 5); call(/* sys */ 0x1016_a24c, 0x6_0268);/* call 0x1016a24c */ ii(0x1010_9fe4, 2); jmp(0x1010_9ff0, 0xa); goto l_0x1010_9ff0;/* jmp 0x10109ff0 */ l_0x1010_9fe6: ii(0x1010_9fe6, 5); mov(eax, 5); /* mov eax, 0x5 */ ii(0x1010_9feb, 5); call(/* sys */ 0x1016_a24c, 0x6_025c);/* call 0x1016a24c */ l_0x1010_9ff0: ii(0x1010_9ff0, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_9ff3, 5); cmp(memw[ds, eax + 8], -1 /* 0xff */);/* cmp word [eax+0x8], 0xffff */ ii(0x1010_9ff8, 2); if(jz(0x1010_a007, 0xd)) goto l_0x1010_a007;/* jz 0x1010a007 */ ii(0x1010_9ffa, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_9ffd, 4); cmp(memd[ds, eax + 10], 0); /* cmp dword [eax+0xa], 0x0 */ ii(0x1010_a001, 6); if(jnz(0x1010_a0af, 0xa8)) goto l_0x1010_a0af;/* jnz 0x1010a0af */ l_0x1010_a007: ii(0x1010_a007, 5); mov(eax, 0x38); /* mov eax, 0x38 */ ii(0x1010_a00c, 5); call(Definitions.sys_new, 0x5_bdef); /* call 0x10165e00 */ ii(0x1010_a011, 3); mov(memd[ss, ebp - 16], eax); /* mov [ebp-0x10], eax */ ii(0x1010_a014, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x1010_a017, 3); mov(memd[ss, ebp - 20], eax); /* mov [ebp-0x14], eax */ ii(0x1010_a01a, 4); cmp(memd[ss, ebp - 20], 0); /* cmp dword [ebp-0x14], 0x0 */ ii(0x1010_a01e, 2); if(jz(0x1010_a061, 0x41)) goto l_0x1010_a061;/* jz 0x1010a061 */ ii(0x1010_a020, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a023, 4); mov(ax, memw[ds, eax + 6]); /* mov ax, [eax+0x6] */ ii(0x1010_a027, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */ ii(0x1010_a02a, 4); sub(ax, memw[ds, edx + 2]); /* sub ax, [edx+0x2] */ ii(0x1010_a02e, 1); cwde(); /* cwde */ ii(0x1010_a02f, 1); push(eax); /* push eax */ ii(0x1010_a030, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a033, 4); mov(ax, memw[ds, eax + 4]); /* mov ax, [eax+0x4] */ ii(0x1010_a037, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */ ii(0x1010_a03a, 3); sub(ax, memw[ds, edx]); /* sub ax, [edx] */ ii(0x1010_a03d, 3); movsx(ecx, ax); /* movsx ecx, ax */ ii(0x1010_a040, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a043, 2); mov(ebx, memd[ds, eax]); /* mov ebx, [eax] */ ii(0x1010_a045, 3); sar(ebx, 0x10); /* sar ebx, 0x10 */ ii(0x1010_a048, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a04b, 3); movsx(edx, memw[ds, eax]); /* movsx edx, word [eax] */ ii(0x1010_a04e, 3); mov(eax, memd[ss, ebp - 16]); /* mov eax, [ebp-0x10] */ ii(0x1010_a051, 5); call(0x100c_e39d, -0x3_bcb9); /* call 0x100ce39d */ ii(0x1010_a056, 3); mov(memd[ss, ebp - 24], eax); /* mov [ebp-0x18], eax */ ii(0x1010_a059, 3); mov(eax, memd[ss, ebp - 24]); /* mov eax, [ebp-0x18] */ ii(0x1010_a05c, 3); mov(memd[ss, ebp - 28], eax); /* mov [ebp-0x1c], eax */ ii(0x1010_a05f, 2); jmp(0x1010_a067, 6); goto l_0x1010_a067;/* jmp 0x1010a067 */ l_0x1010_a061: ii(0x1010_a061, 3); mov(eax, memd[ss, ebp - 20]); /* mov eax, [ebp-0x14] */ ii(0x1010_a064, 3); mov(memd[ss, ebp - 28], eax); /* mov [ebp-0x1c], eax */ l_0x1010_a067: ii(0x1010_a067, 4); movsx(edx, memb[ss, ebp - 4]); /* movsx edx, byte [ebp-0x4] */ ii(0x1010_a06b, 3); shl(edx, 2); /* shl edx, 0x2 */ ii(0x1010_a06e, 3); add(edx, memd[ss, ebp - 8]); /* add edx, [ebp-0x8] */ ii(0x1010_a071, 3); mov(eax, memd[ss, ebp - 28]); /* mov eax, [ebp-0x1c] */ ii(0x1010_a074, 6); mov(memd[ds, edx + 629], eax); /* mov [edx+0x275], eax */ ii(0x1010_a07a, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a07d, 5); cmp(memw[ds, eax + 8], -1 /* 0xff */);/* cmp word [eax+0x8], 0xffff */ ii(0x1010_a082, 2); if(jz(0x1010_a0aa, 0x26)) goto l_0x1010_a0aa;/* jz 0x1010a0aa */ ii(0x1010_a084, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x1010_a087, 2); push(memd[ds, eax]); /* push dword [eax] */ ii(0x1010_a089, 5); mov(ecx, 1); /* mov ecx, 0x1 */ ii(0x1010_a08e, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a091, 2); mov(ebx, memd[ds, eax]); /* mov ebx, [eax] */ ii(0x1010_a093, 3); sar(ebx, 0x10); /* sar ebx, 0x10 */ ii(0x1010_a096, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a099, 3); movsx(edx, memw[ds, eax]); /* movsx edx, word [eax] */ ii(0x1010_a09c, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a09f, 3); mov(eax, memd[ds, eax + 6]); /* mov eax, [eax+0x6] */ ii(0x1010_a0a2, 3); sar(eax, 0x10); /* sar eax, 0x10 */ ii(0x1010_a0a5, 5); call(0x100e_8ef1, -0x2_11b9); /* call 0x100e8ef1 */ l_0x1010_a0aa: ii(0x1010_a0aa, 5); jmp(0x1010_a16f, 0xc0); goto l_0x1010_a16f;/* jmp 0x1010a16f */ l_0x1010_a0af: ii(0x1010_a0af, 5); mov(eax, 0x38); /* mov eax, 0x38 */ ii(0x1010_a0b4, 5); call(Definitions.sys_new, 0x5_bd47); /* call 0x10165e00 */ ii(0x1010_a0b9, 3); mov(memd[ss, ebp - 32], eax); /* mov [ebp-0x20], eax */ ii(0x1010_a0bc, 3); mov(eax, memd[ss, ebp - 32]); /* mov eax, [ebp-0x20] */ ii(0x1010_a0bf, 3); mov(memd[ss, ebp - 36], eax); /* mov [ebp-0x24], eax */ ii(0x1010_a0c2, 4); cmp(memd[ss, ebp - 36], 0); /* cmp dword [ebp-0x24], 0x0 */ ii(0x1010_a0c6, 2); if(jz(0x1010_a0fe, 0x36)) goto l_0x1010_a0fe;/* jz 0x1010a0fe */ ii(0x1010_a0c8, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a0cb, 2); mov(eax, memd[ds, eax]); /* mov eax, [eax] */ ii(0x1010_a0cd, 3); sar(eax, 0x10); /* sar eax, 0x10 */ ii(0x1010_a0d0, 1); push(eax); /* push eax */ ii(0x1010_a0d1, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a0d4, 3); movsx(ecx, memw[ds, eax]); /* movsx ecx, word [eax] */ ii(0x1010_a0d7, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a0da, 4); mov(ax, memw[ds, eax + 8]); /* mov ax, [eax+0x8] */ ii(0x1010_a0de, 1); inc(eax); /* inc eax */ ii(0x1010_a0df, 3); movsx(ebx, ax); /* movsx ebx, ax */ ii(0x1010_a0e2, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a0e5, 3); mov(edx, memd[ds, eax + 6]); /* mov edx, [eax+0x6] */ ii(0x1010_a0e8, 3); sar(edx, 0x10); /* sar edx, 0x10 */ ii(0x1010_a0eb, 3); mov(eax, memd[ss, ebp - 32]); /* mov eax, [ebp-0x20] */ ii(0x1010_a0ee, 5); call(Definitions.my_ctor_c17, -0x3_bce4);/* call 0x100ce40f */ ii(0x1010_a0f3, 3); mov(memd[ss, ebp - 40], eax); /* mov [ebp-0x28], eax */ ii(0x1010_a0f6, 3); mov(eax, memd[ss, ebp - 40]); /* mov eax, [ebp-0x28] */ ii(0x1010_a0f9, 3); mov(memd[ss, ebp - 44], eax); /* mov [ebp-0x2c], eax */ ii(0x1010_a0fc, 2); jmp(0x1010_a104, 6); goto l_0x1010_a104;/* jmp 0x1010a104 */ l_0x1010_a0fe: ii(0x1010_a0fe, 3); mov(eax, memd[ss, ebp - 36]); /* mov eax, [ebp-0x24] */ ii(0x1010_a101, 3); mov(memd[ss, ebp - 44], eax); /* mov [ebp-0x2c], eax */ l_0x1010_a104: ii(0x1010_a104, 4); movsx(edx, memb[ss, ebp - 4]); /* movsx edx, byte [ebp-0x4] */ ii(0x1010_a108, 3); shl(edx, 2); /* shl edx, 0x2 */ ii(0x1010_a10b, 3); add(edx, memd[ss, ebp - 8]); /* add edx, [ebp-0x8] */ ii(0x1010_a10e, 3); mov(eax, memd[ss, ebp - 44]); /* mov eax, [ebp-0x2c] */ ii(0x1010_a111, 6); mov(memd[ds, edx + 629], eax); /* mov [edx+0x275], eax */ ii(0x1010_a117, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a11a, 4); cmp(memd[ds, eax + 10], 0); /* cmp dword [eax+0xa], 0x0 */ ii(0x1010_a11e, 2); if(jz(0x1010_a16f, 0x4f)) goto l_0x1010_a16f;/* jz 0x1010a16f */ ii(0x1010_a120, 3); lea(eax, memd[ss, ebp - 48]); /* lea eax, [ebp-0x30] */ ii(0x1010_a123, 5); call(0x100d_5224, -0x3_4f04); /* call 0x100d5224 */ ii(0x1010_a128, 1); push(eax); /* push eax */ ii(0x1010_a129, 3); lea(eax, memd[ss, ebp - 52]); /* lea eax, [ebp-0x34] */ ii(0x1010_a12c, 5); call(0x100d_5250, -0x3_4ee1); /* call 0x100d5250 */ ii(0x1010_a131, 1); push(eax); /* push eax */ ii(0x1010_a132, 3); lea(eax, memd[ss, ebp - 56]); /* lea eax, [ebp-0x38] */ ii(0x1010_a135, 5); call(0x100d_527c, -0x3_4ebe); /* call 0x100d527c */ ii(0x1010_a13a, 1); push(eax); /* push eax */ ii(0x1010_a13b, 3); lea(eax, memd[ss, ebp - 60]); /* lea eax, [ebp-0x3c] */ ii(0x1010_a13e, 5); call(0x100d_52a8, -0x3_4e9b); /* call 0x100d52a8 */ ii(0x1010_a143, 1); push(eax); /* push eax */ ii(0x1010_a144, 5); call(0x100d_52d4, -0x3_4e75); /* call 0x100d52d4 */ ii(0x1010_a149, 3); movsx(ecx, ax); /* movsx ecx, ax */ ii(0x1010_a14c, 5); call(0x100d_52f8, -0x3_4e59); /* call 0x100d52f8 */ ii(0x1010_a151, 3); movsx(ebx, ax); /* movsx ebx, ax */ ii(0x1010_a154, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x1010_a157, 3); mov(edx, memd[ds, eax + 10]); /* mov edx, [eax+0xa] */ ii(0x1010_a15a, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a15e, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a161, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a164, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a16a, 5); call(0x100c_ef64, -0x3_b20b); /* call 0x100cef64 */ l_0x1010_a16f: ii(0x1010_a16f, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1010_a171, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a175, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a178, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a17b, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a181, 5); call(0x100d_5194, -0x3_4ff2); /* call 0x100d5194 */ ii(0x1010_a186, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a18a, 6); lea(edx, memd[ds, eax + 1000]); /* lea edx, [eax+0x3e8] */ ii(0x1010_a190, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a194, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a197, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a19a, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a1a0, 5); call(0x100d_5134, -0x3_5071); /* call 0x100d5134 */ ii(0x1010_a1a5, 4); movsx(edx, memb[ss, ebp - 4]); /* movsx edx, byte [ebp-0x4] */ ii(0x1010_a1a9, 6); add(edx, 0x7000); /* add edx, 0x7000 */ ii(0x1010_a1af, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a1b3, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a1b6, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a1b9, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a1bf, 5); call(0x100d_5164, -0x3_5060); /* call 0x100d5164 */ ii(0x1010_a1c4, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */ ii(0x1010_a1c7, 3); mov(edx, memd[ds, edx + 20]); /* mov edx, [edx+0x14] */ ii(0x1010_a1ca, 3); sar(edx, 0x10); /* sar edx, 0x10 */ ii(0x1010_a1cd, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a1d1, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a1d4, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a1d7, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a1dd, 5); call(0x100d_50d4, -0x3_510e); /* call 0x100d50d4 */ ii(0x1010_a1e2, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x1010_a1e5, 2); mov(eax, memd[ds, eax]); /* mov eax, [eax] */ ii(0x1010_a1e7, 3); mov(edx, memd[ds, eax + 18]); /* mov edx, [eax+0x12] */ ii(0x1010_a1ea, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a1ee, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a1f1, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a1f4, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a1fa, 5); call(0x100c_f85c, -0x3_a9a3); /* call 0x100cf85c */ ii(0x1010_a1ff, 5); call(0x100d_51e4, -0x3_5020); /* call 0x100d51e4 */ ii(0x1010_a204, 2); xor(ebx, ebx); /* xor ebx, ebx */ ii(0x1010_a206, 2); mov(bl, al); /* mov bl, al */ ii(0x1010_a208, 5); call(0x100d_5204, -0x3_5009); /* call 0x100d5204 */ ii(0x1010_a20d, 2); xor(edx, edx); /* xor edx, edx */ ii(0x1010_a20f, 2); mov(dl, al); /* mov dl, al */ ii(0x1010_a211, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a215, 3); shl(eax, 2); /* shl eax, 0x2 */ ii(0x1010_a218, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a21b, 6); mov(eax, memd[ds, eax + 629]); /* mov eax, [eax+0x275] */ ii(0x1010_a221, 5); call(0x100c_fa7c, -0x3_a7aa); /* call 0x100cfa7c */ ii(0x1010_a226, 4); movsx(edx, memb[ss, ebp - 4]); /* movsx edx, byte [ebp-0x4] */ ii(0x1010_a22a, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a22e, 3); imul(eax, eax, 0xc); /* imul eax, eax, 0xc */ ii(0x1010_a231, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a234, 6); add(edx, 0x3e8); /* add edx, 0x3e8 */ ii(0x1010_a23a, 3); mov(memd[ds, eax + 17], edx); /* mov [eax+0x11], edx */ ii(0x1010_a23d, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a241, 3); imul(eax, eax, 0xc); /* imul eax, eax, 0xc */ ii(0x1010_a244, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a247, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */ ii(0x1010_a24a, 3); mov(edx, memd[ds, edx + 14]); /* mov edx, [edx+0xe] */ ii(0x1010_a24d, 3); mov(memd[ds, eax + 21], edx); /* mov [eax+0x15], edx */ ii(0x1010_a250, 4); movsx(eax, memb[ss, ebp - 4]); /* movsx eax, byte [ebp-0x4] */ ii(0x1010_a254, 3); imul(eax, eax, 0xc); /* imul eax, eax, 0xc */ ii(0x1010_a257, 3); add(eax, memd[ss, ebp - 8]); /* add eax, [ebp-0x8] */ ii(0x1010_a25a, 3); mov(edx, memd[ss, ebp - 12]); /* mov edx, [ebp-0xc] */ ii(0x1010_a25d, 3); mov(edx, memd[ds, edx + 18]); /* mov edx, [edx+0x12] */ ii(0x1010_a260, 3); mov(memd[ds, eax + 25], edx); /* mov [eax+0x19], edx */ ii(0x1010_a263, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x1010_a265, 1); pop(ebp); /* pop ebp */ ii(0x1010_a266, 1); pop(edi); /* pop edi */ ii(0x1010_a267, 1); pop(esi); /* pop esi */ ii(0x1010_a268, 1); pop(ecx); /* pop ecx */ ii(0x1010_a269, 1); pop(ebx); /* pop ebx */ ii(0x1010_a26a, 1); ret(); /* ret */ } } }
88.237288
114
0.446936
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1010-9fa6.cs
20,824
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("Chapter 9")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Chapter 9")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("e73699a6-fbf1-408d-8494-7623530f68e3")] // 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.459459
84
0.74531
[ "MIT" ]
jbhalla86/Programming-in-C-Sharp-Exam-70-483-MCSD-Guide
Book70483Samples/Chapter 9/Properties/AssemblyInfo.cs
1,389
C#
using Main; using System.Collections.Generic; using System.IO; using System.Linq; using Utilities; using Xunit; namespace Tests.AlgorithmsTests.Observers { public class VertexDistanceObsTests { [Theory] [MemberData(nameof(GetInputFiles))] public void Test0(string inputFile) { string directory = Path.GetDirectoryName(inputFile); string file = Path.GetFileNameWithoutExtension(inputFile); var outputFile = @$"{directory}\Observers\VertexDistance\{file}"; var expectedfile = @$"{outputFile}.a"; var resultsfile = $"{outputFile}.r"; List<string> inputs = File.ReadAllLines(inputFile).ToList(); inputs = Parser.RemoveComments(inputs); var nodes = inputs[0].Split(' ').ToList(); // First line is a space delimited list of node names: "1 2 3" or "a b c" // Remove line of node name inputs.RemoveAt(0); List<List<string>> edges = new List<List<string>>(); foreach (var e in inputs) { edges.Add(e.Split(' ').ToList()); // Remaining lines are space delimited list of edges (nodeA nodeB tag(optional)): "1 2" or "a b 5" } List<string> actual = ObserverHelper.VertexDistance(nodes, edges); File.WriteAllLines(resultsfile, actual); // Verify results List<string> expected = File.ReadAllLines(expectedfile).ToList(); Assert.Equal(expected.Count, actual.Count); for (int i = 0; i < expected.Count; i++) { Assert.Equal(expected[i], actual[i]); } } public static IEnumerable<object[]> GetInputFiles => new List<object[]> { new object[] { new string(@"..\..\..\Cases\01") }, new object[] { new string(@"..\..\..\Cases\02") }, new object[] { new string(@"..\..\..\Cases\03") }, new object[] { new string(@"..\..\..\Cases\04") }, }; } }
37.196429
149
0.550648
[ "MIT" ]
TXCodeDancer/OpenSource
Demos/QuikGraph/Tests/AlgorithmsTests/Observers/VertexDistanceObsTests.cs
2,085
C#
/* Copyright (C) 2018. Hitomi Parser Developers */ using System.Drawing; namespace Hitomi_Copy_3.VUI { public class VUIButton : VUIControl { public Font Font { get; set; } public string Text { get; set; } public VUIButton() { MouseMoveEvent = mouse_move_action; MouseLeaveEvent = mouse_leave_action; } bool hover = false; private void mouse_move_action() { hover = true; } private void mouse_leave_action() { hover = false; } public override void Paint(Graphics g) { var button = new MetroFramework.Controls.MetroButton(); button.Location = Location; button.Size = Size; button.Text = Text; button.UseSelectable = true; Bitmap bim = new Bitmap(Size.Width, Size.Height); button.DrawToBitmap(bim, new Rectangle(0, 0, Size.Width, Size.Height)); g.DrawImage(bim, Location); button.Dispose(); } } }
25.904762
83
0.546875
[ "MIT" ]
dc-koromo/hitomi-copy
Hitomi Copy 3/VUI/VUIButton.cs
1,090
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace AzureB2CFunctions { public static class HttpExample { [FunctionName("HttpExample")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["name"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; string responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $"Hello, {name}. This HTTP triggered function executed successfully."; return new OkObjectResult(responseMessage); } } }
33.710526
155
0.671351
[ "Apache-2.0" ]
rbrayb/AzureB2CFunctions
AzureB2CFunctions/HttpExample.cs
1,281
C#
using EngineeringUnits.Units; using System.Collections.Generic; using System; namespace EngineeringUnits { public partial class Irradiance { /// <summary> /// Get from SI Unit. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> //public static Irradiance FromSI(double si) //{ // double value = (double)si; // return new Irradiance(value, IrradianceUnit.SI); //} /// <summary> /// Get Irradiance from KilowattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromKilowattsPerSquareCentimeter->FromKilowattPerSquareCentimeter")] public static Irradiance FromKilowattsPerSquareCentimeter(double kilowattspersquarecentimeter) { double value = (double)kilowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.KilowattPerSquareCentimeter); } /// <summary> /// Get Irradiance from KilowattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromKilowattsPerSquareMeter->FromKilowattPerSquareMeter")] public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) { double value = (double)kilowattspersquaremeter; return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); } /// <summary> /// Get Irradiance from MegawattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMegawattsPerSquareCentimeter->FromMegawattPerSquareCentimeter")] public static Irradiance FromMegawattsPerSquareCentimeter(double megawattspersquarecentimeter) { double value = (double)megawattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MegawattPerSquareCentimeter); } /// <summary> /// Get Irradiance from MegawattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMegawattsPerSquareMeter->FromMegawattPerSquareMeter")] public static Irradiance FromMegawattsPerSquareMeter(double megawattspersquaremeter) { double value = (double)megawattspersquaremeter; return new Irradiance(value, IrradianceUnit.MegawattPerSquareMeter); } /// <summary> /// Get Irradiance from MicrowattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMicrowattsPerSquareCentimeter->FromMicrowattPerSquareCentimeter")] public static Irradiance FromMicrowattsPerSquareCentimeter(double microwattspersquarecentimeter) { double value = (double)microwattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MicrowattPerSquareCentimeter); } /// <summary> /// Get Irradiance from MicrowattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMicrowattsPerSquareMeter->FromMicrowattPerSquareMeter")] public static Irradiance FromMicrowattsPerSquareMeter(double microwattspersquaremeter) { double value = (double)microwattspersquaremeter; return new Irradiance(value, IrradianceUnit.MicrowattPerSquareMeter); } /// <summary> /// Get Irradiance from MilliwattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMilliwattsPerSquareCentimeter->FromMilliwattPerSquareCentimeter")] public static Irradiance FromMilliwattsPerSquareCentimeter(double milliwattspersquarecentimeter) { double value = (double)milliwattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.MilliwattPerSquareCentimeter); } /// <summary> /// Get Irradiance from MilliwattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromMilliwattsPerSquareMeter->FromMilliwattPerSquareMeter")] public static Irradiance FromMilliwattsPerSquareMeter(double milliwattspersquaremeter) { double value = (double)milliwattspersquaremeter; return new Irradiance(value, IrradianceUnit.MilliwattPerSquareMeter); } /// <summary> /// Get Irradiance from NanowattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromNanowattsPerSquareCentimeter->FromNanowattPerSquareCentimeter")] public static Irradiance FromNanowattsPerSquareCentimeter(double nanowattspersquarecentimeter) { double value = (double)nanowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.NanowattPerSquareCentimeter); } /// <summary> /// Get Irradiance from NanowattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromNanowattsPerSquareMeter->FromNanowattPerSquareMeter")] public static Irradiance FromNanowattsPerSquareMeter(double nanowattspersquaremeter) { double value = (double)nanowattspersquaremeter; return new Irradiance(value, IrradianceUnit.NanowattPerSquareMeter); } /// <summary> /// Get Irradiance from PicowattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromPicowattsPerSquareCentimeter->FromPicowattPerSquareCentimeter")] public static Irradiance FromPicowattsPerSquareCentimeter(double picowattspersquarecentimeter) { double value = (double)picowattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.PicowattPerSquareCentimeter); } /// <summary> /// Get Irradiance from PicowattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromPicowattsPerSquareMeter->FromPicowattPerSquareMeter")] public static Irradiance FromPicowattsPerSquareMeter(double picowattspersquaremeter) { double value = (double)picowattspersquaremeter; return new Irradiance(value, IrradianceUnit.PicowattPerSquareMeter); } /// <summary> /// Get Irradiance from WattsPerSquareCentimeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromWattsPerSquareCentimeter->FromWattPerSquareCentimeter")] public static Irradiance FromWattsPerSquareCentimeter(double wattspersquarecentimeter) { double value = (double)wattspersquarecentimeter; return new Irradiance(value, IrradianceUnit.WattPerSquareCentimeter); } /// <summary> /// Get Irradiance from WattsPerSquareMeter. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Obsolete("Use without the 's' - FromWattsPerSquareMeter->FromWattPerSquareMeter")] public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) { double value = (double)wattspersquaremeter; return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); } } }
47.926966
111
0.664752
[ "MIT" ]
AtefeBahrani/EngineeringUnits
EngineeringUnits/CombinedUnits/Irradiance/ObsoleteIrradianceSet.cs
8,533
C#
using System; using System.Text.RegularExpressions; namespace Line.Messaging.Webhooks { /// <summary> /// Object with the date and time selected by a user through a datetime picker action. The full-date, time-hour, and time-minute formats follow the RFC3339 protocol. /// </summary> public class PostbackParams { /// <summary> /// Date selected by user. Only included in the date mode. Format: full-date /// </summary> public string Date { get; } /// <summary> /// Time selected by the user. Only included in the time mode. Format: time-hour ":" time-minute /// </summary> public string Time { get; } /// <summary> /// Date and time selected by the user. Only included in the datetime mode. Format: full-date "T" time-hour ":" time-minute /// </summary> public string DateTime { get; } public PostbackParams(string date, string time, string datetime) { if (date != null && !Regex.Match(date, @"^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$").Success) { throw new ArgumentException($"Date format must be \"yyyy-MM-dd\".", nameof(date)); } if (time != null && !Regex.Match(time, @"^([01][0-9]|2[0-3]):([0-5][0-9])$").Success) { throw new ArgumentException($"Time format must be \"HH:mm\".", nameof(time)); } if (datetime != null && !Regex.Match(datetime, @"^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])$").Success) { throw new ArgumentException("Date-Time format must be \"yyyy-MM-ddTHH:mm\".", nameof(datetime)); } Date = date; Time = time; DateTime = datetime; } } }
39.361702
169
0.537838
[ "MIT" ]
EvanceKao/LineMessagingApi
src/Line.Messaging/Webhooks/PostbackParams.cs
1,852
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MVPConf2020 { public partial class App : Application { public App() { InitializeComponent(); MainPage = new NavigationPage(new Views.MainPage()); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
16.413793
64
0.535714
[ "MIT" ]
ricardoprestes/mvpconf2020
src/MVPConf2020/App.xaml.cs
478
C#
using CountryValidation.Countries; using Xunit; namespace CountryValidation.Tests { public class AndorraValidatorTests { private readonly AndorraValidator _andorraValidator; public AndorraValidatorTests() { _andorraValidator = new AndorraValidator(); } [Theory] [InlineData("U-132950-X", true)] [InlineData("A123B", false)] [InlineData("2012345699", false)] [InlineData("D059888N", true)] public void TestNationalId(string code, bool isValid) { Assert.Equal(isValid, _andorraValidator.ValidateNationalIdentity(code).IsValid); } [Theory] [InlineData("U-132950-X", true)] [InlineData("A123B", false)] [InlineData("2012345699", false)] [InlineData("D059888N", true)] public void TestIndividualCode(string code, bool isValid) { Assert.Equal(isValid, _andorraValidator.ValidateIndividualTaxCode(code).IsValid); } [Theory] [InlineData("U-132950-X", true)] [InlineData("A123B", false)] [InlineData("2012345699", false)] [InlineData("D059888N", true)] public void TestCorrectEntityCode(string code, bool isValid) { Assert.Equal(isValid, _andorraValidator.ValidateEntity(code).IsValid); } [Theory] [InlineData("U-132950-X", true)] [InlineData("A123B", false)] [InlineData("2012345699", false)] [InlineData("D059888N", true)] public void TestCorrectVatCode(string code, bool isValid) { Assert.Equal(isValid, _andorraValidator.ValidateVAT(code).IsValid); } } }
30.660714
93
0.610367
[ "Apache-2.0" ]
anghelvalentin/CountryValidator
CountryValidator.Tests/CountriesValidators/AndorraValidatorTests.cs
1,719
C#
using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/express/delivery/open_msg/update_follow_waybill_goods 接口的请求。</para> /// </summary> public class CgibinExpressDeliveryOpenMessageUpdateFollowWaybillGoodsRequest : WechatApiRequest, IMapResponse<CgibinExpressDeliveryOpenMessageUpdateFollowWaybillGoodsRequest, CgibinExpressDeliveryOpenMessageUpdateFollowWaybillGoodsResponse> { public static class Types { public class Goods { public static class Types { public class Detail : CgibinExpressDeliveryOpenMessageFollowWaybillRequest.Types.Goods.Types.Detail { } } /// <summary> /// 获取或设置商品详情列表。 /// </summary> [Newtonsoft.Json.JsonProperty("detail_list")] [System.Text.Json.Serialization.JsonPropertyName("detail_list")] public IList<Types.Detail> DetailList { get; set; } = new List<Types.Detail>(); } } /// <summary> /// 获取或设置用户 OpenId。 /// </summary> [Newtonsoft.Json.JsonProperty("openid")] [System.Text.Json.Serialization.JsonPropertyName("openid")] public string OpenId { get; set; } = string.Empty; /// <summary> /// 获取或设置微信订单查询 Token。 /// </summary> [Newtonsoft.Json.JsonProperty("waybill_token")] [System.Text.Json.Serialization.JsonPropertyName("waybill_token")] public string WaybillToken { get; set; } = string.Empty; /// <summary> /// 获取或设置商品信息。 /// </summary> [Newtonsoft.Json.JsonProperty("goods_info")] [System.Text.Json.Serialization.JsonPropertyName("goods_info")] public Types.Goods? Goods { get; set; } } }
37.269231
244
0.598555
[ "MIT" ]
vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinExpress/Delivery/OpenMessage/CgibinExpressDeliveryOpenMessageUpdateFollowWaybillGoodsRequest.cs
2,040
C#
using System; using GroupDocs.Conversion.Cloud.Sdk.Api; using GroupDocs.Conversion.Cloud.Sdk.Model; using GroupDocs.Conversion.Cloud.Sdk.Model.Requests; namespace GroupDocs.Conversion.Cloud.Examples.CSharp.LoadOptionsByDocumentType.Spreadsheet { /// <summary> /// This example demonstrates how to convert a spreadsheet document to pdf with advanced options /// </summary> public class ConvertSpreadsheetBySkippingEmptyRowsAndColumns { public static void Run() { try { // Create necessary API instances var apiInstance = new ConvertApi(Constants.GetConfig()); // Prepare convert settings var loadOptions = new SpreadsheetLoadOptions { SkipEmptyRowsAndColumns = true, OnePagePerSheet = true }; var settings = new ConvertSettings { StorageName = Constants.MyStorage, FilePath = "Spreadsheet/sample.xlsx", Format = "pdf", LoadOptions = loadOptions, OutputPath = "converted" }; // Convert to specified format var response = apiInstance.ConvertDocument(new ConvertDocumentRequest(settings)); Console.WriteLine("Document converted successfully: " + response[0].Url); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } } }
34.978261
100
0.558732
[ "MIT" ]
groupdocs-conversion-cloud/groupdocs-conversion-cloud-dotnet-samples
Examples/GroupDocs.Conversion.Cloud.Examples.CSharp/LoadOptionsByDocumentType/Spreadsheet/ConvertSpreadsheetBySkippingEmptyRowsAndColumns.cs
1,609
C#
using EntityFramework.Extensions; using ServiceStation.InterfacesView; using ServiceStation.Model; using System; using System.Linq; using System.Threading.Tasks; using System.Data.Entity; namespace ServiceStation.Presenter { internal class PostPresenter : BasePresenter<IEditingPostView, Guid?> { internal PostPresenter(IEditingPostView view) : base(view) { View.Title = string.Concat("Добавление должности сотрудника"); } internal PostPresenter(IEditingPostView view, Guid postID) : base(view, postID) { View.Title = string.Concat("Редактирование должности сотрудника"); } protected override async Task QueryInfo() { try { using (var context = new DbSSContext()) { var result = await context.Post.Where(p => p.ID == (Guid)Identifier).FirstAsync(); View.Post = result.Name; } } catch (Exception ex) { ShowError(ex.Message); } } protected override void SubscribeEvent() { View.Loading += View_Loading; View.Save += async () => await SaveAsync(); } private async Task View_Loading() { if (Query?.Method != null) await Query?.Invoke(); } protected override async Task SaveAsync() { try { var post = View.Post; if (string.IsNullOrWhiteSpace(post)) throw new ArgumentNullException(null, "Вы не ввели должность сотрудника!"); using (var context = new DbSSContext()) { if(Identifier != null) { await context.Post.Where(p => p.ID == (Guid)Identifier).UpdateAsync(p => new PostModel { Name = post }); } else { PostModel insertPostInfo = new PostModel { ID = ConsistentGuid.CreateGuid(), Name = post }; context.Post.Add(insertPostInfo); await context.SaveChangesAsync(); Identifier = insertPostInfo.ID; } } View.Close(); } catch (Exception ex) { ShowError(ex.Message); } } } }
28.154639
110
0.457342
[ "MIT" ]
Scronullik/ServiceStation
ServiceStation/ServiceStation/Presenter/PostPresenter.cs
2,823
C#
using System; using System.Linq; using Arbor.App.Extensions.Configuration; using Arbor.App.Extensions.DependencyInjection; using Arbor.KVConfiguration.Core; using Arbor.KVConfiguration.Urns; using JetBrains.Annotations; using Marten; using Marten.Services; using Microsoft.Extensions.DependencyInjection; using Milou.Deployer.Web.Core; using Milou.Deployer.Web.Core.Deployment; using Milou.Deployer.Web.Core.Deployment.Sources; using Milou.Deployer.Web.Core.Deployment.Targets; using Milou.Deployer.Web.Core.Json; using Milou.Deployer.Web.Marten.DeploymentTasks; using Milou.Deployer.Web.Marten.EnvironmentTypes; namespace Milou.Deployer.Web.Marten { [RegistrationOrder(1000)] [UsedImplicitly] public class MartenModule : IModule { private readonly IKeyValueConfiguration _keyValueConfiguration; public MartenModule([NotNull] IKeyValueConfiguration keyValueConfiguration) { _keyValueConfiguration = keyValueConfiguration ?? throw new ArgumentNullException(nameof(keyValueConfiguration)); } private void ConfigureMarten(StoreOptions options, string connectionString) { options.Connection(connectionString); var jsonNetSerializer = new JsonNetSerializer(); jsonNetSerializer.Customize(serializer => serializer.UseCustomConverters()); options.Serializer(jsonNetSerializer); options.Schema.For<LogItem>().Index(x => x.TaskLogId); options.Schema.For<LogItem>().Index(x => x.Level); } public IServiceCollection Register(IServiceCollection builder) { var configurations = _keyValueConfiguration.GetInstances<MartenConfiguration>(); if (configurations.IsDefaultOrEmpty) { return builder; } if (configurations.Length > 1) { builder.AddSingleton(new MartenConfiguration(string.Empty), this); builder.AddSingleton(new ConfigurationError( $"Expected exactly 1 instance of type {nameof(MartenConfiguration)} but got {configurations.Length}"), this); return builder; } var configuration = configurations.Single(); if (!string.IsNullOrWhiteSpace(configuration.ConnectionString) && configuration.Enabled) { builder.AddSingleton(typeof(MartenStore), this); builder.AddSingleton(typeof(IDeploymentTargetReadService), typeof(MartenStore), this); builder.AddSingleton(typeof(IDeploymentTargetService), typeof(MartenStore), this); builder.AddSingleton<IDeploymentTaskPackageStore, DeploymentTaskPackageStore>(); var genericInterfaces = typeof(MartenStore) .GetInterfaces() .Where(type => type.IsGenericType) .ToArray(); foreach (var genericInterface in genericInterfaces) { builder.Add(new ExtendedServiceDescriptor(genericInterface, typeof(MartenStore), ServiceLifetime.Singleton, GetType())); } builder.AddSingleton<IDocumentStore>(context => DocumentStore.For(options => ConfigureMarten(options, configuration.ConnectionString)), this); } builder.AddSingleton<IEnvironmentTypeService, EnvironmentTypeService>(); return builder; } } }
37.122449
126
0.641561
[ "MIT" ]
milou-se/milou.deployer
src/Milou.Deployer.Web.Marten/MartenModule.cs
3,640
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Vpc.Model.V20160428; namespace Aliyun.Acs.Vpc.Transform.V20160428 { public class ModifyRouterInterfaceSpecResponseUnmarshaller { public static ModifyRouterInterfaceSpecResponse Unmarshall(UnmarshallerContext context) { ModifyRouterInterfaceSpecResponse modifyRouterInterfaceSpecResponse = new ModifyRouterInterfaceSpecResponse(); modifyRouterInterfaceSpecResponse.HttpResponse = context.HttpResponse; modifyRouterInterfaceSpecResponse.RequestId = context.StringValue("ModifyRouterInterfaceSpec.RequestId"); modifyRouterInterfaceSpecResponse.Spec = context.StringValue("ModifyRouterInterfaceSpec.Spec"); return modifyRouterInterfaceSpecResponse; } } }
39.682927
114
0.77689
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-vpc/Vpc/Transform/V20160428/ModifyRouterInterfaceSpecResponseUnmarshaller.cs
1,627
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace McKenna_PracticalExam2 { class Program { static void Main(string[] args) { //calls and gather names Console.WriteLine("Welcome to DICETOWER!\n\nPlease enter Player 1's name:"); string name1 = Console.ReadLine(); Console.WriteLine("\nPlease enter Player 2's name:"); string name2 = Console.ReadLine(); //round number and dice per round and which dice Console.WriteLine("\nWhat kind of dice would you like to roll today? (enter a number of sides)"); int sides = int.Parse(Console.ReadLine()); Console.WriteLine("\nHow many would you like to roll?"); int numberRolled = int.Parse(Console.ReadLine()); Console.WriteLine("\nHow many rounds would you like to play?"); int rounds = int.Parse(Console.ReadLine()); Player Player1 = new Player(name1); Player Player2 = new Player(name2); DiceTower Roller = new DiceTower(); for (int i = 0; i < rounds; i++) { Console.WriteLine("Round " + (i + 1) + "-------------"); Console.WriteLine("\nPlayer 1's turn"); Player1.AddDiceToScore(Roller.GenerateDiceRolls(numberRolled, sides)); Console.WriteLine("\nPlayer 2's turn"); Player2.AddDiceToScore(Roller.GenerateDiceRolls(numberRolled, sides)); } if (Player1.Score > Player2.Score) { Console.WriteLine("Congratulations, Player 1 Wins!"); } else if (Player1.Score < Player2.Score) { Console.WriteLine("Congratulations, Player 2 Wins!"); } else { Console.WriteLine("Congratulations, It's a tie!"); } } } }
33.459016
109
0.546791
[ "MIT" ]
bmckenna75/GDAPS1
McKenna_PracticalExam2/McKenna_PracticalExam2/Program.cs
2,043
C#
using Infrastructure.Model.Domain; namespace Infrastructure.Tests.Data.Domain { public class OrderLine : Entity { public virtual Product Product { get; set; } public virtual int Quantity { get; set; } public virtual double Price { get; set; } public virtual Order Order { get; set; } // for information on why we want this 'extra' property, see: // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ public virtual int OrderId { get; set; } // for information on why we want this 'extra' property, see: // http://stuartgatenby.com/ef/2011/03/05/entity-framework-relationship-mapping-best-of-both-worlds-ef4-1ctp5-code-only-fluent-api/ public virtual int ProductId { get; set; } } }
24.159091
139
0.541863
[ "MIT" ]
huyrua/efprs
net45/Infrastructure.Tests/Data/Domain/OrderLine.cs
1,065
C#
// The MIT License (MIT) // Copyright (c) 2014 Ben Abelshausen // 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. namespace GTFS.Tool.Switches.Processors { /// <summary> /// Represents a processor that produces a GTFS-feed. /// </summary> public abstract class ProcessorFeedSource : ProcessorBase { /// <summary> /// Returns the GTFS feed from this source. /// </summary> /// <returns></returns> public abstract IGTFSFeed GetFeed(); } }
41.135135
80
0.72339
[ "MIT" ]
timminata/GTFS
GTFS.Tool/Switches/Processors/ProcessorFeedSource.cs
1,524
C#
namespace ClassLibrary.Objects { public class Company { public Company() { this.IsDeleted = false; } public int Id { get; set; } public string Name { get; set; } public bool IsDeleted { get; set; } } }
16.352941
43
0.507194
[ "MIT" ]
jeremyknight-me/presentations
2014-testable-webforms-mvp/ClassLibraryVersion02/Objects/Company.cs
280
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Net; using System.Threading.Tasks; using EducationProcess.Domain.Models; using EducationProcess.Services.Interfaces; namespace EducationProcess.Api.Controllers { [ApiController] [Route("api/[controller]")] public class IntermediateCertificationFormsController : ControllerBase { private readonly ILogger<IntermediateCertificationFormsController> _logger; private readonly IIntermediateCertificationFormService _intermediateCertificationFormService; public IntermediateCertificationFormsController(ILogger<IntermediateCertificationFormsController> logger, IIntermediateCertificationFormService intermediateCertificationFormService) { _logger = logger; _intermediateCertificationFormService = intermediateCertificationFormService; } [HttpGet("{id:int}")] [ProducesResponseType(typeof(IntermediateCertificationForm), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> Get([FromRoute] int id) { IntermediateCertificationForm intermediateCertificationForm = await _intermediateCertificationFormService.GetIntermediateCertificationFormByIdAsync(id); if (intermediateCertificationForm is null) return NotFound(); return Ok(intermediateCertificationForm); } [HttpGet("array")] [ProducesResponseType(typeof(IntermediateCertificationForm[]), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> GetRange() { IntermediateCertificationForm[] intermediateCertificationForms = await _intermediateCertificationFormService.GetAllIntermediateCertificationFormsAsync(); if (intermediateCertificationForms.Length == 0) return NotFound(); return Ok(intermediateCertificationForms); } [HttpPost] [ProducesResponseType(typeof(IntermediateCertificationForm), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> IntermediateCertificationForm([FromBody] IntermediateCertificationForm intermediateCertificationForm) { IntermediateCertificationForm addedIntermediateCertificationForm = await _intermediateCertificationFormService.AddIntermediateCertificationFormAsync(intermediateCertificationForm); if (addedIntermediateCertificationForm is null) return NotFound(); return Ok(addedIntermediateCertificationForm); } [HttpPost("array")] [ProducesResponseType(typeof(IntermediateCertificationForm[]), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> IntermediateCertificationFormRange([FromBody] IntermediateCertificationForm[] intermediateCertificationForms) { IntermediateCertificationForm[] addedIntermediateCertificationForms = await _intermediateCertificationFormService.AddRangeIntermediateCertificationFormAsync(intermediateCertificationForms); if (addedIntermediateCertificationForms is null) return NotFound(); return Ok(addedIntermediateCertificationForms); } [HttpPut] [ProducesResponseType(typeof(IntermediateCertificationForm), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> Put([FromBody] IntermediateCertificationForm intermediateCertificationForm) { IntermediateCertificationForm updatedIntermediateCertificationForm = await _intermediateCertificationFormService.UpdateIntermediateCertificationFormAsync(intermediateCertificationForm); if (updatedIntermediateCertificationForm is null) return NotFound(); return Ok(updatedIntermediateCertificationForm); } [HttpPut("array")] [ProducesResponseType(typeof(IntermediateCertificationForm[]), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> PutRange([FromBody] IntermediateCertificationForm[] intermediateCertificationForms) { IntermediateCertificationForm[] updatedIntermediateCertificationForms = await _intermediateCertificationFormService.UpdateRangeIntermediateCertificationFormAsync(intermediateCertificationForms); if (updatedIntermediateCertificationForms is null) return NotFound(); return Ok(updatedIntermediateCertificationForms); } [HttpDelete] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> Delete([FromBody] IntermediateCertificationForm intermediateCertificationForm) { await _intermediateCertificationFormService.DeleteIntermediateCertificationFormAsync(intermediateCertificationForm); return Ok(); } [HttpDelete("array")] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> DeleteRange([FromBody] IntermediateCertificationForm[] intermediateCertificationForms) { await _intermediateCertificationFormService.DeleteRangeIntermediateCertificationFormAsync(intermediateCertificationForms); return Ok(); } } }
52.842593
206
0.744699
[ "MIT" ]
NotKohtpojiep/EducationProcess
src/Api/EducationProcess.Api/Controllers/IntermediateCertificationFormsController.cs
5,709
C#
using System.Collections.Generic; using System.Threading.Tasks; using Auraxis.Net.Helpers; using Flurl; using Flurl.Http; using Newtonsoft.Json.Linq; namespace Auraxis.Net { public class AuraxisClient { internal readonly Platform Platform; internal AuraxisClient(Platform platform) => Platform = platform; public Query<T> Query<T>() => new Query<T>(this); internal async Task<QueryResult<T>> GetAsync<T>(QueryParamCollection queryParameters) { Url url = ApiUtilities.GetUrl<T>(Platform, queryParameters, isExample: false); JObject result = await url.GetJsonAsync<JObject>().ConfigureAwait(false); var timing = result[1].First.ToObject<int>(); var results = result[2].First.ToObject<List<T>>(); return new QueryResult<T>(results, url, timing); } internal async Task<int> CountAsync<T>(QueryParamCollection queryParameters) { JObject result = await ApiUtilities .GetCountUrl<T>(Platform, queryParameters, isExample: false) .GetJsonAsync<JObject>() .ConfigureAwait(false); return result.First.ToObject<int>(); } } }
30.925
93
0.63945
[ "MIT" ]
FurkanKambay/Auraxis.Net
src/Auraxis.Net/AuraxisClient.cs
1,237
C#
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; namespace Azure.Functions.Cli.Extensions { public static class HttpExtension { /// <summary> /// Clones HttpRequestMessage /// </summary> /// <param name="request">The HttpRequestMessage to be cloned</param> /// <returns></returns> public static HttpRequestMessage Clone(this HttpRequestMessage request) { if (request == null) { return null; } var clone = new HttpRequestMessage(request.Method, request.RequestUri) { Content = request.Content.Clone(), Version = request.Version }; foreach (KeyValuePair<string, object> prop in request.Properties) { clone.Properties.Add(prop); } foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers) { clone.Headers.TryAddWithoutValidation(header.Key, header.Value); } return clone; } /// <summary> /// Clones HttpContent object /// </summary> /// <param name="content">HttpContent to be cloned</param> /// <returns>The cloned HttpContent object</returns> public static HttpContent Clone(this HttpContent content) { if (content == null) { return null; } var ms = new MemoryStream(); content.CopyToAsync(ms).Wait(); ms.Position = 0; var clone = new StreamContent(ms); foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers) { clone.Headers.Add(header.Key, header.Value); } return clone; } } }
29.615385
89
0.539221
[ "MIT" ]
AnnMerlyn/azure-functions-core-tools
src/Azure.Functions.Cli/Extensions/HttpExtension.cs
1,927
C#
/* * This class was auto-generated from the API references found at * https://epayments-api.developer-ingenico.com/s2sapi/v1/ */ using Ingenico.Connect.Sdk; using Ingenico.Connect.Sdk.Domain.Definitions; using Ingenico.Connect.Sdk.Domain.Services; namespace Ingenico.Connect.Sdk.Merchant.Services { public class ConvertBankAccountExample { public async void Example() { #pragma warning disable 0168 using (Client client = GetClient()) { BankAccountBban bankAccountBban = new BankAccountBban(); bankAccountBban.AccountNumber = "0532013000"; bankAccountBban.BankCode = "37040044"; bankAccountBban.CountryCode = "DE"; BankDetailsRequest body = new BankDetailsRequest(); body.BankAccountBban = bankAccountBban; BankDetailsResponse response = await client.Merchant("merchantId").Services().Bankaccount(body); } #pragma warning restore 0168 } private Client GetClient() { string apiKeyId = "someKey"; string secretApiKey = "someSecret"; CommunicatorConfiguration configuration = Factory.CreateConfiguration(apiKeyId, secretApiKey); return Factory.CreateClient(configuration); } } }
32.682927
112
0.646269
[ "MIT" ]
AlexXx777/connect-sdk-dotnet
connect-sdk-dotnet-examples/Ingenico/Connect/Sdk/Merchant/Services/ConvertBankAccountExample.cs
1,340
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab_9_task_1 { internal class three { } }
14.076923
33
0.73224
[ "MIT" ]
GoonerMAK/SWE_4202_OOC-I
Lab_9/Lab_9_task_1/three.cs
185
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; namespace UnityEditor.Experimental.Rendering.Universal { internal class SortingLayerDropDown { private class LayerSelectionData { public SerializedObject serializedObject; public Object[] targets; public int layerID; public System.Action<SerializedObject> onSelectionChanged; public LayerSelectionData(SerializedObject so, int lid, Object[] tgts, System.Action<SerializedObject> selectionChangedCallback) { serializedObject = so; layerID = lid; targets = tgts; onSelectionChanged = selectionChangedCallback; } } private static class Styles { public static GUIContent sortingLayerAll = EditorGUIUtility.TrTextContent("All"); public static GUIContent sortingLayerNone = EditorGUIUtility.TrTextContent("None"); public static GUIContent sortingLayerMixed = EditorGUIUtility.TrTextContent("Mixed..."); } Rect m_SortingLayerDropdownRect = new Rect(); SortingLayer[] m_AllSortingLayers; GUIContent[] m_AllSortingLayerNames; List<int> m_ApplyToSortingLayersList; SerializedProperty m_ApplyToSortingLayers; public void OnEnable(SerializedObject serializedObject, string propertyName) { m_ApplyToSortingLayers = serializedObject.FindProperty(propertyName); m_AllSortingLayers = SortingLayer.layers; m_AllSortingLayerNames = m_AllSortingLayers.Select(x => new GUIContent(x.name)).ToArray(); int applyToSortingLayersSize = m_ApplyToSortingLayers.arraySize; m_ApplyToSortingLayersList = new List<int>(applyToSortingLayersSize); for (int i = 0; i < applyToSortingLayersSize; ++i) { int layerID = m_ApplyToSortingLayers.GetArrayElementAtIndex(i).intValue; if (SortingLayer.IsValid(layerID)) m_ApplyToSortingLayersList.Add(layerID); } } void UpdateApplyToSortingLayersArray(object layerSelectionDataObject) { LayerSelectionData layerSelectionData = (LayerSelectionData)layerSelectionDataObject; m_ApplyToSortingLayers.ClearArray(); for (int i = 0; i < m_ApplyToSortingLayersList.Count; ++i) { m_ApplyToSortingLayers.InsertArrayElementAtIndex(i); m_ApplyToSortingLayers.GetArrayElementAtIndex(i).intValue = m_ApplyToSortingLayersList[i]; } if (layerSelectionData.onSelectionChanged != null) layerSelectionData.onSelectionChanged(layerSelectionData.serializedObject); layerSelectionData.serializedObject.ApplyModifiedProperties(); if (layerSelectionData.targets is Light2D[]) { foreach (Light2D light in layerSelectionData.targets) { if (light != null && light.lightType == Light2D.LightType.Global) light.ErrorIfDuplicateGlobalLight(); } } } void OnNoSortingLayerSelected(object selectionData) { m_ApplyToSortingLayersList.Clear(); UpdateApplyToSortingLayersArray(selectionData); } void OnAllSortingLayersSelected(object selectionData) { m_ApplyToSortingLayersList.Clear(); m_ApplyToSortingLayersList.AddRange(m_AllSortingLayers.Select(x => x.id)); UpdateApplyToSortingLayersArray(selectionData); } void OnSortingLayerSelected(object layerSelectionDataObject) { LayerSelectionData layerSelectionData = (LayerSelectionData)layerSelectionDataObject; int layerID = (int)layerSelectionData.layerID; if (m_ApplyToSortingLayersList.Contains(layerID)) m_ApplyToSortingLayersList.RemoveAll(id => id == layerID); else m_ApplyToSortingLayersList.Add(layerID); UpdateApplyToSortingLayersArray(layerSelectionDataObject); } public void OnTargetSortingLayers(SerializedObject serializedObject, Object[] targets, GUIContent labelContent, System.Action<SerializedObject> selectionChangedCallback) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(labelContent); GUIContent selectedLayers; if (m_ApplyToSortingLayersList.Count == 1) selectedLayers = new GUIContent(SortingLayer.IDToName(m_ApplyToSortingLayersList[0])); else if (m_ApplyToSortingLayersList.Count == m_AllSortingLayers.Length) selectedLayers = Styles.sortingLayerAll; else if (m_ApplyToSortingLayersList.Count == 0) selectedLayers = Styles.sortingLayerNone; else selectedLayers = Styles.sortingLayerMixed; bool buttonDown = EditorGUILayout.DropdownButton(selectedLayers, FocusType.Keyboard, EditorStyles.popup); if (Event.current.type == EventType.Repaint) m_SortingLayerDropdownRect = GUILayoutUtility.GetLastRect(); if (buttonDown) { GenericMenu menu = new GenericMenu(); menu.allowDuplicateNames = true; LayerSelectionData layerSelectionData = new LayerSelectionData(serializedObject, 0, targets, selectionChangedCallback); menu.AddItem(Styles.sortingLayerNone, m_ApplyToSortingLayersList.Count == 0, OnNoSortingLayerSelected, layerSelectionData); menu.AddItem(Styles.sortingLayerAll, m_ApplyToSortingLayersList.Count == m_AllSortingLayers.Length, OnAllSortingLayersSelected, layerSelectionData); menu.AddSeparator(""); for (int i = 0; i < m_AllSortingLayers.Length; ++i) { var sortingLayer = m_AllSortingLayers[i]; layerSelectionData = new LayerSelectionData(serializedObject, sortingLayer.id, targets, selectionChangedCallback); menu.AddItem(m_AllSortingLayerNames[i], m_ApplyToSortingLayersList.Contains(sortingLayer.id), OnSortingLayerSelected, layerSelectionData); } menu.DropDown(m_SortingLayerDropdownRect); } EditorGUILayout.EndHorizontal(); } } }
43.433121
178
0.636897
[ "MIT" ]
MusouCrow/CustomShaderGraph
Packages/[email protected]/Editor/2D/SortingLayerDropDown.cs
6,819
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.IO; using System.Reflection; using Xenko.Core.Annotations; namespace Xenko.Core { /// <summary> /// Folders used for the running platform. /// </summary> public class PlatformFolders { // TODO: This class should not try to initialize directories...etc. Try to find another way to do this /// <summary> /// The system temporary directory. /// </summary> public static readonly string TemporaryDirectory = GetTemporaryDirectory(); /// <summary> /// The Application temporary directory. /// </summary> public static readonly string ApplicationTemporaryDirectory = GetApplicationTemporaryDirectory(); /// <summary> /// The application local directory, where user can write local data (included in backup). /// </summary> public static readonly string ApplicationLocalDirectory = GetApplicationLocalDirectory(); /// <summary> /// The application roaming directory, where user can write roaming data (included in backup). /// </summary> public static readonly string ApplicationRoamingDirectory = GetApplicationRoamingDirectory(); /// <summary> /// The application cache directory, where user can write data that won't be backup. /// </summary> public static readonly string ApplicationCacheDirectory = GetApplicationCacheDirectory(); /// <summary> /// The application data directory, where data is deployed. /// It could be read-only on some platforms. /// </summary> public static readonly string ApplicationDataDirectory = GetApplicationDataDirectory(); /// <summary> /// The (optional) application data subdirectory. If not null or empty, /data will be mounted on <see cref="ApplicationDataDirectory"/>/<see cref="ApplicationDataSubDirectory"/> /// </summary> /// <remarks>This property should not be written after the VirtualFileSystem static initialization. If so, an InvalidOperationExeception will be thrown.</remarks> public static string ApplicationDataSubDirectory { get { return applicationDataSubDirectory; } set { if (virtualFileSystemInitialized) throw new InvalidOperationException("ApplicationDataSubDirectory cannot be modified after the VirtualFileSystem has been initialized."); applicationDataSubDirectory = value; } } /// <summary> /// The application directory, where assemblies are deployed. /// It could be read-only on some platforms. /// </summary> public static readonly string ApplicationBinaryDirectory = GetApplicationBinaryDirectory(); /// <summary> /// Get the path to the application executable. /// </summary> /// <remarks>Might be null if start executable is unknown.</remarks> public static readonly string ApplicationExecutablePath = GetApplicationExecutablePath(); private static string applicationDataSubDirectory = string.Empty; private static bool virtualFileSystemInitialized; public static bool IsVirtualFileSystemInitialized { get { return virtualFileSystemInitialized; } internal set { virtualFileSystemInitialized = value; } } [NotNull] private static string GetApplicationLocalDirectory() { #if XENKO_PLATFORM_ANDROID var directory = Path.Combine(PlatformAndroid.Context.FilesDir.AbsolutePath, "local"); Directory.CreateDirectory(directory); return directory; #elif XENKO_PLATFORM_UWP return Windows.Storage.ApplicationData.Current.LocalFolder.Path; #elif XENKO_PLATFORM_IOS var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "Local"); Directory.CreateDirectory(directory); return directory; #else // TODO: Should we add "local" ? var directory = Path.Combine(GetApplicationBinaryDirectory(), "local"); Directory.CreateDirectory(directory); return directory; #endif } [NotNull] private static string GetApplicationRoamingDirectory() { #if XENKO_PLATFORM_ANDROID var directory = Path.Combine(PlatformAndroid.Context.FilesDir.AbsolutePath, "roaming"); Directory.CreateDirectory(directory); return directory; #elif XENKO_PLATFORM_UWP return Windows.Storage.ApplicationData.Current.RoamingFolder.Path; #elif XENKO_PLATFORM_IOS var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "Roaming"); Directory.CreateDirectory(directory); return directory; #else // TODO: Should we add "local" ? var directory = Path.Combine(GetApplicationBinaryDirectory(), "roaming"); Directory.CreateDirectory(directory); return directory; #endif } [NotNull] private static string GetApplicationCacheDirectory() { #if XENKO_PLATFORM_ANDROID var directory = Path.Combine(PlatformAndroid.Context.FilesDir.AbsolutePath, "cache"); #elif XENKO_PLATFORM_UWP var directory = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "cache"); #elif XENKO_PLATFORM_IOS var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "Caches"); #else // TODO: Should we add "local" ? var directory = Path.Combine(GetApplicationBinaryDirectory(), "cache"); #endif Directory.CreateDirectory(directory); return directory; } private static string GetApplicationExecutablePath() { #if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_MONO_MOBILE || XENKO_PLATFORM_UNIX return Assembly.GetEntryAssembly()?.Location; #else return null; #endif } [NotNull] private static string GetTemporaryDirectory() { return GetApplicationTemporaryDirectory(); } [NotNull] private static string GetApplicationTemporaryDirectory() { #if XENKO_PLATFORM_ANDROID return PlatformAndroid.Context.CacheDir.AbsolutePath; #elif XENKO_PLATFORM_UWP return Windows.Storage.ApplicationData.Current.TemporaryFolder.Path; #elif XENKO_PLATFORM_IOS return Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "tmp"); #else return Path.GetTempPath(); #endif } [NotNull] private static string GetApplicationBinaryDirectory() { return FindCoreAssemblyDirectory(GetApplicationExecutableDiretory()); } private static string GetApplicationExecutableDiretory() { #if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_MONO_MOBILE || XENKO_PLATFORM_UNIX var executableName = GetApplicationExecutablePath(); if (!string.IsNullOrEmpty(executableName)) { return Path.GetDirectoryName(executableName); } #if XENKO_RUNTIME_CORECLR return AppContext.BaseDirectory; #else return AppDomain.CurrentDomain.BaseDirectory; #endif #elif XENKO_PLATFORM_UWP return Windows.ApplicationModel.Package.Current.InstalledLocation.Path; #else throw new NotImplementedException(); #endif } static string FindCoreAssemblyDirectory(string entryDirectory) { //simple case var corePath = Path.Combine(entryDirectory, "Xenko.Core.dll"); if (File.Exists(corePath)) { return entryDirectory; } else //search one level down { foreach (var subfolder in Directory.GetDirectories(entryDirectory)) { corePath = Path.Combine(subfolder, "Xenko.Core.dll"); if (File.Exists(corePath)) { return subfolder; } } } //if nothing found, return input return entryDirectory; } [NotNull] private static string GetApplicationDataDirectory() { #if XENKO_PLATFORM_ANDROID return Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Android/data/" + PlatformAndroid.Context.PackageName + "/data"; #elif XENKO_PLATFORM_IOS return Foundation.NSBundle.MainBundle.BundlePath + "/data"; #elif XENKO_PLATFORM_UWP return Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\data"; #else return Path.Combine(GetApplicationBinaryDirectory(), "data"); #endif } } }
38.072874
185
0.644513
[ "MIT" ]
Phantom-D7/stride
sources/core/Xenko.Core/PlatformFolders.cs
9,404
C#
namespace SyncTool.FileSystem { public abstract class BaseVisitor<T> { public virtual void Visit(IDirectory directory, T parameter) { foreach (var subDir in directory.Directories) { ((dynamic)this).Visit((dynamic)subDir, parameter); } foreach (var file in directory.Files) { ((dynamic)this).Visit((dynamic) file, parameter); } } } }
27
68
0.516461
[ "MIT" ]
ap0llo/SyncTool
src/SyncTool.FileSystem/main/BaseVisitor.cs
488
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using ACSE.Core.Encryption; using ACSE.Core.Saves; namespace ACSE.WinForms.Controls { internal sealed class StalkMarketEditor : FlowLayoutPanel { internal enum GameCubeStalkMarketTrend { Spike, Random, Falling } internal enum CityFolkStalkMarketTrend { Trend0, Trend1, Trend2, Trend3 } public int Days = 7; public int[] Prices; public int Trend; private readonly NumericTextBox[] _priceBoxes; private readonly ComboBox _trendComboBox; private readonly List<FlowLayoutPanel> _panels; private readonly Save _saveData; private readonly int _offset; private readonly int _trendOffset; private static readonly string[] DayNames = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public StalkMarketEditor(Save saveData) { AutoSize = true; FlowDirection = FlowDirection.TopDown; _saveData = saveData; Prices = new int[Days]; _priceBoxes = new NumericTextBox[Days]; _panels = new List<FlowLayoutPanel>(); _offset = _trendOffset = -1; switch (_saveData.SaveType) { case SaveType.AnimalCrossing: _offset = saveData.SaveDataStartOffset + 0x20480; _trendOffset = _offset + 0xE; break; case SaveType.DoubutsuNoMoriEPlus: case SaveType.AnimalForestEPlus: _offset = saveData.SaveDataStartOffset + 0x223C8; _trendOffset = _offset + 0xE; break; case SaveType.CityFolk: _offset = saveData.SaveDataStartOffset + 0x63200; _trendOffset = _offset + 0x3C; break; case SaveType.NewLeaf: Days = 6; _offset = saveData.SaveDataStartOffset + 0x6535C; break; case SaveType.WelcomeAmiibo: Days = 6; _offset = saveData.SaveDataStartOffset + 0x6AD60; break; } if (_offset < 0) { Dispose(); return; } // Header Label Controls.Add(new Label { AutoSize = true, Text = "Stalk Market" }); // Trend if (_trendOffset > -1) { var trendPanel = new FlowLayoutPanel { AutoSize = true, FlowDirection = FlowDirection.LeftToRight }; var trendLabel = new Label { AutoSize = false, Size = new Size(130, 22), TextAlign = ContentAlignment.MiddleRight, Text = "Trend:" }; trendPanel.Controls.Add(trendLabel); _trendComboBox = new ComboBox { AutoSize = false, Size = new Size(60, 20) }; switch (saveData.SaveGeneration) { case SaveGeneration.N64: case SaveGeneration.GCN: case SaveGeneration.iQue: Trend = saveData.ReadUInt16(_trendOffset, saveData.IsBigEndian); foreach (var trend in Enum.GetNames(typeof(GameCubeStalkMarketTrend))) { _trendComboBox.Items.Add(trend); } break; case SaveGeneration.Wii: Trend = (int) saveData.ReadUInt32(_trendOffset, saveData.IsBigEndian); foreach (var trend in Enum.GetNames(typeof(CityFolkStalkMarketTrend))) { _trendComboBox.Items.Add(trend); } break; } _trendComboBox.SelectedIndex = Trend; _trendComboBox.SelectedIndexChanged += (s, e) => TrendChanged(_trendComboBox.SelectedIndex); trendPanel.Controls.Add(_trendComboBox); _panels.Add(trendPanel); Controls.Add(trendPanel); } // Prices var offset = _offset; // City Folk has a Sunday buy price that differs from the Sunday AM/PM prices. if (saveData.SaveGeneration == SaveGeneration.Wii) { // TODO: Do we want to offer a way to change the buy price? var buyPriceFromJoan = saveData.ReadUInt32(offset, true); offset += 4; } for (var day = 0; day < Days; day++) { switch (_saveData.SaveGeneration) { case SaveGeneration.N64: case SaveGeneration.GCN: case SaveGeneration.iQue: { Prices[day] = saveData.ReadUInt16(offset, saveData.IsBigEndian); offset += 2; var pricePanel = new FlowLayoutPanel { AutoSize = true, FlowDirection = FlowDirection.LeftToRight }; var priceLabel = new Label { AutoSize = false, Size = new Size(130, 22), TextAlign = ContentAlignment.MiddleRight, Text = $"{DayNames[day]}'s Price:" }; pricePanel.Controls.Add(priceLabel); _priceBoxes[day] = new NumericTextBox { AutoSize = false, Size = new Size(60, 20), Location = new Point(5, day * 24), Text = Prices[day].ToString(), MaxLength = 4 }; var currentDay = day; _priceBoxes[day].TextChanged += (s, e) => PriceChanged(currentDay, int.Parse(_priceBoxes[currentDay].Text)); pricePanel.Controls.Add(_priceBoxes[day]); _panels.Add(pricePanel); Controls.Add(pricePanel); break; } case SaveGeneration.Wii: { var amPrice = saveData.ReadUInt32(offset, true); var pmPrice = saveData.ReadUInt32(offset + 4, true); offset += 8; for (var i = 0; i < 2; i++) { var pricePanel = new FlowLayoutPanel { AutoSize = true, FlowDirection = FlowDirection.LeftToRight }; var priceLabel = new Label { AutoSize = false, Size = new Size(130, 22), TextAlign = ContentAlignment.MiddleRight, Text = $"{DayNames[day]}'s Price [{(i == 0 ? "AM" : "PM")}]:" }; pricePanel.Controls.Add(priceLabel); var priceBox = new NumericTextBox { AutoSize = false, Size = new Size(60, 20), Location = new Point(5, day * 24), Text = (i == 0 ? amPrice : pmPrice).ToString(), MaxLength = 9 }; var currentDay = day; priceBox.TextChanged += (s, e) => PriceChanged(currentDay, int.Parse(priceBox.Text)); pricePanel.Controls.Add(priceBox); _panels.Add(pricePanel); Controls.Add(pricePanel); } break; } case SaveGeneration.N3DS: { var amPrice = new NewLeafInt32(saveData.ReadUInt32(offset), saveData.ReadUInt32(offset + 4)).Value; var pmPrice = new NewLeafInt32(saveData.ReadUInt32(offset + 8), saveData.ReadUInt32(offset + 0xC)).Value; offset += 0x10; for (var i = 0; i < 2; i++) { var pricePanel = new FlowLayoutPanel { AutoSize = true, FlowDirection = FlowDirection.LeftToRight }; var priceLabel = new Label { AutoSize = false, Size = new Size(130, 22), TextAlign = ContentAlignment.MiddleRight, Text = $"{DayNames[day + 1]}'s Price [{(i == 0 ? "AM" : "PM")}]:" }; pricePanel.Controls.Add(priceLabel); var priceBox = new NumericTextBox { AutoSize = false, Size = new Size(60, 20), Location = new Point(5, day * 24), Text = (i == 0 ? amPrice : pmPrice).ToString(), MaxLength = 9 }; var currentDay = day; priceBox.TextChanged += (s, e) => PriceChanged(currentDay, int.Parse(priceBox.Text)); pricePanel.Controls.Add(priceBox); _panels.Add(pricePanel); Controls.Add(pricePanel); } break; } } } } private void PriceChanged(int index, int newPrice, bool pm = false) { if (_saveData == null) return; Prices[index] = newPrice; // Save price switch (_saveData.SaveGeneration) { case SaveGeneration.N64: case SaveGeneration.GCN: case SaveGeneration.iQue: _saveData.Write(_offset + index * 2, (ushort) newPrice, _saveData.IsBigEndian); break; case SaveGeneration.N3DS: var writeOffset = _offset + index * 0x10 + (pm ? 8 : 0); var encryptedValue = new NewLeafInt32((uint) newPrice); _saveData.Write(writeOffset, encryptedValue.Int1); _saveData.Write(writeOffset + 4, encryptedValue.Int2); break; } } private void TrendChanged(int trend) { if (trend < 0) return; Trend = trend; switch (_saveData.SaveGeneration) { case SaveGeneration.N64: case SaveGeneration.GCN: case SaveGeneration.iQue: _saveData.Write(_trendOffset, (ushort) trend, _saveData.IsBigEndian); break; } } } }
36.945783
129
0.418963
[ "MIT" ]
Cuyler36/ACSE
ACSE.WinForms/Controls/StalkMarketEditor.cs
12,268
C#