content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using MediatR; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Szlem.Engine.Exceptions; using Szlem.Engine.UserManagement; using Szlem.Domain.Exceptions; using Szlem.Models.Users; namespace Szlem.Persistence.EF.UserManagement { internal class EnsureRolesExistUseCaseHandler : IRequestHandler<EnsureRolesExistUseCase.Command, EnsureRolesExistUseCase.Result> { private readonly AppDbContext _dbContext; private readonly RoleManager<ApplicationIdentityRole> _roleManager; public EnsureRolesExistUseCaseHandler(AppDbContext dbContext, RoleManager<ApplicationIdentityRole> roleManager) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager)); } public async Task<EnsureRolesExistUseCase.Result> Handle(EnsureRolesExistUseCase.Command request, CancellationToken cancellationToken) { var existingRoles = new List<ApplicationIdentityRole>(); var createdRoles = new List<ApplicationIdentityRole>(); foreach (var role in request.RoleNames) { if (await _roleManager.RoleExistsAsync(role.Name)) { existingRoles.Add(role); } else { var result = await _roleManager.CreateAsync(role); if (result.Succeeded) createdRoles.Add(role); else throw new SzlemException(string.Join(", ", result.Errors.Select(x => x.Description))); } } return new EnsureRolesExistUseCase.Result() { CreatedRoles = createdRoles, ExistingRoles = existingRoles }; } } }
37.884615
142
0.656853
[ "MIT" ]
Yaevh/fcc-net50-bug-repro
src/Szlem.Persistence.EF/UserManagement/EnsureRolesExistUseCaseHandler.cs
1,972
C#
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(WebJobHost.Startup))] namespace WebJobHost { public class Startup { public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 // Do nothing on startup } } }
22.647059
125
0.651948
[ "MIT" ]
Anchinga/TechnicalCommunityContent
IoT/Azure IoT Suite/Session 3 - Building Practical IoT Solutions/Solutions/Demo 3.2/WebJobHost/Startup.cs
387
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Hazelcast.Client; namespace Hazelcast.Examples.Org.Website.Samples { public class AtomicLongSample { public static void Run(string[] args) { // Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1 var hz = HazelcastClient.NewHazelcastClient(); // Get an Atomic Counter, we'll call it "counter" var counter = hz.GetAtomicLong("counter"); // Add and Get the "counter" counter.AddAndGet(3); // value is now 3 // Display the "counter" value Console.WriteLine("counter: " + counter.Get()); // Shutdown this Hazelcast Client hz.Shutdown(); } } }
38.305556
106
0.661349
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Examples/Org.Website.Samples/AtomicLongSample.cs
1,381
C#
namespace Car.Interface { public interface ISteerController { void Steer(float angle); } }
15.857143
37
0.63964
[ "MIT" ]
punsal/Simple-Racer
Assets/Scripts/Car/Interface/ISteerController.cs
113
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Mvc.Cors; /// <summary> /// A filter factory which creates a new instance of <see cref="CorsAuthorizationFilter"/>. /// </summary> internal class CorsAuthorizationFilterFactory : IFilterFactory, IOrderedFilter { private readonly string? _policyName; /// <summary> /// Creates a new instance of <see cref="CorsAuthorizationFilterFactory"/>. /// </summary> /// <param name="policyName">Name used to fetch a CORS policy.</param> public CorsAuthorizationFilterFactory(string? policyName) { _policyName = policyName; } /// <inheritdoc /> // Since clients' preflight requests would not have data to authenticate requests, this // filter must run before any other authorization filters. public int Order => int.MinValue + 100; /// <inheritdoc /> public bool IsReusable => true; /// <inheritdoc /> public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } var filter = serviceProvider.GetRequiredService<CorsAuthorizationFilter>(); filter.PolicyName = _policyName; return filter; } }
32.326087
91
0.699395
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.Cors/src/CorsAuthorizationFilterFactory.cs
1,487
C#
/* * Copyright 2012-2020 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System.Runtime.InteropServices; using NativeULong = System.UInt32; // Note: Code in this file is maintained manually. namespace Net.Pkcs11Interop.LowLevelAPI41 { /// <summary> /// Provides general information about Cryptoki /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct CK_INFO { /// <summary> /// Cryptoki interface version number, for compatibility with future revisions of this interface. /// </summary> public CK_VERSION CryptokiVersion; /// <summary> /// ID of the Cryptoki library manufacturer. Must be padded with the blank character (‘ ‘). Should not be null-terminated. /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] ManufacturerId; /// <summary> /// Bit flags reserved for future versions. Must be zero for this version /// </summary> public NativeULong Flags; /// <summary> /// Character-string description of the library. Must be padded with the blank character (‘ ‘). Should not be null-terminated. /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] LibraryDescription; /// <summary> /// Cryptoki library version number /// </summary> public CK_VERSION LibraryVersion; } }
34.111111
134
0.666356
[ "Apache-2.0" ]
ConnectionMaster/Pkcs11Interop
src/Pkcs11Interop/LowLevelAPI41/CK_INFO.cs
2,159
C#
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.IO; using System.Management.Automation.Host; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { internal sealed partial class ConsoleHost : PSHost, IDisposable { internal bool IsTranscribing { get { // no locking because the compare should be atomic return _isTranscribing; } set { _isTranscribing = value; } } private bool _isTranscribing; /* internal void StartTranscribing(string transcriptFilename, bool shouldAppend) { // lock so as not to contend with IsTranscribing and StopTranscribing lock (transcriptionStateLock) { Dbg.Assert(transcriptionWriter == null, "writer should not exist"); this.transcriptFileName = transcriptFilename; transcriptionWriter = new StreamWriter(transcriptFilename, shouldAppend, new System.Text.UnicodeEncoding()); transcriptionWriter.AutoFlush = true; string format = ConsoleHostStrings.TranscriptPrologue; string line = StringUtil.Format( format, DateTime.Now, Environment.UserDomainName, Environment.UserName, Environment.MachineName, Environment.OSVersion.VersionString); transcriptionWriter.WriteLine(line); // record that we are transcribing... isTranscribing = true; } } */ private string _transcriptFileName = String.Empty; internal string StopTranscribing() { lock (_transcriptionStateLock) { if (_transcriptionWriter == null) { return null; } // The filestream *must* be closed at the end of this method. // If it isn't and there is a pending IO error, the finalizer will // dispose the stream resulting in an IO exception on the finalizer thread // which will crash the process... try { _transcriptionWriter.WriteLine( StringUtil.Format(ConsoleHostStrings.TranscriptEpilogue, DateTime.Now)); } finally { try { _transcriptionWriter.Dispose(); } finally { _transcriptionWriter = null; _isTranscribing = false; } } return _transcriptFileName; } } internal void WriteToTranscript(string text) { lock (_transcriptionStateLock) { if (_isTranscribing && _transcriptionWriter != null) { _transcriptionWriter.Write(text); } } } private StreamWriter _transcriptionWriter; private object _transcriptionStateLock = new object(); } } // namespace
27
124
0.478817
[ "Apache-2.0", "MIT" ]
HydAu/PowerShell
src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs
3,753
C#
using System; namespace Kf.Core.Conventions.Timestamping.Exceptions { public class TimestampException : Exception { public TimestampException(string message) : base(message) { } public TimestampException(string message, Exception innerException) : base(message, innerException) { } } }
31.5
111
0.730159
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
KodeFoxx/Kf.Core
Source/Kf.Core/(conventions)/Timestamping/Exceptions/TimestampException.cs
317
C#
using Azylee.YeahWeb.SocketUtils.TcpUtils; using BigBird.Models.ProjectModels; using BigBird.Models.SystemModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BigBirdConsole.Commons { public static partial class R { public static class TxConvert { internal static string IP = "";//vaselee.com internal static int Port = 0; internal static bool IsConnect = false; internal static bool IsAuth = false; internal static bool AutoReConnect = true; internal static short AutoReConnectInterval = 10; internal static DateTime ConnectTime = DateTime.MinValue; internal static DateTime LastSendTime = DateTime.MinValue; internal static DateTime LastReadTime = DateTime.MinValue; internal static short SendQueueInterval = 1; internal static short SendQueueErrorInterval = 10; internal static TcppClient TcppClient = null; internal static string ConnectKey = "BigBird.Console.201904201215.tcpp";//Tcp通信连接认证密钥 } } }
32.914286
97
0.676215
[ "MIT" ]
yuzhengyang/BigBirdDeployer
BigBirdDeployer/BigBirdConsole/Commons/R.TxConvert.cs
1,170
C#
using System; using System.ComponentModel; using System.Reflection; using static Alba.CsConsoleFormat.TypeConverterUtils; namespace Alba.CsConsoleFormat { /// <summary> /// Converts <see cref="Size"/> to and from <see cref="string"/>: /// <list type="bullet"> /// <item>"1 2" - <c>new Size(1, 2)</c></item> /// </list> /// Separator can be " " or ",". /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class SizeConverter : SequenceTypeConverter<Size> { private static readonly Lazy<ConstructorInfo> SizeConstructor = new Lazy<ConstructorInfo>(() => typeof(Size).GetConstructor(new[] { typeof(int), typeof(int), typeof(bool) })); protected override Size FromString(string str) { string[] parts = SplitNumbers(str, 2); if (parts.Length != 2) throw new FormatException($"Invalid Size format: '{0}'."); try { return new Size(ParseInt(parts[0]), ParseInt(parts[1])); } catch (ArgumentException ex) { throw new FormatException($"Invalid Size format: '{0}'. {ex.Message}", ex); } } protected override ConstructorInfo InstanceConstructor => SizeConstructor.Value; protected override object[] InstanceConstructorArgs(Size o) => new object[] { o.Width, o.Height, false }; } }
38.459459
113
0.607168
[ "Apache-2.0" ]
Athari/CsConsoleFormat
Alba.CsConsoleFormat/Converters/SizeConverter.cs
1,425
C#
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; namespace UnityEditor.NPNFEditor { public partial class XCProject : System.IDisposable { private PBXDictionary _datastore; public PBXDictionary _objects; private PBXDictionary _configurations; private PBXGroup _rootGroup; private string _defaultConfigurationName; private string _rootObjectKey; public string projectRootPath { get; private set; } private FileInfo projectFileInfo; public string filePath { get; private set; } private string sourcePathRoot; private bool modified = false; #region Data // Objects private PBXDictionary<PBXBuildFile> _buildFiles; private PBXDictionary<PBXGroup> _groups; private PBXDictionary<PBXFileReference> _fileReferences; private PBXDictionary<PBXNativeTarget> _nativeTargets; private PBXDictionary<PBXFrameworksBuildPhase> _frameworkBuildPhases; private PBXDictionary<PBXResourcesBuildPhase> _resourcesBuildPhases; private PBXDictionary<PBXShellScriptBuildPhase> _shellScriptBuildPhases; private PBXDictionary<PBXSourcesBuildPhase> _sourcesBuildPhases; private PBXDictionary<PBXCopyFilesBuildPhase> _copyBuildPhases; private PBXDictionary<XCBuildConfiguration> _buildConfigurations; private PBXDictionary<XCConfigurationList> _configurationLists; private PBXProject _project; #endregion #region Constructor public XCProject() { } public XCProject( string filePath ) : this() { if( !System.IO.Directory.Exists( filePath ) ) { Debug.LogWarning( "Path does not exists." ); return; } if( filePath.EndsWith( ".xcodeproj" ) ) { this.projectRootPath = Path.GetDirectoryName( filePath ); this.filePath = filePath; } else { string[] projects = System.IO.Directory.GetDirectories( filePath, "*.xcodeproj" ); if( projects.Length == 0 ) { Debug.LogWarning( "Error: missing xcodeproj file" ); return; } this.projectRootPath = filePath; this.filePath = projects[ 0 ]; } projectFileInfo = new FileInfo( Path.Combine( this.filePath, "project.pbxproj" ) ); string contents = projectFileInfo.OpenText().ReadToEnd(); PBXParser parser = new PBXParser(); _datastore = parser.Decode( contents ); if( _datastore == null ) { throw new System.Exception( "Project file not found at file path " + filePath ); } if( !_datastore.ContainsKey( "objects" ) ) { Debug.Log( "Errore " + _datastore.Count ); return; } _objects = (PBXDictionary)_datastore["objects"]; modified = false; _rootObjectKey = (string)_datastore["rootObject"]; if( !string.IsNullOrEmpty( _rootObjectKey ) ) { _project = new PBXProject( _rootObjectKey, (PBXDictionary)_objects[ _rootObjectKey ] ); _rootGroup = new PBXGroup( _rootObjectKey, (PBXDictionary)_objects[ _project.mainGroupID ] ); } else { Debug.LogWarning( "Error: project has no root object" ); _project = null; _rootGroup = null; } } #endregion #region Properties public PBXProject project { get { return _project; } } public PBXGroup rootGroup { get { return _rootGroup; } } public PBXDictionary<PBXBuildFile> buildFiles { get { if( _buildFiles == null ) { _buildFiles = new PBXDictionary<PBXBuildFile>( _objects ); } return _buildFiles; } } public PBXDictionary<PBXGroup> groups { get { if( _groups == null ) { _groups = new PBXDictionary<PBXGroup>( _objects ); } return _groups; } } public PBXDictionary<PBXFileReference> fileReferences { get { if( _fileReferences == null ) { _fileReferences = new PBXDictionary<PBXFileReference>( _objects ); } return _fileReferences; } } public PBXDictionary<PBXNativeTarget> nativeTargets { get { if( _nativeTargets == null ) { _nativeTargets = new PBXDictionary<PBXNativeTarget>( _objects ); } return _nativeTargets; } } public PBXDictionary<XCBuildConfiguration> buildConfigurations { get { if( _buildConfigurations == null ) { _buildConfigurations = new PBXDictionary<XCBuildConfiguration>( _objects ); } return _buildConfigurations; } } public PBXDictionary<XCConfigurationList> configurationLists { get { if( _configurationLists == null ) { _configurationLists = new PBXDictionary<XCConfigurationList>( _objects ); } return _configurationLists; } } public PBXDictionary<PBXFrameworksBuildPhase> frameworkBuildPhases { get { if( _frameworkBuildPhases == null ) { _frameworkBuildPhases = new PBXDictionary<PBXFrameworksBuildPhase>( _objects ); } return _frameworkBuildPhases; } } public PBXDictionary<PBXResourcesBuildPhase> resourcesBuildPhases { get { if( _resourcesBuildPhases == null ) { _resourcesBuildPhases = new PBXDictionary<PBXResourcesBuildPhase>( _objects ); } return _resourcesBuildPhases; } } public PBXDictionary<PBXShellScriptBuildPhase> shellScriptBuildPhases { get { if( _shellScriptBuildPhases == null ) { _shellScriptBuildPhases = new PBXDictionary<PBXShellScriptBuildPhase>( _objects ); } return _shellScriptBuildPhases; } } public PBXDictionary<PBXSourcesBuildPhase> sourcesBuildPhases { get { if( _sourcesBuildPhases == null ) { _sourcesBuildPhases = new PBXDictionary<PBXSourcesBuildPhase>( _objects ); } return _sourcesBuildPhases; } } public PBXDictionary<PBXCopyFilesBuildPhase> copyBuildPhases { get { if( _copyBuildPhases == null ) { _copyBuildPhases = new PBXDictionary<PBXCopyFilesBuildPhase>( _objects ); } return _copyBuildPhases; } } #endregion #region PBXMOD public bool AddOtherCFlags( string flag ) { return AddOtherCFlags( new PBXList( flag ) ); } public bool AddOtherCFlags( PBXList flags ) { foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) { buildConfig.Value.AddOtherCFlags( flags ); } modified = true; return modified; } public bool AddLibrarySearchPaths( string path ) { return AddLibrarySearchPaths (new PBXList(path)); } public bool AddLibrarySearchPaths( PBXList paths) { foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) { buildConfig.Value.AddLibrarySearchPaths( paths, false ); } modified = true; return modified; } public bool AddHeaderSearchPaths( string path ) { return AddHeaderSearchPaths( new PBXList( path ) ); } public bool AddHeaderSearchPaths( PBXList paths ) { foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) { buildConfig.Value.AddHeaderSearchPaths( paths, false ); } modified = true; return modified; } public bool AddFrameworkSearchPaths( string path ) { return AddFrameworkSearchPaths( new PBXList( path ) ); } public bool AddFrameworkSearchPaths( PBXList paths ) { foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) { buildConfig.Value.AddFrameworkSearchPaths( paths, false ); } modified = true; return modified; } public object GetObject( string guid ) { return _objects[guid]; } public PBXDictionary AddFile( string filePath, PBXGroup parent = null, string tree = "SOURCE_ROOT", bool createBuildFiles = true, bool weak = false ) { PBXDictionary results = new PBXDictionary(); string absPath = string.Empty; if( Path.IsPathRooted( filePath ) ) { absPath = filePath; } else if( tree.CompareTo( "SDKROOT" ) != 0) { absPath = Path.Combine( Application.dataPath, filePath ); } if( tree.CompareTo( "SOURCE_ROOT" ) == 0 ) { System.Uri fileURI = new System.Uri( absPath ); System.Uri rootURI = new System.Uri( ( projectRootPath + "/." ) ); filePath = rootURI.MakeRelativeUri( fileURI ).ToString(); } if( parent == null ) { parent = _rootGroup; } // TODO: Aggiungere controllo se file già presente PBXFileReference fileReference = GetFile( System.IO.Path.GetFileName( filePath ) ); if( fileReference != null ) { return null; } fileReference = new PBXFileReference( filePath, (TreeEnum)System.Enum.Parse( typeof(TreeEnum), tree ) ); parent.AddChild( fileReference ); fileReferences.Add( fileReference ); results.Add( fileReference.guid, fileReference ); //Create a build file for reference if( !string.IsNullOrEmpty( fileReference.buildPhase ) && createBuildFiles ) { PBXBuildFile buildFile; switch( fileReference.buildPhase ) { case "PBXFrameworksBuildPhase": foreach( KeyValuePair<string, PBXFrameworksBuildPhase> currentObject in frameworkBuildPhases ) { buildFile = new PBXBuildFile( fileReference, weak ); buildFiles.Add( buildFile ); currentObject.Value.AddBuildFile( buildFile ); } if ( !string.IsNullOrEmpty( absPath ) && ( tree.CompareTo( "SOURCE_ROOT" ) == 0 ) && File.Exists( absPath ) ) { string libraryPath = Path.Combine( "$(SRCROOT)", Path.GetDirectoryName( filePath ) ); this.AddLibrarySearchPaths( new PBXList( libraryPath ) ); } break; case "PBXResourcesBuildPhase": foreach( KeyValuePair<string, PBXResourcesBuildPhase> currentObject in resourcesBuildPhases ) { buildFile = new PBXBuildFile( fileReference, weak ); buildFiles.Add( buildFile ); currentObject.Value.AddBuildFile( buildFile ); } break; case "PBXShellScriptBuildPhase": foreach( KeyValuePair<string, PBXShellScriptBuildPhase> currentObject in shellScriptBuildPhases ) { buildFile = new PBXBuildFile( fileReference, weak ); buildFiles.Add( buildFile ); currentObject.Value.AddBuildFile( buildFile ); } break; case "PBXSourcesBuildPhase": foreach( KeyValuePair<string, PBXSourcesBuildPhase> currentObject in sourcesBuildPhases ) { buildFile = new PBXBuildFile( fileReference, weak ); buildFiles.Add( buildFile ); currentObject.Value.AddBuildFile( buildFile ); } break; case "PBXCopyFilesBuildPhase": foreach( KeyValuePair<string, PBXCopyFilesBuildPhase> currentObject in copyBuildPhases ) { buildFile = new PBXBuildFile( fileReference, weak ); buildFiles.Add( buildFile ); currentObject.Value.AddBuildFile( buildFile ); } break; case null: Debug.LogWarning( "fase non supportata null" ); break; default: Debug.LogWarning( "fase non supportata def" ); return null; } } return results; } public bool AddFolder( string folderPath, PBXGroup parent = null, string[] exclude = null, bool recursive = true, bool createBuildFile = true ) { if( !Directory.Exists( folderPath ) ) return false; DirectoryInfo sourceDirectoryInfo = new DirectoryInfo( folderPath ); if( exclude == null ) exclude = new string[] {}; if( parent == null ) parent = rootGroup; // Create group PBXGroup newGroup = GetGroup( sourceDirectoryInfo.Name, null /*relative path*/, parent ); foreach( string directory in Directory.GetDirectories( folderPath ) ) { Debug.Log( "DIR: " + directory ); if( directory.EndsWith( ".bundle" ) ) { // Treath it like a file and copy even if not recursive Debug.LogWarning( "This is a special folder: " + directory ); AddFile( directory, newGroup, "SOURCE_ROOT", createBuildFile ); Debug.Log( "fatto" ); continue; } if( recursive ) { Debug.Log( "recursive" ); AddFolder( directory, newGroup, exclude, recursive, createBuildFile ); } } // Adding files. string regexExclude = string.Format( @"{0}", string.Join( "|", exclude ) ); foreach( string file in Directory.GetFiles( folderPath ) ) { if( Regex.IsMatch( file, regexExclude ) ) { continue; } AddFile( file, newGroup, "SOURCE_ROOT", createBuildFile ); } modified = true; return modified; } #endregion #region Getters public PBXFileReference GetFile( string name ) { if( string.IsNullOrEmpty( name ) ) { return null; } foreach( KeyValuePair<string, PBXFileReference> current in fileReferences ) { if( !string.IsNullOrEmpty( current.Value.name ) && current.Value.name.CompareTo( name ) == 0 ) { return current.Value; } } return null; } public PBXGroup GetGroup( string name, string path = null, PBXGroup parent = null ) { if( string.IsNullOrEmpty( name ) ) return null; if( parent == null ) parent = rootGroup; foreach( KeyValuePair<string, PBXGroup> current in groups ) { if( string.IsNullOrEmpty( current.Value.name ) ) { if( current.Value.path.CompareTo( name ) == 0 ) { return current.Value; } } else if( current.Value.name.CompareTo( name ) == 0 ) { return current.Value; } } PBXGroup result = new PBXGroup( name, path ); groups.Add( result ); parent.AddChild( result ); modified = true; return result; } #endregion #region Mods public void ApplyMod( string rootPath, string pbxmod ) { XCMod mod = new XCMod( rootPath, pbxmod ); ApplyMod( mod ); } internal static string AddXcodeQuotes(string path) { return "\"\\\"" + path + "\\\"\""; } public void ApplyMod( XCMod mod ) { PBXGroup modGroup = this.GetGroup( mod.group ); foreach( XCModFile libRef in mod.libs ) { string completeLibPath; if(libRef.sourceTree.Equals("SDKROOT")) { completeLibPath = System.IO.Path.Combine( "usr/lib", libRef.filePath ); } else { completeLibPath = System.IO.Path.Combine( mod.path, libRef.filePath ); } this.AddFile( completeLibPath, modGroup, libRef.sourceTree, true, libRef.isWeak ); } PBXGroup frameworkGroup = this.GetGroup( "Frameworks" ); foreach( string framework in mod.frameworks ) { string[] filename = framework.Split( ':' ); bool isWeak = ( filename.Length > 1 ) ? true : false; string completePath = System.IO.Path.Combine( "System/Library/Frameworks", filename[0] ); this.AddFile( completePath, frameworkGroup, "SDKROOT", true, isWeak ); } foreach( string filePath in mod.files ) { string absoluteFilePath = System.IO.Path.Combine( mod.path, filePath ); this.AddFile( absoluteFilePath, modGroup ); } foreach( string folderPath in mod.folders ) { string absoluteFolderPath = AddXcodeQuotes(System.IO.Path.Combine( mod.path, folderPath )); this.AddFolder( absoluteFolderPath, modGroup, (string[])mod.excludes.ToArray( ) ); } foreach( string headerpath in mod.headerpaths ) { string absoluteHeaderPath = AddXcodeQuotes( System.IO.Path.Combine( mod.path, headerpath ) ); this.AddHeaderSearchPaths( absoluteHeaderPath ); } foreach( string librarypath in mod.librarysearchpaths ) { string absolutePath = AddXcodeQuotes(System.IO.Path.Combine( mod.path, librarypath )); this.AddLibrarySearchPaths( absolutePath ); } if(mod.frameworksearchpath != null) { foreach( string frameworksearchpath in mod.frameworksearchpath ) { string absoluteHeaderPath = AddXcodeQuotes(System.IO.Path.Combine( mod.path, frameworksearchpath )); this.AddFrameworkSearchPaths( absoluteHeaderPath ); } } this.Consolidate(); } #endregion #region Savings public void Consolidate() { PBXDictionary consolidated = new PBXDictionary(); consolidated.internalNewlines = true; consolidated.Append<PBXBuildFile>( this.buildFiles ); consolidated.Append<PBXCopyFilesBuildPhase>( this.copyBuildPhases ); consolidated.Append<PBXFileReference>( this.fileReferences ); consolidated.Append<PBXFrameworksBuildPhase>( this.frameworkBuildPhases ); consolidated.Append<PBXGroup>( this.groups ); consolidated.Append<PBXNativeTarget>( this.nativeTargets ); consolidated.Add( project.guid, project.data ); consolidated.Append<PBXResourcesBuildPhase>( this.resourcesBuildPhases ); consolidated.Append<PBXShellScriptBuildPhase>( this.shellScriptBuildPhases ); consolidated.Append<PBXSourcesBuildPhase>( this.sourcesBuildPhases ); consolidated.Append<XCBuildConfiguration>( this.buildConfigurations ); consolidated.Append<XCConfigurationList>( this.configurationLists ); _objects = consolidated; consolidated = null; } public void Backup() { string backupPath = Path.Combine( this.filePath, "project.backup.pbxproj" ); // Delete previous backup file if( File.Exists( backupPath ) ) File.Delete( backupPath ); // Backup original pbxproj file first File.Copy( System.IO.Path.Combine( this.filePath, "project.pbxproj" ), backupPath ); } /// <summary> /// Saves a project after editing. /// </summary> public void Save() { PBXDictionary result = new PBXDictionary(); result.internalNewlines = true; result.Add( "archiveVersion", 1 ); result.Add( "classes", new PBXDictionary() ); result.Add( "objectVersion", 46 ); Consolidate(); result.Add( "objects", _objects ); result.Add( "rootObject", _rootObjectKey ); Backup(); PBXParser parser = new PBXParser(); StreamWriter saveFile = File.CreateText( System.IO.Path.Combine( this.filePath, "project.pbxproj" ) ); saveFile.Write( parser.Encode( result ) ); saveFile.Close(); } /** * Raw project data. */ public Dictionary<string, object> objects { get { return null; } } #endregion public void Dispose() { } } }
30.003236
152
0.660393
[ "Apache-2.0" ]
npnf-inc/PlayForKeeps
Assets/NPNF/Editor/iOS/third_party/NPNFXcodeEditor/NPNFXCProject.cs
18,543
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the comprehend-2017-11-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Comprehend.Model { /// <summary> /// This is the response object from the DetectSentiment operation. /// </summary> public partial class DetectSentimentResponse : AmazonWebServiceResponse { private SentimentType _sentiment; private SentimentScore _sentimentScore; /// <summary> /// Gets and sets the property Sentiment. /// <para> /// The inferred sentiment that Amazon Comprehend has the highest level of confidence /// in. /// </para> /// </summary> public SentimentType Sentiment { get { return this._sentiment; } set { this._sentiment = value; } } // Check to see if Sentiment property is set internal bool IsSetSentiment() { return this._sentiment != null; } /// <summary> /// Gets and sets the property SentimentScore. /// <para> /// An object that lists the sentiments, and their corresponding confidence levels. /// </para> /// </summary> public SentimentScore SentimentScore { get { return this._sentimentScore; } set { this._sentimentScore = value; } } // Check to see if SentimentScore property is set internal bool IsSetSentimentScore() { return this._sentimentScore != null; } } }
30.376623
108
0.637452
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Comprehend/Generated/Model/DetectSentimentResponse.cs
2,339
C#
namespace Echo.Roles.Dto { public class FlatPermissionDto { public string Name { get; set; } public string DisplayName { get; set; } public string Description { get; set; } } }
21
47
0.558442
[ "MIT" ]
Versus-91/Echo
src/Echo.Application/Roles/Dto/FlatPermissionDto.cs
233
C#
using Foundation.Cms.ViewModels; using Foundation.Commerce.Models.Pages; using System.Collections.Generic; namespace Foundation.Commerce.Customer.ViewModels { /// <summary> /// Represent for all credit cards of user or an organization /// </summary> public class CreditCardCollectionViewModel : ContentViewModel<CreditCardPage> { public CreditCardCollectionViewModel(CreditCardPage currentPage) : base(currentPage) { } public IEnumerable<CreditCardModel> CreditCards { get; set; } public FoundationContact CurrentContact { get; set; } public bool IsB2B { get; set; } } }
30.714286
92
0.706977
[ "Apache-2.0" ]
MiracleManS/Foundation
src/Foundation.Commerce/Customer/ViewModels/CreditCardCollectionViewModel.cs
645
C#
using System.Collections.Generic; using System.Threading; namespace Frog.Util.Collection { /// <summary> /// 阻塞队列 /// </summary> public class BlockingQueue<T> { #region Fields & Properties //队列名称 private string m_name; //队列最大长度 private readonly int m_maxSize; //FIFO队列 private Queue<T> m_queue; //是否运行中 private bool m_isRunning; //入队手动复位事件 private ManualResetEvent m_enqueueWait; //出队手动复位事件 private ManualResetEvent m_dequeueWait; /// <summary> /// 队列长度 /// </summary> public int Count => m_queue.Count; #endregion #region Ctor public BlockingQueue(int maxSize, string name = "BlockingQueue", bool isRunning = false) { m_maxSize = maxSize; m_name = name; m_queue = new Queue<T>(m_maxSize); m_isRunning = isRunning; m_enqueueWait = new ManualResetEvent(false); // 无信号,入队waitOne阻塞 m_dequeueWait = new ManualResetEvent(false); // 无信号, 出队waitOne阻塞 } #endregion #region Public Method /// <summary> /// 开启阻塞队列 /// </summary> public void Open() { m_isRunning = true; } /// <summary> /// 关闭阻塞队列 /// </summary> public void Close() { // 停止队列 m_isRunning = false; // 发送信号,通知出队阻塞waitOne可继续执行,可进行出队操作 m_dequeueWait.Set(); } /// <summary> /// 入队 /// </summary> /// <param name="item"></param> public void Enqueue(T item) { if (!m_isRunning) { return; } while (true) { lock (m_queue) { // 如果队列未满,继续入队 if (m_queue.Count < m_maxSize) { m_queue.Enqueue(item); // 置为无信号 m_enqueueWait.Reset(); // 发送信号,通知出队阻塞waitOne可继续执行,可进行出队操作 m_dequeueWait.Set(); break; } } // 如果队列已满,则阻塞队列,停止入队,等待信号 m_enqueueWait.WaitOne(); } } /// <summary> /// 出队 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Dequeue(ref T item) { while (true) { if (!m_isRunning) { lock (m_queue) return false; } lock (m_queue) { // 如果队列有数据,则执行出队 if (m_queue.Count > 0) { item = m_queue.Dequeue(); // 置为无信号 m_dequeueWait.Reset(); // 发送信号,通知入队阻塞waitOne可继续执行,可进行入队操作 m_enqueueWait.Set(); return true; } } // 如果队列无数据,则阻塞队列,停止出队,等待信号 m_dequeueWait.WaitOne(); } } #endregion public bool IsRunning { get { return m_isRunning; } } /// <summary> /// 队列的最大容量 /// </summary> public int MaxQueueSize { get { return this.m_maxSize; } } } }
25.082192
96
0.404424
[ "MIT" ]
FrogIf/FrogUtil
FrogUtil/Collection/BlockingQueue.cs
4,132
C#
using System; using System.Data; using System.Data.SqlClient; using lmDatasets; namespace atriumDAL { /// <summary> /// Class generated by sgen /// based on secFeature table /// in lawmate database /// on 1/3/2007 /// </summary> public partial class secFeatureDAL:atDAL.ObjectDAL { internal secFeatureDAL(atriumDALManager pDALManager) :base(pDALManager) { Init(); } private void Init() { this.sqlDa.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] { new System.Data.Common.DataTableMapping("Table", "secFeature", new System.Data.Common.DataColumnMapping[] { new System.Data.Common.DataColumnMapping("FeatureName", "FeatureName"), new System.Data.Common.DataColumnMapping("DescE", "DescE"), new System.Data.Common.DataColumnMapping("DescF", "DescF"), new System.Data.Common.DataColumnMapping("entryUser", "entryUser"), new System.Data.Common.DataColumnMapping("entryDate", "entryDate"), new System.Data.Common.DataColumnMapping("updateUser", "updateUser"), new System.Data.Common.DataColumnMapping("updateDate", "updateDate"), new System.Data.Common.DataColumnMapping("ts", "ts"), new System.Data.Common.DataColumnMapping("FeatureId", "FeatureId"), new System.Data.Common.DataColumnMapping("FeatureType", "FeatureType"), })}); // // sqlSelect // this.sqlSelect.CommandType = System.Data.CommandType.StoredProcedure; this.sqlSelect.Connection=myDALManager.SqlCon; this.sqlSelectAll.CommandText = "[secFeatureSelect]"; this.sqlSelectAll.CommandType = System.Data.CommandType.StoredProcedure; this.sqlSelectAll.Connection=myDALManager.SqlCon; this.sqlSelectAll.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); // // sqlInsert // this.sqlInsert.CommandText = "[secFeatureInsert]"; this.sqlInsert.CommandType = System.Data.CommandType.StoredProcedure; this.sqlInsert.Connection=myDALManager.SqlCon; this.sqlInsert.Parameters.Add(new SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlInsert.Parameters.Add(new SqlParameter("@FeatureName", SqlDbType.NVarChar, 50, "FeatureName")); this.sqlInsert.Parameters["@FeatureName"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@DescE", SqlDbType.NVarChar, 255, "DescE")); this.sqlInsert.Parameters["@DescE"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@DescF", SqlDbType.NVarChar, 255, "DescF")); this.sqlInsert.Parameters["@DescF"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@entryUser", SqlDbType.NVarChar, 20, "entryUser")); this.sqlInsert.Parameters["@entryUser"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@entryDate", SqlDbType.SmallDateTime, 24, "entryDate")); this.sqlInsert.Parameters["@entryDate"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@updateUser", SqlDbType.NVarChar, 20, "updateUser")); this.sqlInsert.Parameters["@updateUser"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@updateDate", SqlDbType.SmallDateTime, 24, "updateDate")); this.sqlInsert.Parameters["@updateDate"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@ts", SqlDbType.Timestamp, 50, "ts")); this.sqlInsert.Parameters["@ts"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@FeatureId", SqlDbType.Int, 10, "FeatureId")); this.sqlInsert.Parameters["@FeatureId"].SourceVersion=DataRowVersion.Current; this.sqlInsert.Parameters.Add(new SqlParameter("@FeatureType", SqlDbType.Int, 10, "FeatureType")); this.sqlInsert.Parameters["@FeatureType"].SourceVersion=DataRowVersion.Current; // // sqlUpdate // this.sqlUpdate.CommandText = "[secFeatureUpdate]"; this.sqlUpdate.CommandType = System.Data.CommandType.StoredProcedure; this.sqlUpdate.Connection=myDALManager.SqlCon; this.sqlUpdate.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlUpdate.Parameters.Add(new SqlParameter("@FeatureName", SqlDbType.NVarChar, 50, "FeatureName")); this.sqlUpdate.Parameters["@FeatureName"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@DescE", SqlDbType.NVarChar, 255, "DescE")); this.sqlUpdate.Parameters["@DescE"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@DescF", SqlDbType.NVarChar, 255, "DescF")); this.sqlUpdate.Parameters["@DescF"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@entryUser", SqlDbType.NVarChar, 20, "entryUser")); this.sqlUpdate.Parameters["@entryUser"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@entryDate", SqlDbType.SmallDateTime, 24, "entryDate")); this.sqlUpdate.Parameters["@entryDate"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@updateUser", SqlDbType.NVarChar, 20, "updateUser")); this.sqlUpdate.Parameters["@updateUser"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@updateDate", SqlDbType.SmallDateTime, 24, "updateDate")); this.sqlUpdate.Parameters["@updateDate"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@ts", SqlDbType.Timestamp, 50, "ts")); this.sqlUpdate.Parameters["@ts"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@FeatureId", SqlDbType.Int, 10, "FeatureId")); this.sqlUpdate.Parameters["@FeatureId"].SourceVersion=DataRowVersion.Current; this.sqlUpdate.Parameters.Add(new SqlParameter("@FeatureType", SqlDbType.Int, 10, "FeatureType")); this.sqlUpdate.Parameters["@FeatureType"].SourceVersion=DataRowVersion.Current; // // sqlDelete // this.sqlDelete.CommandText = "[secFeatureDelete]"; this.sqlDelete.CommandType = System.Data.CommandType.StoredProcedure; this.sqlDelete.Connection=myDALManager.SqlCon; this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FeatureId", System.Data.SqlDbType.Int, 4, "FeatureId")); this.sqlDelete.Parameters["@FeatureId"].SourceVersion=DataRowVersion.Original; this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ts", System.Data.SqlDbType.Timestamp, 50, "ts")); this.sqlDelete.Parameters["@ts"].SourceVersion=DataRowVersion.Original; } public SecurityDB.secFeatureDataTable Load() { this.sqlDa.SelectCommand=sqlSelectAll; SecurityDB.secFeatureDataTable dt=new SecurityDB.secFeatureDataTable(); Fill(dt); return dt; } public SecurityDB.secFeatureDataTable Load(int FeatureId) { this.sqlDa.SelectCommand=sqlSelect; this.sqlSelect.Parameters.Clear(); this.sqlSelect.CommandText = "[secFeatureSelectByFeatureId]"; this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FeatureId", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlSelect.Parameters["@FeatureId"].Value=FeatureId; SecurityDB.secFeatureDataTable dt=new SecurityDB.secFeatureDataTable(); Fill(dt); return dt; } public SecurityDB.secFeatureDataTable LoadByFeatureType(int FeatureType) { this.sqlDa.SelectCommand=sqlSelect; this.sqlSelect.Parameters.Clear(); this.sqlSelect.CommandText = "[secFeatureSelectByFeatureType]"; this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FeatureType", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null)); this.sqlSelect.Parameters["@FeatureType"].Value=FeatureType; SecurityDB.secFeatureDataTable dt=new SecurityDB.secFeatureDataTable(); Fill(dt); return dt; } } }
54.062857
261
0.751612
[ "MIT" ]
chris-weekes/atrium
atriumDAL/secFeature_DAL.cs
9,461
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. namespace mshtml { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [ComImport, Guid("3050F1F0-98B5-11CF-BB82-00AA00BDCE0B"), TypeLibType((short)0x1040)] public interface IHTMLBRElement { [DispId(-2147413096)] string clear {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147413096)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147413096)] get; } } }
45.166667
377
0.749077
[ "MIT" ]
BobinYang/OpenLiveWriter
src/managed/OpenLiveWriter.Interop.Mshtml/mshtml/IHTMLBRElement.cs
813
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 eventbridge-2015-10-07.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.EventBridge.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.EventBridge.Model.Internal.MarshallTransformations { /// <summary> /// CreatePartnerEventSource Request Marshaller /// </summary> public class CreatePartnerEventSourceRequestMarshaller : IMarshaller<IRequest, CreatePartnerEventSourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreatePartnerEventSourceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreatePartnerEventSourceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EventBridge"); string target = "AWSEvents.CreatePartnerEventSource"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-10-07"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAccount()) { context.Writer.WritePropertyName("Account"); context.Writer.Write(publicRequest.Account); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreatePartnerEventSourceRequestMarshaller _instance = new CreatePartnerEventSourceRequestMarshaller(); internal static CreatePartnerEventSourceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreatePartnerEventSourceRequestMarshaller Instance { get { return _instance; } } } }
35.837838
163
0.628205
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/EventBridge/Generated/Model/Internal/MarshallTransformations/CreatePartnerEventSourceRequestMarshaller.cs
3,978
C#
using System; using System.ComponentModel.Composition; using FirstFloor.ModernUI.Windows; namespace DumpMiner.Infrastructure.Mef { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ContentAttribute : ExportAttribute { public ContentAttribute(string contentUri) : base(typeof(IContent)) { ContentUri = contentUri; } public string ContentUri { get; private set; } } }
23.45
54
0.675906
[ "MIT" ]
dudikeleti/DumpMiner
DumpMiner/Infrastructure/Mef/ContentAttribute.cs
471
C#
namespace MyMiniWebServer.Server.Handlers { using System; using MyMiniWebServer.Server.Common; using MyMiniWebServer.Server.Handlers.Contracts; using MyMiniWebServer.Server.Http; using MyMiniWebServer.Server.Http.Contracts; public class RequestHandler : IRequestHandler { private readonly Func<IHttpRequest, IHttpResponse> handlingFunc; public RequestHandler(Func<IHttpRequest, IHttpResponse> handlingFunc) { CoreValidator.ThrowIfNull(handlingFunc, nameof(handlingFunc)); this.handlingFunc = handlingFunc; } public IHttpResponse Handle(IHttpContext context) { string sessionIdToSend = null; if (!context.Request.Cookies.ContainsKey(SessionStore.SessionCookieKey)) { var sessionId = Guid.NewGuid().ToString(); context.Request.Session = SessionStore.Get(sessionId); sessionIdToSend = sessionId; } var response = this.handlingFunc(context.Request); if (sessionIdToSend != null) { response.Headers.Add( HttpHeader.SetCookie, $"{SessionStore.SessionCookieKey}={sessionIdToSend}; HttpOnly; path=/"); } if (!response.Headers.ContainsKey(HttpHeader.ContentType)) { response.Headers.Add(HttpHeader.ContentType, "text/plain"); } foreach (var cookie in response.Cookies) { response.Headers.Add(HttpHeader.SetCookie, cookie.ToString()); } return response; } } }
30.553571
92
0.591467
[ "MIT" ]
mdamyanova/C-Sharp-Web-Development
09.C# Web/09.01.C# Web Development Basics/MyMiniWebServer/MyMiniWebServer/Server/Handlers/RequestHandler.cs
1,713
C#
using System.Linq; namespace Infrastructure { public partial class BaseForm : System.Windows.Forms.Form { public BaseForm() { InitializeComponent(); } private void BaseForm_Load(object sender, System.EventArgs e) { } } }
15.176471
64
0.662791
[ "MIT" ]
zomorodiNooshin/C-sample
MyApplication/Infrastructure/BaseForm.cs
260
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associada a um assembly. [assembly: AssemblyTitle("Page275")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Page275")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna invisíveis os tipos neste assembly // para componentes COM. Caso precise acessar um tipo neste assembly a partir de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("f221b90c-e40b-498c-886a-2bcfd082c68b")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números da Versão e da Revisão // utilizando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.351351
97
0.750529
[ "MIT" ]
renebentes/HeadFirstCSharp
Cap7/Page275/Properties/AssemblyInfo.cs
1,445
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IManagedDeviceRemoteLockRequest. /// </summary> public partial interface IManagedDeviceRemoteLockRequest : IBaseRequest { /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task PostAsync( CancellationToken cancellationToken = default); /// <summary> /// Issues the POST request and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse"/> object of the request</returns> System.Threading.Tasks.Task<GraphResponse> PostResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IManagedDeviceRemoteLockRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IManagedDeviceRemoteLockRequest Select(string value); } }
38.263158
153
0.602017
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IManagedDeviceRemoteLockRequest.cs
2,181
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.ProjectSystem.VS.Tree.Dependencies.Models { internal static class IDependencyViewModelExtensions { public static IEnumerable<ImageMoniker> GetIcons(this IDependencyViewModel self) { yield return self.Icon; yield return self.ExpandedIcon; } } }
32.333333
161
0.731959
[ "Apache-2.0" ]
bording/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/Tree/Dependencies/Models/IDependencyViewModelExtensions.cs
584
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Threading.Tasks; using Microsoft.JSInterop; using Microsoft.JSInterop.WebAssembly; namespace Microsoft.AspNetCore.Components.WebAssembly.Services { /// <summary> /// Provides a service for loading assemblies at runtime in a browser context. /// /// Supports finding pre-loaded assemblies in a server or pre-rendering context. /// </summary> public sealed class LazyAssemblyLoader { internal const string GetLazyAssemblies = "window.Blazor._internal.getLazyAssemblies"; internal const string ReadLazyAssemblies = "window.Blazor._internal.readLazyAssemblies"; internal const string ReadLazyPDBs = "window.Blazor._internal.readLazyPdbs"; private readonly IJSRuntime _jsRuntime; private readonly HashSet<string> _loadedAssemblyCache; /// <summary> /// Initializes a new instance of <see cref="LazyAssemblyLoader"/>. /// </summary> /// <param name="jsRuntime">The <see cref="IJSRuntime"/>.</param> public LazyAssemblyLoader(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; _loadedAssemblyCache = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name + ".dll").ToHashSet(); } /// <summary> /// In a browser context, calling this method will fetch the assemblies requested /// via a network call and load them into the runtime. In a server or pre-rendered /// context, this method will look for the assemblies already loaded in the runtime /// and return them. /// </summary> /// <param name="assembliesToLoad">The names of the assemblies to load (e.g. "MyAssembly.dll")</param> /// <returns>A list of the loaded <see cref="Assembly"/></returns> public async Task<IEnumerable<Assembly>> LoadAssembliesAsync(IEnumerable<string> assembliesToLoad) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"))) { return await LoadAssembliesInClientAsync(assembliesToLoad); } return await LoadAssembliesInServerAsync(assembliesToLoad); } private Task<IEnumerable<Assembly>> LoadAssembliesInServerAsync(IEnumerable<string> assembliesToLoad) { var loadedAssemblies = new List<Assembly>(); try { foreach (var assemblyName in assembliesToLoad) { loadedAssemblies.Add(Assembly.Load(Path.GetFileNameWithoutExtension(assemblyName))); } } catch (FileNotFoundException ex) { throw new InvalidOperationException($"Unable to find the following assembly: {ex.FileName}. Make sure that the appplication is referencing the assemblies and that they are present in the output folder."); } return Task.FromResult<IEnumerable<Assembly>>(loadedAssemblies); } private async Task<IEnumerable<Assembly>> LoadAssembliesInClientAsync(IEnumerable<string> assembliesToLoad) { // Check to see if the assembly has already been loaded and avoids reloading it if so. // Note: in the future, as an extra precuation, we can call `Assembly.Load` and check // to see if it throws FileNotFound to ensure that an assembly hasn't been loaded // between when the cache of loaded assemblies was instantiated in the constructor // and the invocation of this method. var newAssembliesToLoad = assembliesToLoad.Where(assembly => !_loadedAssemblyCache.Contains(assembly)); var loadedAssemblies = new List<Assembly>(); var count = (int)await ((IJSUnmarshalledRuntime)_jsRuntime).InvokeUnmarshalled<string[], object, object, Task<object>>( GetLazyAssemblies, newAssembliesToLoad.ToArray(), null, null); if (count == 0) { return loadedAssemblies; } var assemblies = ((IJSUnmarshalledRuntime)_jsRuntime).InvokeUnmarshalled<object, object, object, byte[][]>( ReadLazyAssemblies, null, null, null); var pdbs = ((IJSUnmarshalledRuntime)_jsRuntime).InvokeUnmarshalled<object, object, object, byte[][]>( ReadLazyPDBs, null, null, null); for (int i = 0; i < assemblies.Length; i++) { // The runtime loads assemblies into an isolated context by default. As a result, // assemblies that are loaded via Assembly.Load aren't available in the app's context // AKA the default context. To work around this, we explicitly load the assemblies // into the default app context. var assembly = assemblies[i]; var pdb = pdbs[i]; var loadedAssembly = pdb.Length == 0 ? AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(assembly)) : AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(assembly), new MemoryStream(pdb)); loadedAssemblies.Add(loadedAssembly); _loadedAssemblyCache.Add(loadedAssembly.GetName().Name + ".dll"); } return loadedAssemblies; } } }
44.715385
220
0.632032
[ "Apache-2.0" ]
AaqibAhamed/aspnetcore
src/Components/WebAssembly/WebAssembly/src/Services/LazyAssemblyLoader.cs
5,813
C#
namespace daq_api.Models.WebMap { public class Bookmark { public Extent Extent { get; set; } public string Name { get; set; } } }
19.875
42
0.584906
[ "MIT" ]
agrc/daq-web-framework
api/Models/WebMap/Bookmark.cs
161
C#
namespace DapperExtensionsReloaded.Test.Mapper { public class FooWithIntId { public int Id { get; set; } public string Value { get; set; } public int BarId { get; set; } } }
23.222222
46
0.602871
[ "MIT" ]
MisterGoodcat/Dapper-Extensions
DapperExtensionsReloaded.Test/Mapper/FooWithIntId.cs
209
C#
using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using FHICORC.Enums; using FHICORC.Configuration; using FHICORC.Core.Data; using FHICORC.Data; using System.Diagnostics; using System.Globalization; namespace FHICORC.Services { public class LocaleService { public static LocaleService Current { get; set; } = new LocaleService(); private Dictionary<string, string> _translations = new Dictionary<string, string>(); private string _notFoundSymbol = "$"; private string _locale; private JsonKvpReader _reader = new JsonKvpReader(); private bool _loadedFromEmbeddedFile { get; set; } public bool LoadedFromEmbeddedFile { get { return _loadedFromEmbeddedFile; } set { _loadedFromEmbeddedFile = value; } } public LocaleService() { } public string this[string key] => Translate(key); public string Translate(string key, params object[] args) { if (_translations.ContainsKey(key)) return args.Length == 0 ? _translations[key] : string.Format(_translations[key], args); return $"{_notFoundSymbol}{key}{_notFoundSymbol}"; } public LanguageSelection GetLanguage() { return _locale.FromISOCode(); } public void LoadLocale(string isoCode, Stream localeStream, bool loadedFromEmbeddedFile) { _translations.Clear(); try { _translations = _reader.Read(localeStream) ?? new Dictionary<string, string>(); LoadedFromEmbeddedFile = loadedFromEmbeddedFile; IoCContainer.Resolve<IPreferencesService>().SetUserPreference(PreferencesKeys.LANGUAGE_SETTING, isoCode); } catch (Exception) { throw new JsonReaderException(); } _locale = isoCode; } public T GetClassValueForKey<T>(string key) where T : class { if (_translations.ContainsKey(key)) { string valueFromTextFile = _translations[key]; try { T value = (T)Convert.ChangeType(valueFromTextFile, typeof(T), CultureInfo.InvariantCulture); return value; } catch (Exception e) { Debug.Print($"{nameof(LocaleService)}.{nameof(GetClassValueForKey)}: Could not retrieve " + $"the value from text file, caught {e} with message {e.Message}"); return null; } } return null; } public void Reset() { Current = new LocaleService(); } } }
28.980583
121
0.545394
[ "MIT" ]
folkehelseinstituttet/Fhi.Koronasertifikat.Verifikasjon.App
FHICORC/Services/LocaleService.cs
2,987
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Xml.Serialization; using System.Text; using System.IO; using Lars.UI; //using UI.Xml; namespace Lars.Sound { public abstract class CalibrationManager : ManagerHelper { public static CalibrationManager instance = null; protected AudioSource calibPlayer; public CalibrationData calibData = new CalibrationData(); bool dataLoaded; #region Methods void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); calibPlayer = GetComponent<AudioSource>(); panelController = calibPanel.GetComponent<CalibrationPanelController>(); } void Start() { // Calibration profile exists? Apply it if (!LoadData()) { uiController.ShowWarning("No calibration profile found"); } else { ApplyCalibration(); } } public CalibrationData GetData() { if (!dataLoaded) LoadData(); return calibData; } #endregion #region GUI public GameObject calibPanel; CalibrationPanelController panelController; /// <summary> /// Show calibrationpanel /// </summary> /// <param name="s"></param> public void ShowPanel(bool s) { calibPanel.SetActive(s); if (s) { //soundManager.StopAllSounds(); } else { StopCalibration(); ApplyCalibration(); } } protected Button GetButton(bool max, bool left) { string t = max ? "play" : "test"; string s = left ? "left" : "right"; return panelController.xmlLayout.GetElementById<Button>(t + s); } #endregion #region Calibration protected bool calibrating, calibrateLeft; public abstract void StartCalibration(bool max, Channel chan); /// <summary> /// Plays calib player at max output /// </summary> /// <param name="chan"></param> public void PlayMaxCalibration(Channel chan) { StartCalibration(true, chan); } /// <summary> /// Plays calib at level that was inputted into UI /// </summary> /// <param name="chan"></param> public void PlayTestCalibration(Channel chan) { StartCalibration(false, chan); } /// <summary> /// Stop calib player, checks if values are correct /// </summary> public void StopCalibration() { calibPlayer.Stop(); dataLoaded = true; } /// <summary> /// Set calibplayer level with buttons /// </summary> /// <param name="dB"></param> public abstract void SetLevel(int dB); /// <summary> /// Pass values to SoundManager /// </summary> public virtual void ApplyCalibration() { if (!dataLoaded) LoadData(); if (calibData.measuredAtMax_L < calibData.targetLevel || calibData.measuredAtMax_R < calibData.targetLevel) { uiController.ShowWarning("Target value should not be greater than measured value"); return; } Debug.Log("LEFT difference is: " + GetCalibrationDiff(Channel.Left) + "which is: " + Utils.DecibelToLinear(GetCalibrationDiff(Channel.Left))); Debug.Log("RIGHT difference is: " + GetCalibrationDiff(Channel.Right) + "which is: " + Utils.DecibelToLinear(GetCalibrationDiff(Channel.Right))); soundManager.SetCalibration(GetCalibrationDiff(Channel.Left), Channel.Left); soundManager.SetCalibration(GetCalibrationDiff(Channel.Right), Channel.Right); } /// <summary> /// Returns difference between recorded max (PlayMaxCalibration) & the desired target dB /// </summary> /// <param name="chan"></param> /// <returns></returns> public float GetCalibrationDiff(Channel chan) { if (!dataLoaded) LoadData(); float diff; if (chan == Channel.Left) { diff = calibData.targetLevel - calibData.measuredAtMax_L; if (diff > 0f) diff = 0; } else { diff = calibData.targetLevel - calibData.measuredAtMax_R; if (diff > 0f) diff = 0; } return diff; } #endregion #region IO public void SaveData() { ApplyCalibration(); XmlSerializer serializer = new XmlSerializer(typeof(CalibrationData)); var fname = Path.Combine(Application.persistentDataPath, "calibration_profile.xml"); Debug.Log("SAVED TO: " + fname); var encoding = Encoding.GetEncoding("UTF-8"); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); using (StreamWriter sw = new StreamWriter(fname, false, encoding)) { serializer.Serialize(sw, calibData, ns); } } public bool LoadData() { try { XmlSerializer serializer = new XmlSerializer(typeof(CalibrationData)); string fname = Path.Combine(Application.persistentDataPath, "calibration_profile.xml"); FileStream stream = new FileStream(fname, FileMode.Open); calibData = serializer.Deserialize(stream) as CalibrationData; stream.Close(); dataLoaded = true; return true; } catch (System.Exception e) { Debug.Log("Could not Load XML due to error: " + e.ToString()); return false; } } #endregion } [System.Serializable] public class CalibrationData { [XmlElement("measured_at_max_left")] public float measuredAtMax_L = 80; [XmlElement("measured_at_max_right")] public float measuredAtMax_R = 80; [XmlElement("target_level")] public float targetLevel = 70; public CalibrationData() { } } }
27.311741
157
0.536021
[ "Apache-2.0" ]
exporl/lars-common
Core/Sound/CalibrationManager.cs
6,748
C#
/* Copyright (C) 2018. Hitomi Parser Developers */ using Hitomi_Copy; using Hitomi_Copy.Data; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace Hitomi_Copy_3 { public partial class frmBookmark : Form { Dictionary<string, ListViewGroup> groups = new Dictionary<string, ListViewGroup>(); Dictionary<string, List<string>> artists = new Dictionary<string, List<string>>(); public frmBookmark() { InitializeComponent(); } private void frmBookmark_Load(object sender, EventArgs e) { //ColumnSorter.InitListView(listView1); ColumnSorter.InitListView(listView2); ColumnSorter.InitListView(listView6); ColumnSorter.InitListView(listView3); ColumnSorter.InitListView(listView4); ColumnSorter.InitListView(listView5); AddToListGroups(listView1, HitomiBookmark.Instance.GetModel().Artists); AddToList(listView2, HitomiBookmark.Instance.GetModel().Groups); AddToList(listView6, HitomiBookmark.Instance.GetModel().Articles); AddToList(listView3, HitomiBookmark.Instance.GetModel().Tags); AddToList(listView4, HitomiBookmark.Instance.GetModel().Series); AddToList(listView5, HitomiBookmark.Instance.GetModel().Characters); } private void AddToListGroups(ListView lv, List<Tuple<string, DateTime, string>> contents) { ListViewGroup lvg = new ListViewGroup("미분류"); groups.Clear(); artists.Clear(); groups.Add("미분류", lvg); artists.Add("미분류", new List<string>()); foreach (var content in contents) if (!groups.ContainsKey(content.Item3 ?? "미분류")) { ListViewGroup lvgt = new ListViewGroup(content.Item3 ?? "미분류"); groups.Add(content.Item3, lvgt); artists.Add(content.Item3, new List<string>()); lv.Groups.Add(lvgt); } lv.Groups.Add(lvg); for (int i = 0; i < contents.Count; i++) { int index = contents.Count - i - 1; lv.Items.Add(new ListViewItem(new string[] { (i+1).ToString(), contents[index].Item1, contents[index].Item2.ToString() }, groups[contents[index].Item3 ?? "미분류"])); artists[contents[index].Item3 ?? "미분류"].Add(contents[index].Item1); } } private void AddToList(ListView lv, List<Tuple<string, DateTime>> contents) { for (int i = 0; i < contents.Count; i++) { int index = contents.Count - i - 1; lv.Items.Add(new ListViewItem(new string[] { (i+1).ToString(), contents[index].Item1, contents[index].Item2.ToString() })); } } private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView1.SelectedItems.Count == 1) { (new frmArtistInfo(this, listView1.SelectedItems[0].SubItems[1].Text.Replace('_', ' '))).Show(); } } private void listView2_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView2.SelectedItems.Count == 1) { (new frmGroupInfo(this, listView2.SelectedItems[0].SubItems[1].Text.Replace('_', ' '))).Show(); } } private void listView6_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView6.SelectedItems.Count == 1) { foreach (var md in HitomiData.Instance.metadata_collection) if (md.ID.ToString() == listView6.SelectedItems[0].SubItems[1].Text) { (new frmGalleryInfo(this, md)).Show(); break; } } } private void listView3_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView3.SelectedItems.Count == 1) { (new frmFinder("tag:" + listView3.SelectedItems[0].SubItems[1].Text.Replace(' ', '_'))).Show(); } } private void listView4_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView4.SelectedItems.Count == 1) { (new frmFinder("series:" + listView4.SelectedItems[0].SubItems[1].Text.Replace(' ', '_'))).Show(); } } private void listView5_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView5.SelectedItems.Count == 1) { (new frmFinder("character:" + listView5.SelectedItems[0].SubItems[1].Text.Replace(' ', '_'))).Show(); } } private void button1_Click(object sender, EventArgs e) { BKPicker frm = new BKPicker(this,"작가", RequestAddArtist); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); } public void RequestAddArtist(string artist) { artist = artist.Replace('_', ' '); if (HitomiBookmark.Instance.GetModel().Artists.Any(x => x.Item1 == artist)) { MessageBox.Show($"이미 추가된 작가입니다!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } HitomiBookmark.Instance.GetModel().Artists.Add(new Tuple<string, DateTime, string>(artist, DateTime.Now, null)); HitomiBookmark.Instance.Save(); listView1.Items.Clear(); AddToListGroups(listView1, HitomiBookmark.Instance.GetModel().Artists); } private void button2_Click(object sender, EventArgs e) { BKPicker frm = new BKPicker(this, "그룹", RequestAddGroup); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); } public void RequestAddGroup(string group) { group = group.Replace('_', ' '); if (HitomiBookmark.Instance.GetModel().Groups.Any(x => x.Item1 == group)) { MessageBox.Show($"이미 추가된 그룹입니다!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } HitomiBookmark.Instance.GetModel().Groups.Add(new Tuple<string, DateTime>(group, DateTime.Now)); HitomiBookmark.Instance.Save(); listView2.Items.Clear(); AddToList(listView2, HitomiBookmark.Instance.GetModel().Groups); } private void button3_Click(object sender, EventArgs e) { BKPicker frm = new BKPicker(this, "태그", RequestAddTag); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); } public void RequestAddTag(string tag) { tag = tag.Replace('_', ' '); if (HitomiBookmark.Instance.GetModel().Tags.Any(x => x.Item1 == tag)) { MessageBox.Show($"이미 추가된 태그입니다!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } HitomiBookmark.Instance.GetModel().Tags.Add(new Tuple<string, DateTime>(tag, DateTime.Now)); HitomiBookmark.Instance.Save(); listView3.Items.Clear(); AddToList(listView3, HitomiBookmark.Instance.GetModel().Tags); } private void button4_Click(object sender, EventArgs e) { BKPicker frm = new BKPicker(this, "시리즈", RequestAddSeries); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); } public void RequestAddSeries(string series) { series = series.Replace('_', ' '); if (HitomiBookmark.Instance.GetModel().Series.Any(x => x.Item1 == series)) { MessageBox.Show($"이미 추가된 시리즈입니다!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } HitomiBookmark.Instance.GetModel().Series.Add(new Tuple<string, DateTime>(series, DateTime.Now)); HitomiBookmark.Instance.Save(); listView4.Items.Clear(); AddToList(listView4, HitomiBookmark.Instance.GetModel().Series); } private void button5_Click(object sender, EventArgs e) { BKPicker frm = new BKPicker(this, "캐릭터", RequestAddCharacter); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); } public void RequestAddCharacter(string character) { character = character.Replace('_', ' '); if (HitomiBookmark.Instance.GetModel().Characters.Any(x => x.Item1 == character)) { MessageBox.Show($"이미 추가된 캐릭터입니다!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } HitomiBookmark.Instance.GetModel().Characters.Add(new Tuple<string, DateTime>(character, DateTime.Now)); HitomiBookmark.Instance.Save(); listView5.Items.Clear(); AddToList(listView5, HitomiBookmark.Instance.GetModel().Characters); } protected override bool ProcessDialogKey(Keys keyData) { if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape) { this.Close(); return true; } return base.ProcessDialogKey(keyData); } private void DeleteSpecifyElement(List<Tuple<string, DateTime, string>> list, string item_text) { for (int i = 0; i < list.Count; i++) if (list[i].Item1.ToLower().Replace(' ', '_') == item_text.ToLower().Replace(' ', '_')) { list.RemoveAt(i); return; } } private void DeleteSpecifyElement(List<Tuple<string, DateTime>> list, string item_text) { for (int i = 0; i < list.Count; i++) if (list[i].Item1.ToLower().Replace(' ', '_') == item_text.ToLower().Replace(' ', '_')) { list.RemoveAt(i); return; } } private void listView_KeyDown(object sender, KeyEventArgs e) { ListView lv = sender as ListView; if (e.KeyCode == Keys.F2) { if (lv.SelectedItems.Count == 1) { (new Record(lv.SelectedItems[0].SubItems[1].Text.Replace('_', ' '))).Show(); } return; } if (e.KeyCode != Keys.Delete) return; if (lv.SelectedItems.Count == 1) { if (MessageBox.Show($"'{lv.SelectedItems[0].SubItems[1].Text}'를 삭제할까요?", "Hitomi Copy", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (lv == listView1) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Artists, lv.SelectedItems[0].SubItems[1].Text); } else if (lv == listView2) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Groups, lv.SelectedItems[0].SubItems[1].Text); } else if (lv == listView6) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Articles, lv.SelectedItems[0].SubItems[1].Text); } else if (lv == listView3) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Tags, lv.SelectedItems[0].SubItems[1].Text); } else if (lv == listView4) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Series, lv.SelectedItems[0].SubItems[1].Text); } else if (lv == listView5) { DeleteSpecifyElement(HitomiBookmark.Instance.GetModel().Characters, lv.SelectedItems[0].SubItems[1].Text); } HitomiBookmark.Instance.Save(); lv.SelectedItems[0].Remove(); } } } private void button6_Click(object sender, EventArgs e) { StringBuilder builder = new StringBuilder(); foreach (var group in artists) { builder.Append($"------- {group.Key} -------\n"); foreach (var artist in group.Value) builder.Append($"{artist}\n"); } MessageBox.Show(builder.ToString()); } #region 작가 관련 ListViewItem selected = null; private void GroupModify_Click(object sender, EventArgs e) { if (selected != null) { int index = HitomiBookmark.Instance.GetModel().Artists.Count - Convert.ToInt32(selected.SubItems[0].Text); if ((sender as ToolStripMenuItem).Text != "새로 만들기...") { selected.Group = groups[(sender as ToolStripMenuItem).Text]; HitomiBookmark.Instance.GetModel().Artists[index] = new Tuple<string, DateTime, string>( HitomiBookmark.Instance.GetModel().Artists[index].Item1, HitomiBookmark.Instance.GetModel().Artists[index].Item2, (sender as ToolStripMenuItem).Text); HitomiBookmark.Instance.Save(); } else { using (var cgd = new CreateGroup()) { if (cgd.ShowDialog() == DialogResult.OK) { if (groups.ContainsKey(cgd.ReturnValue)) { MessageBox.Show("이미 존재하는 그룹입니다.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { ListViewGroup lvgt = new ListViewGroup(cgd.ReturnValue); groups.Add(cgd.ReturnValue, lvgt); listView1.Groups.Add(lvgt); selected.Group = groups[cgd.ReturnValue]; HitomiBookmark.Instance.GetModel().Artists[index] = new Tuple<string, DateTime, string>( HitomiBookmark.Instance.GetModel().Artists[index].Item1, HitomiBookmark.Instance.GetModel().Artists[index].Item2, cgd.ReturnValue); HitomiBookmark.Instance.Save(); } } } } HitomiBookmark.Instance.Save(); } selected = null; } private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e) { (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Clear(); if (listView1.SelectedItems.Count > 0) { selected = listView1.SelectedItems[0]; (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.AddRange(groups.Select(x => new ToolStripMenuItem(x.Key, null, GroupModify_Click)).ToArray()); (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Add(new ToolStripSeparator()); (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Add(new ToolStripMenuItem("새로 만들기...", null, GroupModify_Click)); } } private void 삭제DToolStripMenuItem_Click(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { if (MessageBox.Show($"'{listView1.SelectedItems[0].SubItems[1].Text}'를 삭제할까요?", "Hitomi Copy", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { int index = HitomiBookmark.Instance.GetModel().Artists.Count - Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text); HitomiBookmark.Instance.GetModel().Artists.RemoveAt(index); } } } #endregion } }
41.646192
181
0.530619
[ "MIT" ]
dc-koromo/hitomi-copy
Hitomi Copy 3/frmBookmark.cs
17,200
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sokoban.Tiles { class Normal:Tile { public Normal() { this.Character = '.'; } public override void Update() { } } }
15.842105
41
0.598007
[ "Apache-2.0" ]
Sanderovich/Sokoban
Sokoban/Tiles/Normal.cs
303
C#
using System; using System.Diagnostics; using System.Resources; using System.Windows; using System.Windows.Markup; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using TabbedPageDemo.WinPhone.Resources; namespace TabbedPageDemo.WinPhone { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public static PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) { // Unregister the event so it doesn't get called again RootFrame.Navigated -= ClearBackStackAfterReset; // Only clear the stack for 'new' (forward) and 'refresh' navigations if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh) return; // For UI consistency, clear the entire page stack while (RootFrame.RemoveBackEntry() != null) { ; // do nothing } } #endregion // Initialize the app's font and flow direction as defined in its localized resource strings. // // To ensure that the font of your application is aligned with its supported languages and that the // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage // and ResourceFlowDirection should be initialized in each resx file to match these values with that // file's culture. For example: // // AppResources.es-ES.resx // ResourceLanguage's value should be "es-ES" // ResourceFlowDirection's value should be "LeftToRight" // // AppResources.ar-SA.resx // ResourceLanguage's value should be "ar-SA" // ResourceFlowDirection's value should be "RightToLeft" // // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072. // private void InitializeLanguage() { try { // Set the font to match the display language defined by the // ResourceLanguage resource string for each supported language. // // Fall back to the font of the neutral language if the Display // language of the phone is not supported. // // If a compiler error is hit then ResourceLanguage is missing from // the resource file. RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage); // Set the FlowDirection of all elements under the root frame based // on the ResourceFlowDirection resource string for each // supported language. // // If a compiler error is hit then ResourceFlowDirection is missing from // the resource file. FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection); RootFrame.FlowDirection = flow; } catch { // If an exception is caught here it is most likely due to either // ResourceLangauge not being correctly set to a supported language // code or ResourceFlowDirection is set to a value other than LeftToRight // or RightToLeft. if (Debugger.IsAttached) { Debugger.Break(); } throw; } } } }
40.428571
127
0.614841
[ "Apache-2.0" ]
Alshaikh-Abdalrahman/jedoo
Navigation/TabbedPage/TabbedPageDemo/TabbedPageDemo.WinPhone/App.xaml.cs
9,058
C#
namespace TheBookProject.Web { using System.Threading.Tasks; using Microsoft.AspNet.Identity; public class EmailService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. return Task.FromResult(0); } } }
22.125
64
0.638418
[ "MIT" ]
The-Book-Project/The-Book-Project
Web/TheBookProject.Web/App_Start/EmailService.cs
356
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace SQ { class MenuManager { Menu menu; public bool menuLock = false; public bool isMenuOpen = false; public SpriteFont ItemFont; Rectangle menu1 = new Rectangle(32, 32, 640, 600); Rectangle menu2 = new Rectangle(0, 0, 640, 600); new Vector2 DrawTarget; public string HealthName = "Health"; public string StaminaName = "Stamina"; public string MagicName = "Magic"; public string STRName = "Strength"; public string STRValue; public string DEXName = "Dexterity"; public string DEXValue; public string WILName = "Willpower"; public string WILValue; public string INTName = "Intelligence"; public string INTValue; public string CHAName = "Charisma"; public string CHAValue; public string VITName = "Vitality"; public string VITValue; public string LCKName = "Luck"; public string LuckValue; public MenuManager() {} public void LoadContent(ContentManager content) { menu = new Menu(content.Load<Texture2D>("menu"), menu1 , menu2); ItemFont = content.Load<SpriteFont>("font"); } public void Draw(SpriteBatch spriteBatch) { if (isMenuOpen) { menu.Draw(spriteBatch); spriteBatch.DrawString(ItemFont, STRName, DrawTarget, Color.White); } } public void Update(GameTime gameTime, Camera cam) { KeyboardState MenuKey = Keyboard.GetState(); if (MenuKey.IsKeyUp(Keys.Tab) && menuLock == true) { menuLock = false; } if (MenuKey.IsKeyDown(Keys.Tab) && menuLock == false) { isMenuOpen = !isMenuOpen; menuLock = true; } if (isMenuOpen) { menu.Update(gameTime, cam); } } } class Menu { public Menu(Texture2D texture, Rectangle position, Rectangle source) { this.texture = texture; this.position = position; this.source = source; } Rectangle absolutePosition; Texture2D texture; Rectangle position; Rectangle source; public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, absolutePosition, source, Color.White); } public void Update(GameTime gameTime, Camera cam) { absolutePosition = new Rectangle((int)cam.Position.X + position.X, (int)cam.Position.Y + position.Y, position.Width, position.Height); } } }
29.081818
146
0.546421
[ "MIT" ]
toasty333/SpiritQuest
SQ/MenuManager.cs
3,201
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; namespace Dolittle.Runtime.Embeddings.Store.MongoDB { /// <summary> /// Defines a system that knows about embeddings. /// </summary> public interface IEmbeddings : IEmbeddingsConnection { /// <summary> /// Gets the projection states collection for an embedding. /// </summary> /// <param name="projectionId">The <see cref="ProjectionId" />.</param> /// <param name="token">The <see cref="CancellationToken" />.</param> /// <returns>A <see cref="Task" /> that, when resolved, returns a <see cref="IMongoCollection{TDocument}" /> with <see cref="State.Projection" />.</returns> Task<IMongoCollection<State.Embedding>> GetStates(EmbeddingId embeddingId, CancellationToken token); /// <summary> /// Gets the embedding definitions collection for an embedding. /// </summary> /// <param name="token">The <see cref="CancellationToken" />.</param> /// <returns>A <see cref="Task" /> that, when resolved, returns a <see cref="IMongoCollection{TDocument}" /> with <see cref="Definition.EmbeddingDefinition" />.</returns> Task<IMongoCollection<Definition.EmbeddingDefinition>> GetDefinitions(CancellationToken token); } }
47.354839
178
0.675749
[ "MIT" ]
dolittle/Runtime
Source/Embeddings.Store.MongoDB/IEmbeddings.cs
1,468
C#
/* Original source Farseer Physics Engine: * Copyright (c) 2014 Ian Qvist, http://farseerphysics.codeplex.com * Microsoft Permissive License (Ms-PL) v1.1 */ using System.Collections.Generic; namespace tainicom.Aether.Physics2D.Fluids { public class SpringHash : IEqualityComparer<SpringHash> { public FluidParticle P0; public FluidParticle P1; public bool Equals(SpringHash lhs, SpringHash rhs) { return (lhs.P0.Index == rhs.P0.Index && lhs.P1.Index == rhs.P1.Index) || (lhs.P0.Index == rhs.P1.Index && lhs.P1.Index == rhs.P0.Index); } public int GetHashCode(SpringHash s) { return (s.P0.Index * 73856093) ^ (s.P1.Index * 19349663) ^ (s.P0.Index * 19349663) ^ (s.P1.Index * 73856093); } } }
31.384615
121
0.617647
[ "MIT" ]
jocamar/Caravel
Libs/Aether.Physics2D/Physics2D/Fluids/1/SpringHash.cs
816
C#
using System; using UnityEngine.Scripting; ////REVIEW: should this *not* be inherited? inheritance can lead to surprises namespace UnityEngine.InputSystem.Layouts { /// <summary> /// Attribute to control layout settings of a type used to generate an <see cref="InputControlLayout"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class InputControlLayoutAttribute : Attribute { /// <summary> /// Associates a state representation with an input device and drives /// the control layout generated for the device from its state rather /// than from the device class. /// </summary> /// <remarks>This is *only* useful if you have a state struct dictating a specific /// state layout and you want the device layout to automatically take offsets from /// the fields annotated with <see cref="InputControlAttribute"/>. /// </remarks> public Type stateType { get; set; } public string stateFormat { get; set; } ////TODO: rename this to just "usages"; "commonUsages" is such a weird name [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "According to MSDN, this message can be ignored for attribute parameters, as there are no better alternatives.")] public string[] commonUsages { get; set; } public string variants { get; set; } internal bool? updateBeforeRenderInternal; /// <summary> /// Whether the device should receive events in <see cref="LowLevel.InputUpdateType.BeforeRender"/> updates. /// </summary> /// <seealso cref="InputDevice.updateBeforeRender"/> public bool updateBeforeRender { get => updateBeforeRenderInternal.Value; set => updateBeforeRenderInternal = value; } /// <summary> /// If true, the layout describes a generic class of devices such as "gamepads" or "mice". /// </summary> /// <remarks> /// This property also determines how the layout is presented in the UI. All the device layouts /// that are marked as generic kinds of devices are displayed with their own entry at the root level of /// the control picker (<see cref="UnityEngine.InputSystem.Editor.InputControlPicker"/>), for example. /// </remarks> public bool isGenericTypeOfDevice { get; set; } /// <summary> /// Gives a name to display in the UI. By default, the name is the same as the class the attribute /// is applied to. /// </summary> public string displayName { get; set; } public string description { get; set; } /// <summary> /// If true, don't include the layout when presenting picking options in the UI. /// </summary> /// <remarks> /// This will keep device layouts out of the control picker and will keep control layouts out of /// action type dropdowns. /// </remarks> public bool hideInUI { get; set; } } }
43.30137
253
0.643151
[ "Unlicense" ]
23SAMY23/Meet-and-Greet-MR
Meet & Greet MR (AR)/Library/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/Controls/InputControlLayoutAttribute.cs
3,161
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.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Gets information about Site Recovery network mappings for the current vault. /// </summary> [Cmdlet( VerbsCommon.Get, "AzureRmRecoveryServicesAsrNetworkMapping", DefaultParameterSetName = ASRParameterSets.ByObject)] [Alias("Get-ASRNetworkMapping")] [OutputType(typeof(ASRNetworkMapping))] public class GetAzureRmRecoveryServicesAsrNetworkMapping : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets name of the ASR network mapping object to get. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.ByObject)] [Parameter(ParameterSetName = ASRParameterSets.ByFabricObject)] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// Gets or sets the ASR network mappings corresponding to the specified network ASR object. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.ByObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRNetwork Network { get; set; } /// <summary> /// Gets or sets the ASR network mappings corresponding to the specified primary fabric object. /// </summary> [Parameter(ParameterSetName = ASRParameterSets.ByFabricObject, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRFabric PrimaryFabric { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); switch (this.ParameterSetName) { case ASRParameterSets.ByObject: this.ByObject(); break; case ASRParameterSets.ByFabricObject: this.GetNetworkMappingByFabric(); break; } } /// <summary> /// Get network mapping by network object. /// </summary> private void ByObject() { var tokens = this.Network.ID.UnFormatArmId(ARMResourceIdPaths.NetworkResourceIdPath); if (this.Network.FabricType.Equals(Constants.Azure)) { this.PrimaryFabric = new ASRFabric(this.RecoveryServicesClient.GetAzureSiteRecoveryFabric(tokens[0])); this.GetNetworkMappingByFabric(); } else { if (this.Name == null) { var networkMappingList = this.RecoveryServicesClient.GetAzureSiteRecoveryNetworkMappings( tokens[0], this.Network.Name); this.WriteNetworkMappings(networkMappingList); } else { var networkMapping = this.RecoveryServicesClient.GetAzureSiteRecoveryNetworkMappings( tokens[0], this.Network.Name, this.Name); this.WriteNetworkMapping(networkMapping); } } } /// <summary> /// Write Network mapping. /// </summary> /// <param name="networkMapping">Network mapping</param> private void WriteNetworkMapping( NetworkMapping networkMapping) { this.WriteObject(new ASRNetworkMapping(networkMapping)); } /// <summary> /// Write Network mappings. /// </summary> /// <param name="networkMappings">List of Network mappings</param> private void WriteNetworkMappings( IList<NetworkMapping> networkMappings) { this.WriteObject( networkMappings.Select(nm => new ASRNetworkMapping(nm)), true); } /// <summary> /// Get Azure to Azure Network mapping. /// </summary> private void GetNetworkMappingByFabric() { if (string.Equals( this.PrimaryFabric.FabricType, Constants.Azure, StringComparison.InvariantCultureIgnoreCase)) { if (string.IsNullOrEmpty(this.Name)) { var networkMappingList = RecoveryServicesClient.GetAzureSiteRecoveryNetworkMappings( this.PrimaryFabric.Name, ARMResourceTypeConstants.AzureNetwork); this.WriteNetworkMappings(networkMappingList); } else { var networkMapping = RecoveryServicesClient.GetAzureSiteRecoveryNetworkMappings( this.PrimaryFabric.Name, ARMResourceTypeConstants.AzureNetwork, this.Name); this.WriteNetworkMapping(networkMapping); } } else { var networks = this.RecoveryServicesClient.GetAzureSiteRecoveryNetworks(this.PrimaryFabric.Name); foreach (var network in networks) { this.Network = new ASRNetwork(network); this.ByObject(); } } } } }
38.988439
119
0.546182
[ "MIT" ]
Philippe-Morin/azure-powershell
src/ResourceManager/RecoveryServices.SiteRecovery/Commands.RecoveryServices.SiteRecovery/Network/GetAzureRmRecoveryServicesAsrNetworkMapping.cs
6,573
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using Azure; using Azure.Core; namespace Bicep.Core.RegistryClient { internal partial class ContainerRegistryBlobUploadChunkHeaders { private readonly Response _response; public ContainerRegistryBlobUploadChunkHeaders(Response response) { _response = response; } /// <summary> Provided location for blob. </summary> public string Location => _response.Headers.TryGetValue("Location", out string value) ? value : null; /// <summary> Range indicating the current progress of the upload. </summary> public string Range => _response.Headers.TryGetValue("Range", out string value) ? value : null; /// <summary> Identifies the docker upload uuid for the current request. </summary> public string DockerUploadUuid => _response.Headers.TryGetValue("Docker-Upload-UUID", out string value) ? value : null; } }
37.25
127
0.697987
[ "MIT" ]
Agazoth/bicep
src/Bicep.Core.RegistryClient/generated/ContainerRegistryBlobUploadChunkHeaders.cs
1,043
C#
namespace RhSystem.Repositories { using RhSystem.Seeders; using RhSystem.Repositories.Services; using RhSystem.Repositories.IServices; using Microsoft.Extensions.DependencyInjection; using RhSystem.Repositories.IServices.ISeederService; public class RegisterService { public void Register(ref IServiceCollection services) { services.AddScoped<ITokenService, TokenService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IUserRulesService, UserRulesService>(); services.AddScoped<IFirstInstallSeederService, FirstInstallSeederService>(); } } }
35.315789
88
0.71535
[ "MIT" ]
GUSTAVPEREIRA/RhSystem
RhSystem/Repositories/RegisterService.cs
673
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. ==================================================================== */ namespace NPOI.SS.Formula { using System; using System.Collections.Generic; using System.Text; using NPOI.SS.Formula.PTG; /** * @author Josh Micich */ public class FormulaShifter { public enum ShiftMode { Row, Sheet } /** * Extern sheet index of sheet where moving is occurring */ private int _externSheetIndex; private int _firstMovedIndex; private int _lastMovedIndex; private int _amountToMove; private int _srcSheetIndex; private int _dstSheetIndex; private ShiftMode _mode; private FormulaShifter(int externSheetIndex, int firstMovedIndex, int lastMovedIndex, int amountToMove) { if (amountToMove == 0) { throw new ArgumentException("amountToMove must not be zero"); } if (firstMovedIndex > lastMovedIndex) { throw new ArgumentException("firstMovedIndex, lastMovedIndex out of order"); } _externSheetIndex = externSheetIndex; _firstMovedIndex = firstMovedIndex; _lastMovedIndex = lastMovedIndex; _amountToMove = amountToMove; _mode = ShiftMode.Row; _srcSheetIndex = _dstSheetIndex = -1; } /** * Create an instance for shifting sheets. * * For example, this will be called on {@link org.apache.poi.hssf.usermodel.HSSFWorkbook#setSheetOrder(String, int)} */ private FormulaShifter(int srcSheetIndex, int dstSheetIndex) { _externSheetIndex = _firstMovedIndex = _lastMovedIndex = _amountToMove = -1; _srcSheetIndex = srcSheetIndex; _dstSheetIndex = dstSheetIndex; _mode = ShiftMode.Sheet; } public static FormulaShifter CreateForRowShift(int externSheetIndex, int firstMovedRowIndex, int lastMovedRowIndex, int numberOfRowsToMove) { return new FormulaShifter(externSheetIndex, firstMovedRowIndex, lastMovedRowIndex, numberOfRowsToMove); } public static FormulaShifter CreateForSheetShift(int srcSheetIndex, int dstSheetIndex) { return new FormulaShifter(srcSheetIndex, dstSheetIndex); } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append(GetType().Name); sb.Append(" ["); sb.Append(_firstMovedIndex); sb.Append(_lastMovedIndex); sb.Append(_amountToMove); return sb.ToString(); } /** * @param ptgs - if necessary, will get modified by this method * @param currentExternSheetIx - the extern sheet index of the sheet that contains the formula being adjusted * @return <c>true</c> if a change was made to the formula tokens */ public bool AdjustFormula(Ptg[] ptgs, int currentExternSheetIx) { bool refsWereChanged = false; for (int i = 0; i < ptgs.Length; i++) { Ptg newPtg = AdjustPtg(ptgs[i], currentExternSheetIx); if (newPtg != null) { refsWereChanged = true; ptgs[i] = newPtg; } } return refsWereChanged; } private Ptg AdjustPtg(Ptg ptg, int currentExternSheetIx) { //return AdjustPtgDueToRowMove(ptg, currentExternSheetIx); switch (_mode) { case ShiftMode.Row: return AdjustPtgDueToRowMove(ptg, currentExternSheetIx); case ShiftMode.Sheet: return AdjustPtgDueToShiftMove(ptg); default: throw new InvalidOperationException("Unsupported shift mode: " + _mode); } } /** * @return <c>true</c> if this Ptg needed to be changed */ private Ptg AdjustPtgDueToRowMove(Ptg ptg, int currentExternSheetIx) { if (ptg is RefPtg) { if (currentExternSheetIx != _externSheetIndex) { // local refs on other sheets are unaffected return null; } RefPtg rptg = (RefPtg)ptg; return RowMoveRefPtg(rptg); } if (ptg is Ref3DPtg) { Ref3DPtg rptg = (Ref3DPtg)ptg; if (_externSheetIndex != rptg.ExternSheetIndex) { // only move 3D refs that refer to the sheet with cells being moved // (currentExternSheetIx is irrelevant) return null; } return RowMoveRefPtg(rptg); } if (ptg is Area2DPtgBase) { if (currentExternSheetIx != _externSheetIndex) { // local refs on other sheets are unaffected return ptg; } return RowMoveAreaPtg((Area2DPtgBase)ptg); } if (ptg is Area3DPtg) { Area3DPtg aptg = (Area3DPtg)ptg; if (_externSheetIndex != aptg.ExternSheetIndex) { // only move 3D refs that refer to the sheet with cells being moved // (currentExternSheetIx is irrelevant) return null; } return RowMoveAreaPtg(aptg); } return null; } private Ptg AdjustPtgDueToShiftMove(Ptg ptg) { Ptg updatedPtg = null; if (ptg is Ref3DPtg) { Ref3DPtg ref1 = (Ref3DPtg)ptg; if (ref1.ExternSheetIndex == _srcSheetIndex) { ref1.ExternSheetIndex = (_dstSheetIndex); updatedPtg = ref1; } else if (ref1.ExternSheetIndex == _dstSheetIndex) { ref1.ExternSheetIndex = (_srcSheetIndex); updatedPtg = ref1; } } return updatedPtg; } private Ptg RowMoveRefPtg(RefPtgBase rptg) { int refRow = rptg.Row; if (_firstMovedIndex <= refRow && refRow <= _lastMovedIndex) { // Rows being moved completely enclose the ref. // - move the area ref along with the rows regardless of destination rptg.Row = (refRow + _amountToMove); return rptg; } // else rules for adjusting area may also depend on the destination of the moved rows int destFirstRowIndex = _firstMovedIndex + _amountToMove; int destLastRowIndex = _lastMovedIndex + _amountToMove; // ref is outside source rows // check for clashes with destination if (destLastRowIndex < refRow || refRow < destFirstRowIndex) { // destination rows are completely outside ref return null; } if (destFirstRowIndex <= refRow && refRow <= destLastRowIndex) { // destination rows enclose the area (possibly exactly) return CreateDeletedRef(rptg); } throw new InvalidOperationException("Situation not covered: (" + _firstMovedIndex + ", " + _lastMovedIndex + ", " + _amountToMove + ", " + refRow + ", " + refRow + ")"); } private Ptg RowMoveAreaPtg(AreaPtgBase aptg) { int aFirstRow = aptg.FirstRow; int aLastRow = aptg.LastRow; if (_firstMovedIndex <= aFirstRow && aLastRow <= _lastMovedIndex) { // Rows being moved completely enclose the area ref. // - move the area ref along with the rows regardless of destination aptg.FirstRow = (aFirstRow + _amountToMove); aptg.LastRow = (aLastRow + _amountToMove); return aptg; } // else rules for adjusting area may also depend on the destination of the moved rows int destFirstRowIndex = _firstMovedIndex + _amountToMove; int destLastRowIndex = _lastMovedIndex + _amountToMove; if (aFirstRow < _firstMovedIndex && _lastMovedIndex < aLastRow) { // Rows moved were originally *completely* within the area ref // If the destination of the rows overlaps either the top // or bottom of the area ref there will be a change if (destFirstRowIndex < aFirstRow && aFirstRow <= destLastRowIndex) { // truncate the top of the area by the moved rows aptg.FirstRow = (destLastRowIndex + 1); return aptg; } else if (destFirstRowIndex <= aLastRow && aLastRow < destLastRowIndex) { // truncate the bottom of the area by the moved rows aptg.LastRow = (destFirstRowIndex - 1); return aptg; } // else - rows have moved completely outside the area ref, // or still remain completely within the area ref return null; // - no change to the area } if (_firstMovedIndex <= aFirstRow && aFirstRow <= _lastMovedIndex) { // Rows moved include the first row of the area ref, but not the last row // btw: (aLastRow > _lastMovedIndex) if (_amountToMove < 0) { // simple case - expand area by shifting top upward aptg.FirstRow = (aFirstRow + _amountToMove); return aptg; } if (destFirstRowIndex > aLastRow) { // in this case, excel ignores the row move return null; } int newFirstRowIx = aFirstRow + _amountToMove; if (destLastRowIndex < aLastRow) { // end of area is preserved (will remain exact same row) // the top area row is moved simply aptg.FirstRow = (newFirstRowIx); return aptg; } // else - bottom area row has been replaced - both area top and bottom may move now int areaRemainingTopRowIx = _lastMovedIndex + 1; if (destFirstRowIndex > areaRemainingTopRowIx) { // old top row of area has moved deep within the area, and exposed a new top row newFirstRowIx = areaRemainingTopRowIx; } aptg.FirstRow = (newFirstRowIx); aptg.LastRow = (Math.Max(aLastRow, destLastRowIndex)); return aptg; } if (_firstMovedIndex <= aLastRow && aLastRow <= _lastMovedIndex) { // Rows moved include the last row of the area ref, but not the first // btw: (aFirstRow < _firstMovedIndex) if (_amountToMove > 0) { // simple case - expand area by shifting bottom downward aptg.LastRow = (aLastRow + _amountToMove); return aptg; } if (destLastRowIndex < aFirstRow) { // in this case, excel ignores the row move return null; } int newLastRowIx = aLastRow + _amountToMove; if (destFirstRowIndex > aFirstRow) { // top of area is preserved (will remain exact same row) // the bottom area row is moved simply aptg.LastRow = (newLastRowIx); return aptg; } // else - top area row has been replaced - both area top and bottom may move now int areaRemainingBottomRowIx = _firstMovedIndex - 1; if (destLastRowIndex < areaRemainingBottomRowIx) { // old bottom row of area has moved up deep within the area, and exposed a new bottom row newLastRowIx = areaRemainingBottomRowIx; } aptg.FirstRow = (Math.Min(aFirstRow, destFirstRowIndex)); aptg.LastRow = (newLastRowIx); return aptg; } // else source rows include none of the rows of the area ref // check for clashes with destination if (destLastRowIndex < aFirstRow || aLastRow < destFirstRowIndex) { // destination rows are completely outside area ref return null; } if (destFirstRowIndex <= aFirstRow && aLastRow <= destLastRowIndex) { // destination rows enclose the area (possibly exactly) return CreateDeletedRef(aptg); } if (aFirstRow <= destFirstRowIndex && destLastRowIndex <= aLastRow) { // destination rows are within area ref (possibly exact on top or bottom, but not both) return null; // - no change to area } if (destFirstRowIndex < aFirstRow && aFirstRow <= destLastRowIndex) { // dest rows overlap top of area // - truncate the top aptg.FirstRow = (destLastRowIndex + 1); return aptg; } if (destFirstRowIndex < aLastRow && aLastRow <= destLastRowIndex) { // dest rows overlap bottom of area // - truncate the bottom aptg.LastRow = (destFirstRowIndex - 1); return aptg; } throw new InvalidOperationException("Situation not covered: (" + _firstMovedIndex + ", " + _lastMovedIndex + ", " + _amountToMove + ", " + aFirstRow + ", " + aLastRow + ")"); } private static Ptg CreateDeletedRef(Ptg ptg) { if (ptg is RefPtg) { return new RefErrorPtg(); } if (ptg is Ref3DPtg) { Ref3DPtg rptg = (Ref3DPtg)ptg; return new DeletedRef3DPtg(rptg.ExternSheetIndex); } if (ptg is AreaPtg) { return new AreaErrPtg(); } if (ptg is Area3DPtg) { Area3DPtg area3DPtg = (Area3DPtg)ptg; return new DeletedArea3DPtg(area3DPtg.ExternSheetIndex); } throw new ArgumentException("Unexpected ref ptg class (" + ptg.GetType().Name + ")"); } } }
41.346633
148
0.511701
[ "Apache-2.0" ]
sunshinele/npoi
main/SS/Formula/PTG/FormulaShifter.cs
16,580
C#
using System; namespace NetToolBox.HealthChecks.AzureFunctionTimer { public sealed class TimerTriggerHealthResult { public DateTimeOffset LastCompletionTime { get; set; } public DateTimeOffset LastExpectedCompletionTime { get; set; } public bool IsTimerDisabled { get; set; } } }
26.5
70
0.716981
[ "MIT" ]
npnelson/HealthChecks
src/NetToolBox.HealthChecks.AzureFunctionTimer/TimerTriggerHealthResult.cs
320
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetFieldLevelEncryption operation /// </summary> public class GetFieldLevelEncryptionResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { GetFieldLevelEncryptionResponse response = new GetFieldLevelEncryptionResponse(); UnmarshallResult(context,response); if (context.ResponseData.IsHeaderPresent("ETag")) response.ETag = context.ResponseData.GetHeaderValue("ETag"); return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, GetFieldLevelEncryptionResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("FieldLevelEncryption", targetDepth)) { var unmarshaller = FieldLevelEncryptionUnmarshaller.Instance; response.FieldLevelEncryption = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDenied")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchFieldLevelEncryptionConfig")) { return NoSuchFieldLevelEncryptionConfigExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonCloudFrontException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static GetFieldLevelEncryptionResponseUnmarshaller _instance = new GetFieldLevelEncryptionResponseUnmarshaller(); internal static GetFieldLevelEncryptionResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetFieldLevelEncryptionResponseUnmarshaller Instance { get { return _instance; } } } }
38.553846
165
0.634278
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/GetFieldLevelEncryptionResponseUnmarshaller.cs
5,012
C#
//----------------------------------------------------------------------- // <copyright file="DiResolverSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Threading.Tasks; using Akka.Actor; using Akka.Configuration; using Akka.DI.Core; using Akka.Dispatch; using Akka.TestKit; using Akka.TestKit.TestActors; using Akka.TestKit.Xunit2; using Akka.Util; using Akka.Util.Internal; using Xunit; namespace Akka.DI.TestKit { public abstract class DiResolverSpec : TestKitBase, IDisposable { #region DI classes class GetCallCount { } class DiPerRequestActor : ReceiveActor { private readonly IDiTest _di; public DiPerRequestActor(IDiTest di) { _di = di; Receive<GetCallCount>(count => Sender.Tell(_di.CallCount)); ReceiveAny(o => _di.Call()); } } class DiSingletonActor : ReceiveActor { private readonly IDiSingleton _di; public DiSingletonActor(IDiSingleton di) { _di = di; Receive<GetCallCount>(count => Sender.Tell(_di.CallCount)); ReceiveAny(o => _di.Call()); } } class DiParentActor : ReceiveActor { private IActorRef _child; public class GetChild { } public DiParentActor() { Receive<GetChild>(c => Sender.Tell(_child)); } protected override void PreStart() { var childProps = Context.DI().Props<DiPerRequestActor>(); _child = Context.ActorOf(childProps); } } class DisposableActor : ReceiveActor { public class Restart { } public class GetHashCode { } private readonly IDiDisposable _di; public DisposableActor(IDiDisposable di) { _di = di; Receive<GetHashCode>(g => Sender.Tell(_di.GetHashCode())); Receive<Restart>(r => ForceRestart()); } private void ForceRestart() { throw new Exception("RESTART ME!"); } } interface IDiTest { int CallCount { get; } void Call(); } class ConcreteDiTest : IDiTest { public int CallCount { get; private set; } public void Call() { CallCount = CallCount + 1; } } interface IDiSingleton { int CallCount { get; } void Call(); } class ConcreteDiSingleton : IDiSingleton { AtomicCounter _counter = new AtomicCounter(0); public int CallCount { get { return _counter.Current; }} public void Call() { _counter.GetAndIncrement(); } } interface IDiDisposable : IDisposable { bool WasDisposed { get; } } class ConcreteDiDisposable : IDiDisposable { private readonly AtomicCounter _disposeCounter; public ConcreteDiDisposable(AtomicCounter disposeCounter) { _disposeCounter = disposeCounter; } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool isDisposing) { if (!WasDisposed) { WasDisposed = true; _disposeCounter.Next(); } } public bool WasDisposed { get; private set; } } private static readonly IDiSingleton Single = new ConcreteDiSingleton(); class UnboundedStashActor : BlackHoleActor, IWithUnboundedStash { private readonly IDiTest _di; public UnboundedStashActor(IDiTest di) { _di = di; } public IStash Stash { get; set; } } class BoundedStashActor : BlackHoleActor, IWithBoundedStash { private readonly IDiTest _di; public BoundedStashActor(IDiTest di) { _di = di; } public IStash Stash { get; set; } } #endregion private static readonly AtomicCounter Counter = new AtomicCounter(0); private string _pid; protected int ActorInstanceId = 1; public string Pid { get { return _pid; } } private AtomicCounter _disposeCounter = new AtomicCounter(0); protected DiResolverSpec(Config config = null, string actorSystemName = null, string testActorName = null) : base(new XunitAssertions(), config, actorSystemName, testActorName) { _pid = "p-" + Counter.IncrementAndGet(); // ReSharper disable once DoNotCallOverridableMethodsInConstructor var resolver = ConfigureDependencyResolver(Sys); } /// <summary> /// Creates and configures a brand new <see cref="IDependencyResolver"/>. /// </summary> /// <returns>A new <see cref="IDependencyResolver"/> configured using the provided DI generator.</returns> protected IDependencyResolver ConfigureDependencyResolver(ActorSystem system) { var container = NewDiContainer(); Bind<IDiTest>(container, () => new ConcreteDiTest()); Bind<IDiSingleton>(container, () => Single); Bind<IDiDisposable>(container, () => new ConcreteDiDisposable(_disposeCounter)); Bind<DisposableActor>(container); Bind<DiPerRequestActor>(container); Bind<DiSingletonActor>(container); return NewDependencyResolver(container, system); } #region Abstract methods /// <summary> /// Create a new instance of the Dependency Injection container that we're creating. /// </summary> /// <returns>A new DI container instance.</returns> protected abstract object NewDiContainer(); /// <summary> /// Create a new <see cref="IDependencyResolver"/> instance that we're going to use /// in the context of all of our tests. /// </summary> /// <returns>An <see cref="IDependencyResolver"/> instance.</returns> protected abstract IDependencyResolver NewDependencyResolver(object diContainer, ActorSystem system); /// <summary> /// Create a binding for type <typeparam name="T"/> on the provided DI container. /// </summary> /// <typeparam name="T">The type we're binding onto the DI container.</typeparam> /// <param name="diContainer">The DI container.</param> /// <param name="generator">A generator function that yields new objects of type <typeparam name="T"/>.</param> protected abstract void Bind<T>(object diContainer, Func<T> generator); /// <summary> /// Create a binding for type <typeparam name="T"/> on the provided DI container. /// /// Used for DI frameworks that require the DI target to be registered as well /// as the injected components. /// </summary> /// <typeparam name="T">The type we're binding onto the DI container.</typeparam> /// <param name="diContainer">The DI container.</param> protected abstract void Bind<T>(object diContainer); #endregion #region Tests [Fact] public void DependencyResolver_should_inject_new_instances_into_DiPerRequestActor() { var diActorProps = Sys.DI().Props<DiPerRequestActor>(); var diActor1 = Sys.ActorOf(diActorProps); var diActor2 = Sys.ActorOf(diActorProps); diActor1.Tell("increment 1"); diActor1.Tell("increment 2"); diActor2.Tell("increment 1"); diActor1.Tell(new GetCallCount()); Assert.Equal(2, ExpectMsg<int>()); diActor2.Tell(new GetCallCount()); Assert.Equal(1, ExpectMsg<int>()); } [Fact] public void DependencyResolver_should_inject_new_instances_on_Restart() { var disposableActorProps = Sys.DI().Props<DisposableActor>(); var disposableActor = Sys.ActorOf(disposableActorProps); disposableActor.Tell(new DisposableActor.GetHashCode()); var originalHashCode = ExpectMsg<int>(); disposableActor.Tell(new DisposableActor.Restart()); disposableActor.Tell(new DisposableActor.GetHashCode()); var nextHashCode = ExpectMsg<int>(); Assert.NotEqual(originalHashCode, nextHashCode); } [Fact] public void DependencyResolver_should_inject_same_instance_into_DiSingletonActor() { var diActorProps = Sys.DI().Props<DiSingletonActor>(); var diActor1 = Sys.ActorOf(diActorProps); var diActor2 = Sys.ActorOf(diActorProps); diActor1.Tell("increment 1"); diActor1.Tell("increment 2"); diActor2.Tell("increment 1"); diActor1.Tell(new Identify(null)); diActor2.Tell(new Identify(null)); ExpectMsg<ActorIdentity>(); ExpectMsg<ActorIdentity>(); diActor1.Tell(new GetCallCount()); Assert.Equal(3, ExpectMsg<int>()); diActor2.Tell(new GetCallCount()); Assert.Equal(3, ExpectMsg<int>()); } [Fact] public void DependencyResolver_should_inject_instances_into_DiChildActor() { var diParent = Sys.ActorOf(Props.Create<DiParentActor>()); diParent.Tell(new DiParentActor.GetChild()); var child = ExpectMsg<IActorRef>(); child.Tell("increment 1"); child.Tell("increment 2"); child.Tell(new GetCallCount()); Assert.Equal(2, ExpectMsg<int>()); } [Fact] public void DependencyResolver_should_inject_into_normal_mailbox_Actor() { var stashActorProps = Sys.DI().Props<DiPerRequestActor>(); var stashActor = Sys.ActorOf(stashActorProps); var internalRef = (LocalActorRef)stashActor; Assert.IsType<UnboundedMailbox>(internalRef.Cell.Mailbox); } [Fact] public void DependencyResolver_should_inject_into_UnboundedStash_Actor() { var stashActorProps = Sys.DI().Props<UnboundedStashActor>(); var stashActor = Sys.ActorOf(stashActorProps); var internalRef = (LocalActorRef) stashActor; Assert.IsType<UnboundedDequeBasedMailbox>(internalRef.Cell.Mailbox); } [Fact] public void DependencyResolver_should_inject_into_BoundedStash_Actor() { var stashActorProps = Sys.DI().Props<BoundedStashActor>(); var stashActor = Sys.ActorOf(stashActorProps); var internalRef = (LocalActorRef)stashActor; Assert.IsType<BoundedDequeBasedMailbox>(internalRef.Cell.Mailbox); } [Fact] public void DependencyResolver_should_dispose_IDisposable_instances_on_Actor_Termination() { var disposableActorProps = Sys.DI().Props<DisposableActor>(); var disposableActor = Sys.ActorOf(disposableActorProps); var currentDisposeCounter = _disposeCounter.Current; Assert.True(disposableActor.GracefulStop(TimeSpan.FromSeconds(1)).Result); AwaitAssert(() => Assert.True(currentDisposeCounter + 1 == _disposeCounter.Current), TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50)); } [Fact] public void DependencyResolver_should_dispose_IDisposable_instances_on_Actor_Restart() { var disposableActorProps = Sys.DI().Props<DisposableActor>(); var disposableActor = Sys.ActorOf(disposableActorProps); var currentDisposeCounter = _disposeCounter.Current; disposableActor.Tell(new DisposableActor.Restart()); AwaitAssert(() => Assert.True(currentDisposeCounter + 1 == _disposeCounter.Current), TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50)); } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) Shutdown(); } } }
32.5025
153
0.577879
[ "Apache-2.0" ]
to11mtm/akka.net
src/contrib/dependencyInjection/Akka.DI.TestKit/DiResolverSpec.cs
13,003
C#
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using JsonSubTypes; using Newtonsoft.Json; using Bitmovin.Api.Sdk.Common; using Bitmovin.Api.Sdk.Models; namespace Bitmovin.Api.Sdk.Models { /// <summary> /// DashMp4Representation /// </summary> public class DashMp4Representation : DashRepresentation { /// <summary> /// Path to the MP4 file (required) /// </summary> [JsonProperty(PropertyName = "filePath")] public string FilePath { get; set; } /// <summary> /// The type of the dash representation /// </summary> [JsonProperty(PropertyName = "type")] public DashOnDemandRepresentationType? Type { get; set; } } }
25.290323
65
0.646684
[ "MIT" ]
bitmovin/bitmovin-api-sdk-dotnet
src/Bitmovin.Api.Sdk/Models/DashMp4Representation.cs
784
C#
namespace Hotel.Web.ViewModels.Rooms { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Hotel.Data.Models; using Hotel.Services.Mapping; using Hotel.Web.ViewModels.RoomTypes; using Microsoft.AspNetCore.Http; public class AddRoomInputModel : IMapFrom<Room>, IMapTo<Room> { public AddRoomInputModel() { this.ListOfRoomTypes = new HashSet<RoomTypeDropDownViewModel>(); } [Required] [MinLength(1)] [MaxLength(20)] public string RoomNumber { get; set; } [Required] public string RoomTypeId { get; set; } [MinLength(1)] [MaxLength(100)] public string Description { get; set; } public string HotelDataId { get; set; } public IEnumerable<RoomTypeDropDownViewModel> ListOfRoomTypes { get; set; } } }
25.571429
83
0.635754
[ "MIT" ]
BoryanaLen/FinalWebProject
Web/Hotel.Web.ViewModels/Rooms/AddRoomInputModel.cs
897
C#
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Mayfly.Akinator.Utils { public class AkiWebClient : IDisposable { private readonly HttpClient m_webClient; public AkiWebClient() { m_webClient = new HttpClient(new HttpClientHandler { UseCookies = false }); m_webClient.DefaultRequestHeaders.Add("Accept", "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01"); m_webClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.9,ar;q=0.8"); m_webClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest"); m_webClient.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty"); m_webClient.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors"); m_webClient.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin"); m_webClient.DefaultRequestHeaders.Add("Connection", "keep-alive"); m_webClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36"); m_webClient.DefaultRequestHeaders.Add("Referer", "https://en.akinator.com/game"); } public Task<HttpResponseMessage> GetAsync(string url, CancellationToken cancellationToken = default) { return m_webClient.GetAsync(url, cancellationToken); } public void Dispose() { m_webClient?.Dispose(); } } }
35.9
173
0.746518
[ "MIT" ]
Kerillian/Mayfly
Mayfly/Akinator/Utils/AkiWebClient.cs
1,438
C#
using S2VX.Game.Editor.ToolState; using S2VX.Game.Story; using S2VX.Game.Story.Note; namespace S2VX.Game.Editor.Reversible { public class ReversibleAddHoldNote : IReversible { private EditorScreen Editor { get; set; } private S2VXStory Story { get; set; } private HoldNote Note { get; } public ReversibleAddHoldNote(S2VXStory story, HoldNote note, EditorScreen editor) { Story = story; Note = note; Editor = editor; } public void Undo() { Story.RemoveNote(Note); if (Editor.ToolState is SelectToolState selectTool) { selectTool.ClearNoteSelection(); } } public void Redo() { Story.AddNote(Note); if (Editor.ToolState is SelectToolState selectTool) { selectTool.ClearNoteSelection(); selectTool.AddNoteSelection(Note); } } } }
28.470588
91
0.580579
[ "MIT" ]
maxrchung/S2VX
S2VX.Game/Editor/Reversible/ReversibleAddHoldNote.cs
970
C#
using System; using System.Collections.Generic; using System.Text; namespace DefiningClasses { public class Car { public string Model { get; set; } public Engine Engine { get; set; } public Cargo Cargo { get; set; } public List<Tire> Tires { get; set; } public Car(string model, Engine engine, Cargo cargo, List<Tire> tires) { this.Model = model; this.Engine = engine; this.Cargo = cargo; this.Tires = tires; } } }
23.25
79
0.537634
[ "MIT" ]
NenovaRositsa/CSharp-Advanced
05DefiningClasses/07RawData/Car.cs
560
C#
using System.Drawing; using System.IO; using System.Windows.Media.Imaging; namespace QPAS { public static class BitmapSourceExtensions { public static Bitmap ToBitmap(this BitmapSource bitmapsource) { Bitmap bitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapsource)); enc.Save(outStream); bitmap = new Bitmap(outStream); } return bitmap; } } }
26.173913
69
0.578073
[ "BSD-3-Clause" ]
esusini/QPAS
QPAS/ExtensionMethods/BitmapSourceExtensions.cs
604
C#
using Android.Hardware.Camera2; using Plugin.Xamarin.Controls.Droid.Classes; namespace Plugin.Xamarin.Controls.Droid.Listner { public class CameraCaptureSessionCallback : CameraCaptureSession.StateCallback { private readonly CameraDroidView owner; public CameraCaptureSessionCallback(CameraDroidView owner) { if (owner == null) throw new System.ArgumentNullException("owner"); this.owner = owner; } public override void OnConfigureFailed(CameraCaptureSession session) { owner.ShowToast("Failed"); } public override void OnConfigured(CameraCaptureSession session) { // The camera is already closed if (null == owner.mCameraDevice) { return; } // When the session is ready, we start displaying the preview. owner.mCaptureSession = session; //owner.updatePreview(); try { // Auto focus should be continuous for camera preview. owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture); // Flash is automatically enabled when necessary. owner.SetAutoFlash(owner.mPreviewRequestBuilder); // Finally, we start displaying the camera preview. owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build(); owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest, owner.mCaptureCallback, owner.mBackgroundHandler); } catch (CameraAccessException e) { e.PrintStackTrace(); } } } }
35.196078
117
0.6
[ "MIT" ]
dodesilva/Plugin.Xamarin.Controls
Plugin.Xamarin.Controls.Droid/Listner/CameraCaptureSessionCallback.cs
1,797
C#
// // StatePointer.cs // // Copyright (C) 2019 OpenTK // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // using System; namespace OpenTK.OpenAL.Extensions.Soft { /// <summary> /// A list of valid <see cref="IntPtr"/> <see cref="IStateSoft.GetPointer"/> parameters. /// </summary> public enum StatePointer { /// <summary> /// Gets a pointer to the set event callback function. /// </summary> EventCallbackFunction = 0x1220, /// <summary> /// Gets a pointer to the set event callback user parameter. /// </summary> EventCallbackUserParameter = 0x1221, } }
24.033333
92
0.618585
[ "MIT" ]
7Bpencil/opentk
src/OpenAL/OpenTK.OpenAL.Extensions/Soft/Enums/StatePointer.cs
721
C#
namespace Poseidon.Infrastructure.ClientDx { partial class RepairRecordGrid { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.colRepairId = new DevExpress.XtraGrid.Columns.GridColumn(); this.colModelType = new DevExpress.XtraGrid.Columns.GridColumn(); this.colFacilityName = new DevExpress.XtraGrid.Columns.GridColumn(); this.repoFacility = new DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit(); this.bsFacility = new System.Windows.Forms.BindingSource(this.components); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.colName = new DevExpress.XtraGrid.Columns.GridColumn(); this.colRemark1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.colStatus1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.colId1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.colItemName = new DevExpress.XtraGrid.Columns.GridColumn(); this.colCount = new DevExpress.XtraGrid.Columns.GridColumn(); this.colUnit = new DevExpress.XtraGrid.Columns.GridColumn(); this.colUnitPrice = new DevExpress.XtraGrid.Columns.GridColumn(); this.colTotalPrice = new DevExpress.XtraGrid.Columns.GridColumn(); this.colRemark = new DevExpress.XtraGrid.Columns.GridColumn(); this.colStatus = new DevExpress.XtraGrid.Columns.GridColumn(); this.colId = new DevExpress.XtraGrid.Columns.GridColumn(); this.colCalculatePrice = new DevExpress.XtraGrid.Columns.GridColumn(); this.colFacilityId = new DevExpress.XtraGrid.Columns.GridColumn(); this.colSpecification = new DevExpress.XtraGrid.Columns.GridColumn(); this.colRepairNumber = new DevExpress.XtraGrid.Columns.GridColumn(); ((System.ComponentModel.ISupportInitialize)(this.bsEntity)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgcEntity)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvEntity)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repoFacility)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsFacility)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); this.SuspendLayout(); // // bsEntity // this.bsEntity.DataSource = typeof(Poseidon.Infrastructure.Core.DL.RepairRecord); // // dgcEntity // this.dgcEntity.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.repoFacility}); this.dgcEntity.Size = new System.Drawing.Size(711, 390); // // dgvEntity // this.dgvEntity.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colRepairNumber, this.colRepairId, this.colModelType, this.colFacilityId, this.colFacilityName, this.colItemName, this.colSpecification, this.colCount, this.colUnit, this.colUnitPrice, this.colCalculatePrice, this.colTotalPrice, this.colRemark, this.colStatus, this.colId}); this.dgvEntity.IndicatorWidth = 40; this.dgvEntity.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; this.dgvEntity.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; this.dgvEntity.OptionsBehavior.Editable = false; this.dgvEntity.OptionsDetail.EnableMasterViewMode = false; this.dgvEntity.OptionsView.EnableAppearanceEvenRow = true; this.dgvEntity.OptionsView.EnableAppearanceOddRow = true; this.dgvEntity.OptionsView.ShowGroupPanel = false; this.dgvEntity.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(this.dgvEntity_CellValueChanged); this.dgvEntity.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(this.dgvEntity_CustomUnboundColumnData); // // colRepairId // this.colRepairId.FieldName = "RepairId"; this.colRepairId.Name = "colRepairId"; // // colModelType // this.colModelType.Caption = "设施模型类型"; this.colModelType.FieldName = "ModelType"; this.colModelType.Name = "colModelType"; this.colModelType.OptionsColumn.AllowEdit = false; // // colFacilityName // this.colFacilityName.Caption = "设施名称"; this.colFacilityName.FieldName = "FacilityName"; this.colFacilityName.Name = "colFacilityName"; this.colFacilityName.OptionsColumn.AllowEdit = false; this.colFacilityName.Visible = true; this.colFacilityName.VisibleIndex = 2; // // repoFacility // this.repoFacility.AutoHeight = false; this.repoFacility.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.repoFacility.DataSource = this.bsFacility; this.repoFacility.DisplayMember = "Name"; this.repoFacility.Name = "repoFacility"; this.repoFacility.NullText = "请选择设施"; this.repoFacility.ValueMember = "Id"; this.repoFacility.View = this.gridView1; // // bsFacility // this.bsFacility.DataSource = typeof(Poseidon.Core.DL.Facility); // // gridView1 // this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colName, this.colRemark1, this.colStatus1, this.colId1}); this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus; this.gridView1.Name = "gridView1"; this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false; this.gridView1.OptionsView.ShowGroupPanel = false; // // colName // this.colName.Caption = "名称"; this.colName.FieldName = "Name"; this.colName.Name = "colName"; this.colName.Visible = true; this.colName.VisibleIndex = 0; // // colRemark1 // this.colRemark1.Caption = "备注"; this.colRemark1.FieldName = "Remark"; this.colRemark1.Name = "colRemark1"; this.colRemark1.Visible = true; this.colRemark1.VisibleIndex = 1; // // colStatus1 // this.colStatus1.FieldName = "Status"; this.colStatus1.Name = "colStatus1"; // // colId1 // this.colId1.FieldName = "Id"; this.colId1.Name = "colId1"; // // colItemName // this.colItemName.Caption = "项目名称"; this.colItemName.FieldName = "ItemName"; this.colItemName.Name = "colItemName"; this.colItemName.Visible = true; this.colItemName.VisibleIndex = 3; // // colCount // this.colCount.Caption = "数量"; this.colCount.FieldName = "Count"; this.colCount.Name = "colCount"; this.colCount.Visible = true; this.colCount.VisibleIndex = 5; // // colUnit // this.colUnit.Caption = "单位"; this.colUnit.FieldName = "Unit"; this.colUnit.Name = "colUnit"; this.colUnit.Visible = true; this.colUnit.VisibleIndex = 6; // // colUnitPrice // this.colUnitPrice.Caption = "单价"; this.colUnitPrice.FieldName = "UnitPrice"; this.colUnitPrice.Name = "colUnitPrice"; this.colUnitPrice.Visible = true; this.colUnitPrice.VisibleIndex = 7; // // colTotalPrice // this.colTotalPrice.Caption = "总价(元)"; this.colTotalPrice.FieldName = "TotalPrice"; this.colTotalPrice.Name = "colTotalPrice"; this.colTotalPrice.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Sum, "TotalPrice", "合计={0:0.##}")}); this.colTotalPrice.Visible = true; this.colTotalPrice.VisibleIndex = 9; // // colRemark // this.colRemark.Caption = "备注"; this.colRemark.FieldName = "Remark"; this.colRemark.Name = "colRemark"; this.colRemark.Visible = true; this.colRemark.VisibleIndex = 10; // // colStatus // this.colStatus.FieldName = "Status"; this.colStatus.Name = "colStatus"; // // colId // this.colId.FieldName = "Id"; this.colId.Name = "colId"; // // colCalculatePrice // this.colCalculatePrice.Caption = "计算总价(元)"; this.colCalculatePrice.FieldName = "colCalculatePrice"; this.colCalculatePrice.Name = "colCalculatePrice"; this.colCalculatePrice.OptionsColumn.AllowEdit = false; this.colCalculatePrice.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Sum, "colCalculatePrice", "合计={0:0.##}")}); this.colCalculatePrice.UnboundExpression = "[Count] * [UnitPrice]"; this.colCalculatePrice.UnboundType = DevExpress.Data.UnboundColumnType.Decimal; this.colCalculatePrice.Visible = true; this.colCalculatePrice.VisibleIndex = 8; // // colFacilityId // this.colFacilityId.Caption = "设施名称"; this.colFacilityId.ColumnEdit = this.repoFacility; this.colFacilityId.FieldName = "FacilityId"; this.colFacilityId.Name = "colFacilityId"; this.colFacilityId.Visible = true; this.colFacilityId.VisibleIndex = 1; // // colSpecification // this.colSpecification.Caption = "规格型号"; this.colSpecification.FieldName = "Specification"; this.colSpecification.Name = "colSpecification"; this.colSpecification.Visible = true; this.colSpecification.VisibleIndex = 4; // // colRepairNumber // this.colRepairNumber.Caption = "序号"; this.colRepairNumber.FieldName = "colRepairNumber"; this.colRepairNumber.Name = "colRepairNumber"; this.colRepairNumber.OptionsColumn.AllowEdit = false; this.colRepairNumber.UnboundType = DevExpress.Data.UnboundColumnType.String; this.colRepairNumber.Visible = true; this.colRepairNumber.VisibleIndex = 0; // // RepairRecordGrid // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Name = "RepairRecordGrid"; this.Size = new System.Drawing.Size(711, 390); this.Load += new System.EventHandler(this.RepairRecordGrid_Load); ((System.ComponentModel.ISupportInitialize)(this.bsEntity)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgcEntity)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvEntity)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repoFacility)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsFacility)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraGrid.Columns.GridColumn colRepairId; private DevExpress.XtraGrid.Columns.GridColumn colModelType; private DevExpress.XtraGrid.Columns.GridColumn colFacilityName; private DevExpress.XtraGrid.Columns.GridColumn colItemName; private DevExpress.XtraGrid.Columns.GridColumn colCount; private DevExpress.XtraGrid.Columns.GridColumn colUnit; private DevExpress.XtraGrid.Columns.GridColumn colUnitPrice; private DevExpress.XtraGrid.Columns.GridColumn colCalculatePrice; private DevExpress.XtraGrid.Columns.GridColumn colTotalPrice; private DevExpress.XtraGrid.Columns.GridColumn colRemark; private DevExpress.XtraGrid.Columns.GridColumn colStatus; private DevExpress.XtraGrid.Columns.GridColumn colId; private System.Windows.Forms.BindingSource bsFacility; private DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit repoFacility; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraGrid.Columns.GridColumn colName; private DevExpress.XtraGrid.Columns.GridColumn colRemark1; private DevExpress.XtraGrid.Columns.GridColumn colStatus1; private DevExpress.XtraGrid.Columns.GridColumn colId1; private DevExpress.XtraGrid.Columns.GridColumn colFacilityId; private DevExpress.XtraGrid.Columns.GridColumn colSpecification; private DevExpress.XtraGrid.Columns.GridColumn colRepairNumber; } }
46.62069
158
0.606576
[ "MIT" ]
robertzml/Poseidon.Infrastructure
Poseidon.Infrastructure.ClientDx/Grid/RepairRecordGrid.Designer.cs
15,134
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("04. Distance between Points")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04. Distance between Points")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("ebda02a3-428a-4d00-8dfb-d3aae542379d")] // 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.432432
84
0.747539
[ "Apache-2.0" ]
vencislav-viktorov/VS-Console-App
Tech Module Extended/20.ObjectsandSimpleClasses-Lab/04. Distance between Points/Properties/AssemblyInfo.cs
1,425
C#
#region License // FLS - Fuzzy Logic Sharp for .NET // Copyright 2014 David Grupp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using FLS.Constants; using FLS.MembershipFunctions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FLS.Tests.MembershipFunctions { [TestFixture] public class BellMembershipFunctionTests { [SetUp] public void Setup() { } [Test] [TestCase(15, 3, 50, 50, 1)] [TestCase(15, 3, 50, 30, .151)] [TestCase(15, 3, 50, 70, .151)] public void Bell_Fuzzify_Success(double a, double b, double c, double inputValue, double expectedResult) { //Arrange var membershipFunction = new BellMembershipFunction("test", a, b, c); //Act var result = membershipFunction.Fuzzify(inputValue); //Assert Assert.That(Math.Round(result, 3), Is.EqualTo(expectedResult)); } [Test] public void Bell_Min_Success() { //Arrange var membershipFunction = new BellMembershipFunction("test", 10, 50, 20); //Act var result = membershipFunction.Min(); //Assert Assert.That(result, Is.EqualTo(0)); } [Test] public void Bell_Max_Success() { //Arrange var membershipFunction = new BellMembershipFunction("test", 10, 50, 20); //Act var result = membershipFunction.Max(); //Assert Assert.That(result, Is.EqualTo(200)); } [Test] [TestCase(ExpectedException = typeof(ArgumentException), ExpectedMessage = ErrorMessages.AArgumentIsInvalid)] public void Bell_InvalidInput() { //Arrange //Act var membershipFunction = new BellMembershipFunction("test", 0, 50, 10); //Assert } } }
23.787234
111
0.700805
[ "Apache-2.0" ]
Mailaender/Fuzzy-Logic-Sharp
FLS.Tests/MembershipFunctions/BellMembershipFunctionTests.cs
2,238
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Jarvis { class Program { public class Coreference { public Mention Root { get; set; } public IList<Mention> Mentions { get; set; } public Coreference() { Mentions = new List<Mention>(); } } static IList<Coreference> GetCoReferences(XElement document, IList<Sentence> Sentences) { List<Coreference> result = new List<Coreference>(); var coreferences = from c in document.Elements("document").Elements("coreference").Elements("coreference") select c; foreach (var item in coreferences) { var co = new Coreference(); var mentions = from c in item.Elements("mention") select c; Mention root = null; foreach (var mention in mentions) { var m = new Mention(); m.Read(mention); m.Head = Sentences.Where(c=>c.Id ==m.Sentence).First().Tokens.Where(c=>c.SentenceLoc == m.HeadLoc).First(); if (mention.Attributes("representative").Count() != 0) { co.Root = m; root = m; } else { m.Root = root; co.Mentions.Add(m); } } result.Add(co); } var Roots = result.Select(c => c.Root).ToList(); //obtain non root mention and avoid recursive mentions foreach (var coreference in result) { foreach (var mention in coreference.Mentions) { if (Roots.Where(c => c.Contains(mention)).Count() > 0) mention.Enable = false; } } return result; } static IList<Sentence> GetSentences(XElement document) { List<Sentence> result = new List<Sentence>(); var sentences = from c in document.Elements("document").Elements("sentences").Elements("sentence") select c; int id = 1; foreach (var sentence in sentences) { Sentence sen = new Sentence(); sen.Id = id; var tokens = from c in sentence.Elements("tokens").Elements("token") select c; int loc = 1; foreach (var token in tokens) { var m = new Token() { CharacterOffsetBegin = int.Parse(token.Element("CharacterOffsetBegin").Value), CharacterOffsetEnd = int.Parse(token.Element("CharacterOffsetEnd").Value), Id = int.Parse(token.Attribute("id").Value), Word = token.Element("word").Value, POS = token.Element("POS").Value }; m.SentenceLoc = loc; sen.Tokens.AddLast(m); loc++; } result.Add(sen); id++; } return result; } static void Main(string[] args) { var ValidTarget_Pos = new List<String>() { "PRP"}; var ValidReplace_Pos = new List<String>() { "NN", "NNS", "NNP", "NNPS" }; var directory = @"D:\Tesis2016\Jarvis\duc\02DocumentExpansion\Input\"; foreach (var item in Directory.GetFiles(directory, "*.xml")) { var sb_document = new StringBuilder(); var document = XElement.Load(item); var sentences = GetSentences(document); var references = GetCoReferences(document, sentences); foreach (var sentence in sentences) { #region coreference var senreference = from c in references.SelectMany(x => x.Mentions) where c.Sentence == sentence.Id && c.Enable && ValidTarget_Pos.Contains(c.Head.POS) && ValidReplace_Pos.Contains(c.Root.Head.POS) select c; //valid_pos.Contains( c.Head.POS) foreach (var core in senreference) { var start_token = sentence.Tokens.Where(c => c.SentenceLoc == core.Start).First(); var end_token = sentence.Tokens.Where(c => c.SentenceLoc == core.End - 1).First(); var cursor = sentence.Tokens.Find(start_token).Next; var replace = new List<Token>(); for (int i = 0; i < core.GetLen() - 1; i++) { replace.Add(cursor.Value); cursor = cursor.Next; } foreach (var del in replace) { sentence.Tokens.Remove(del); } cursor = sentence.Tokens.Find(start_token); cursor.Value = new Token() { Id = start_token.Id, CharacterOffsetBegin = start_token.CharacterOffsetBegin, CharacterOffsetEnd = end_token.CharacterOffsetEnd, //Word = string.Format("[{0}({1})| {2}({3})]", core.Text, core.Head.POS, core.Root.Text, core.Root.Head.POS) Word = core.Root.Text }; } #endregion StringBuilder sb_sentence = new StringBuilder(); foreach (var token in sentence.Tokens) { sb_sentence.Append(token.Word + " "); } sb_document.AppendLine(sb_sentence.ToString()); } File.WriteAllText(@"D:\Tesis2016\Jarvis\duc\02DocumentExpansion\Output\document_expansion.txt", sb_document.ToString()); } } } }
41.433735
137
0.431375
[ "Apache-2.0" ]
gcvalderrama/Jarvis
duc/02DocumentExpansion/Jarvis/Jarvis/Program.cs
6,880
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.V20170901Preview.Outputs { [OutputType] public sealed class SelfHostedIntegrationRuntimeNodeResponse { /// <summary> /// The integration runtime capabilities dictionary /// </summary> public readonly ImmutableDictionary<string, string> Capabilities; /// <summary> /// Maximum concurrent jobs on the integration runtime node. /// </summary> public readonly int ConcurrentJobsLimit; /// <summary> /// The time at which the integration runtime will expire in ISO8601 format. /// </summary> public readonly string ExpiryTime; /// <summary> /// URI for the host machine of the integration runtime. /// </summary> public readonly string HostServiceUri; /// <summary> /// Indicates whether this node is the active dispatcher for integration runtime requests. /// </summary> public readonly bool IsActiveDispatcher; /// <summary> /// The most recent time at which the integration runtime was connected in ISO8601 format. /// </summary> public readonly string LastConnectTime; /// <summary> /// The last time for the integration runtime node update end. /// </summary> public readonly string LastEndUpdateTime; /// <summary> /// The time the node last started up. /// </summary> public readonly string LastStartTime; /// <summary> /// The last time for the integration runtime node update start. /// </summary> public readonly string LastStartUpdateTime; /// <summary> /// The integration runtime node last stop time. /// </summary> public readonly string LastStopTime; /// <summary> /// The result of the last integration runtime node update. /// </summary> public readonly string LastUpdateResult; /// <summary> /// Machine name of the integration runtime node. /// </summary> public readonly string MachineName; /// <summary> /// The maximum concurrent jobs in this integration runtime. /// </summary> public readonly int MaxConcurrentJobs; /// <summary> /// Name of the integration runtime node. /// </summary> public readonly string NodeName; /// <summary> /// The time at which the integration runtime node was registered in ISO8601 format. /// </summary> public readonly string RegisterTime; /// <summary> /// Status of the integration runtime node. /// </summary> public readonly string Status; /// <summary> /// Version of the integration runtime node. /// </summary> public readonly string Version; /// <summary> /// Status of the integration runtime node version. /// </summary> public readonly string VersionStatus; [OutputConstructor] private SelfHostedIntegrationRuntimeNodeResponse( ImmutableDictionary<string, string> capabilities, int concurrentJobsLimit, string expiryTime, string hostServiceUri, bool isActiveDispatcher, string lastConnectTime, string lastEndUpdateTime, string lastStartTime, string lastStartUpdateTime, string lastStopTime, string lastUpdateResult, string machineName, int maxConcurrentJobs, string nodeName, string registerTime, string status, string version, string versionStatus) { Capabilities = capabilities; ConcurrentJobsLimit = concurrentJobsLimit; ExpiryTime = expiryTime; HostServiceUri = hostServiceUri; IsActiveDispatcher = isActiveDispatcher; LastConnectTime = lastConnectTime; LastEndUpdateTime = lastEndUpdateTime; LastStartTime = lastStartTime; LastStartUpdateTime = lastStartUpdateTime; LastStopTime = lastStopTime; LastUpdateResult = lastUpdateResult; MachineName = machineName; MaxConcurrentJobs = maxConcurrentJobs; NodeName = nodeName; RegisterTime = registerTime; Status = status; Version = version; VersionStatus = versionStatus; } } }
33.121622
98
0.604855
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/DataFactory/V20170901Preview/Outputs/SelfHostedIntegrationRuntimeNodeResponse.cs
4,902
C#
namespace AdventOfCode.Solutions.Year2019.Computer { public enum Opcode { Add = 1, Multiply = 2, ProcessInput = 3, ProcessOutput = 4, JumpIfTrue = 5, JumpIfFalse = 6, LessThan = 7, Equals = 8, UpdateRelativeBase = 9, Stop = 99 } }
19.058824
51
0.512346
[ "MIT" ]
YBijen/advent-of-code-2019
Solutions/Year2019/Computer/Opcode.cs
326
C#
using System.Runtime.CompilerServices; namespace System.Html.Media.Graphics.SVG { [IgnoreNamespace, Imported(ObeysTypeSystem = true)] public partial class SVGPathSegLinetoVerticalAbs : SVGPathSeg { internal SVGPathSegLinetoVerticalAbs() { } [IntrinsicProperty] public double Y { get { return 0; } set { } } } }
18.052632
64
0.71137
[ "Apache-2.0" ]
Saltarelle/SaltarelleWeb
Web/Generated/Html/Media/Graphics/SVG/SVGPathSegLinetoVerticalAbs.cs
345
C#
using System.Windows; namespace EconomyMonitor.Wpf.MVVM.Commands.Window; internal sealed class MinimalizeAppCommand : CommandBase { protected override bool CanExecute(object? parameter) => true; protected override void Execute(object? parameter) { Application.Current.MainWindow.WindowState = WindowState.Minimized; } public MinimalizeAppCommand() { } }
20.789474
75
0.734177
[ "MIT" ]
dtoriki/EconomyMonitor
src/EconomyMonitor.Wpf/MVVM/Commands/Window/MinimalizeAppCommand.cs
395
C#
using Marten.Events; using Shouldly; using Marten.Services; using Npgsql; using Xunit; namespace Marten.Testing.Events { public class asserting_on_expected_event_version_on_append : DocumentSessionFixture<NulloIdentityMap> { [Fact] public void should_check_max_event_id_on_append() { var joined = new MembersJoined { Members = new string[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var stream = theSession.Events.StartStream<Quest>(joined).Id; theSession.Events.Append(stream, 2, departed); theSession.SaveChanges(); var state = theSession.Events.FetchStreamState(stream); state.Id.ShouldBe(stream); state.Version.ShouldBe(2); } [Fact] public void should_not_append_events_when_unexpected_max_version() { var joined = new MembersJoined { Members = new string[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var stream = theSession.Events.StartStream<Quest>(joined).Id; theSession.SaveChanges(); theSession.Events.Append(stream, 2, departed); using (var session = theStore.OpenSession()) { var joined3 = new MembersJoined {Members = new[] {"Egwene"}}; var departed3 = new MembersDeparted {Members = new[] {"Perrin"}}; session.Events.Append(stream, joined3, departed3); session.SaveChanges(); } Assert.Throws<EventStreamUnexpectedMaxEventIdException>(() => theSession.SaveChanges()); using (var session = theStore.OpenSession()) { var state = session.Events.FetchStreamState(stream); state.Id.ShouldBe(stream); state.Version.ShouldBe(3); } } [Fact] public void should_check_max_event_id_on_append_with_string_identifier() { StoreOptions(_ => _.Events.StreamIdentity = StreamIdentity.AsString); var joined = new MembersJoined { Members = new string[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var stream = "First"; theSession.Events.Append(stream, joined); theSession.Events.Append(stream, 2, departed); theSession.SaveChanges(); var state = theSession.Events.FetchStreamState(stream); state.Key.ShouldBe(stream); state.Version.ShouldBe(2); } [Fact] public void should_not_append_events_when_unexpected_max_version_with_string_identifier() { StoreOptions(_ => _.Events.StreamIdentity = StreamIdentity.AsString); var joined = new MembersJoined { Members = new string[] { "Rand", "Matt", "Perrin", "Thom" } }; var departed = new MembersDeparted { Members = new[] { "Thom" } }; var stream = "Another"; theSession.Events.Append(stream, joined); theSession.SaveChanges(); theSession.Events.Append(stream, 2, departed); using (var session = theStore.OpenSession()) { var joined3 = new MembersJoined { Members = new[] { "Egwene" } }; var departed3 = new MembersDeparted { Members = new[] { "Perrin" } }; session.Events.Append(stream, joined3, departed3); session.SaveChanges(); } Assert.Throws<EventStreamUnexpectedMaxEventIdException>(() => theSession.SaveChanges()); using (var session = theStore.OpenSession()) { var state = session.Events.FetchStreamState(stream); state.Key.ShouldBe(stream); state.Version.ShouldBe(3); } } } }
34.871795
119
0.573529
[ "MIT" ]
Maximusya/marten
src/Marten.Testing/Events/asserting_on_expected_event_version_on_append.cs
4,080
C#
// Copyright (c) 2014 Christian Crowhurst. All rights reserved. // see LICENSE using System; using CcAcca.CacheAbstraction.Statistics; namespace CcAcca.CacheAbstraction { /// <summary> /// Defines the main behaviour of a cache /// </summary> /// <remarks> /// <para> /// For additional caching functionality that can be added to a cache, see concreate implementations of <see /// cref="CacheDecorator"/> such as /// <see cref="StatisticsDecorator"/> /// </para> /// <para> /// This interface has been kept lean. For additionaly API see the extension methods /// that target this interface. /// </para> /// </remarks> /// <seealso cref="CacheExtensions"/> public interface ICache { /// <summary> /// Returns a reference to a derived <see cref="ICache"/> interface that this instance may implement, otherwise /// returns null /// </summary> /// <typeparam name="T">The derived <see cref="ICache"/> interface reference requested</typeparam> T As<T>() where T : class, ICache; /// <summary> /// When supported by the cache implementation, returns the number of items currently in the cache /// </summary> /// <remarks> /// <para> /// An implemention that does not want to support this property should return null /// </para> /// <para> /// Where one or more <see cref="ICache"/> instances share a backing store this property should /// return only those items added to this instance /// </para> /// </remarks> int? Count { get; } /// <summary> /// Checks the cache for an existing item associated with the value of the <paramref name="key"/> supplied, if no /// item found adds it otherwise overwrites the entry with the <paramref name="value"/> /// </summary> /// <param name="key">The key to associate with the <paramref name="value"/></param> /// <param name="value">The value to add to the cache</param> /// <param name="cachePolicy"> /// Optional cache policy that controls behaviour such as when the item will be aged out of the cache /// </param> /// <remarks> /// The cache may already be associated with a cache policy. In this case, any <paramref name="cachePolicy"/> /// parameter supplied will override the cache policy defined for the cache /// </remarks> /// <exception cref="ArgumentNullException">When <paramref name="key"/> or <paramref name="value"/> is null</exception> void AddOrUpdate<T>(string key, T value, object cachePolicy = null); /// <summary> /// Adds a key/value pair to the <see cref="ICache"/> if the key does not already exist, /// or to update a key/value pair in the <see cref="ICache"/> by using the specified function if the key already exists. /// </summary> /// <param name="key">The key to be added or whose value is to be updated</param> /// <param name="addValue">The value to be added for an absent key</param> /// <param name="updateValueFactory">The function used to generate a new value for an existing key based on the key's existing value</param> /// <param name="cachePolicy"> /// Optional cache policy that controls behaviour such as when the item will be aged out of the cache /// </param> /// <remarks> /// The cache may already be associated with a cache policy. In this case, any <paramref name="cachePolicy"/> /// parameter supplied will override the cache policy defined for the cache /// </remarks> /// <exception cref="ArgumentNullException"> /// When <paramref name="key"/> or <paramref name="updateValueFactory"/> is null or <paramref name="updateValueFactory"/> /// returns a null</exception> void AddOrUpdate<T>(string key, T addValue, Func<string, T, T> updateValueFactory, object cachePolicy = null); /// <summary> /// Returns true when an item is found matching the <paramref name="key"/> /// </summary> /// <param name="key"></param> /// <returns></returns> bool Contains(string key); /// <summary> /// Clears the cache /// </summary> void Flush(); /// <summary> /// Return the item associated with the <paramref name="key"/> supplied or null if not found /// </summary> CacheItem<T> GetCacheItem<T>(string key); /// <summary> /// Returns an object that this instance will use to lock the cache items during updates /// </summary> object LockKey { get; } /// <summary> /// The unique identify for this instance /// </summary> CacheIdentity Id { get; } /// <summary> /// Remove the cache item associated with the key /// </summary> /// <remarks> /// This is no-op when an item is not found associated with the key /// </remarks> void Remove(string key); } }
43.669492
148
0.604502
[ "MIT" ]
christianacca/Cache-Abstraction
src/CcAcca.CacheAbstraction/ICache.cs
5,153
C#
using System; using System.Threading.Tasks; using ConsistentApiResponseErrors.ConsistentErrors; using ConsistentApiResponseErrors.Exceptions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace ConsistentApiResponseErrors.Middlewares { /// <summary> /// Central error/exception handler Middle-ware /// </summary> public class ExceptionHandlerMiddleware { private const string JsonContentType = "application/problem+json"; private readonly RequestDelegate request; private readonly ILogger logger; /// <summary> /// Initializes a new instance of the <see cref="ExceptionHandlerMiddleware"/> class. /// </summary> /// <param name="next">The next.</param> public ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger) { this.request = next; this.logger = logger; } /// <summary> /// Invokes the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public Task Invoke(HttpContext context) => this.InvokeAsync(context); async Task InvokeAsync(HttpContext context) { try { await request(context); } catch (Exception exception) { string traceID = Guid.NewGuid().ToString(); // Log validation errors with this specific traceID: logger.LogError(exception, exception.Message + $" ({traceID})"); // 2020-01-04: Handle custom "ValidationExceptions" in order to return the related "ValidationError" object errorResult; int httpStatusCode; switch (exception) { case ValidationException validationException when exception is ValidationException: errorResult = validationException.ValidationResult; httpStatusCode = validationException.ValidationResult.StatusCode; break; default: ExceptionError apiException = new ExceptionError(exception, traceID); httpStatusCode = apiException.StatusCode; errorResult = apiException; break; } // Set HTTP status code and content type context.Response.StatusCode = httpStatusCode; context.Response.ContentType = JsonContentType; // Writes / Returns error model to the response (in camelCase format) await context.Response.WriteAsync(JsonConvert.SerializeObject( errorResult, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })); } } } }
36.348837
116
0.582214
[ "MIT" ]
ikyriak/ConsistentApiResponseErrors
src/ConsistentApiResponseErrors/Middlewares/ExceptionHandlerMiddleware.cs
3,128
C#
//----------------------------------------------------------------------- // <copyright file="SharedAccessSignatureHelper.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Core.Auth { using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.Shared.Protocol; #if ALL_SERVICES using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.Table; #endif using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; /// <summary> /// Contains helper methods for implementing shared access signatures. /// </summary> internal static class SharedAccessSignatureHelper { internal static UriQueryBuilder GetSignature( SharedAccessAccountPolicy policy, string signature, string accountKeyName, string sasVersion) { CommonUtility.AssertNotNull("signature", signature); CommonUtility.AssertNotNull("policy", policy); UriQueryBuilder builder = new UriQueryBuilder(); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName); AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedProtocols, policy.Protocols == null ? null : GetProtocolString(policy.Protocols.Value)); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIP, policy.IPAddressOrRange == null ? null : policy.IPAddressOrRange.ToString()); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime)); AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime)); string resourceTypes = SharedAccessAccountPolicy.ResourceTypesToString(policy.ResourceTypes); if (!string.IsNullOrEmpty(resourceTypes)) { AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedResourceTypes, resourceTypes); } string services = SharedAccessAccountPolicy.ServicesToString(policy.Services); if (!string.IsNullOrEmpty(services)) { AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedServices, services); } string permissions = SharedAccessAccountPolicy.PermissionsToString(policy.Permissions); if (!string.IsNullOrEmpty(permissions)) { AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions); } return builder; } /// <summary> /// Converts the specified value to either a string representation or <see cref="String.Empty"/>. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A string representing the specified value.</returns> internal static string GetDateTimeOrEmpty(DateTimeOffset? value) { string result = GetDateTimeOrNull(value) ?? string.Empty; return result; } /// <summary> /// Converts the specified value to either a string representation or <c>null</c>. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>A string representing the specified value.</returns> internal static string GetDateTimeOrNull(DateTimeOffset? value) { string result = value != null ? value.Value.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) : null; return result; } /// <summary> /// Converts the specified value to either a string representation or <c>null</c>. /// </summary> /// <param name="protocols">The protocols to convert</param> /// <returns>A string representing the specified value.</returns> internal static string GetProtocolString(SharedAccessProtocol? protocols) { if (!protocols.HasValue) { return null; } if ((protocols.Value != SharedAccessProtocol.HttpsOnly) && (protocols.Value != SharedAccessProtocol.HttpsOrHttp)) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, SR.InvalidProtocolsInSAS, protocols.Value)); } return protocols.Value == SharedAccessProtocol.HttpsOnly ? "https" : "https,http"; } /// <summary> /// Escapes and adds the specified name/value pair to the query builder if it is not null. /// </summary> /// <param name="builder">The builder to add the value to.</param> /// <param name="name">The name of the pair.</param> /// <param name="value">The value to be escaped.</param> internal static void AddEscapedIfNotNull(UriQueryBuilder builder, string name, string value) { if (value != null) { builder.Add(name, value); } } /// <summary> /// Parses the query. /// </summary> /// <param name="queryParameters">The query parameters.</param> internal static StorageCredentials ParseQuery(IDictionary<string, string> queryParameters) { bool sasParameterFound = false; List<string> removeList = new List<string>(); foreach (KeyValuePair<string, string> parameter in queryParameters) { switch (parameter.Key.ToLower()) { case Constants.QueryConstants.Signature: sasParameterFound = true; break; case Constants.QueryConstants.ResourceType: case Constants.QueryConstants.Component: case Constants.QueryConstants.Snapshot: case Constants.QueryConstants.ApiVersion: case Constants.QueryConstants.ShareSnapshot: removeList.Add(parameter.Key); break; default: break; } } foreach (string removeParam in removeList) { queryParameters.Remove(removeParam); } if (sasParameterFound) { UriQueryBuilder builder = new UriQueryBuilder(); foreach (KeyValuePair<string, string> parameter in queryParameters) { AddEscapedIfNotNull(builder, parameter.Key.ToLower(), parameter.Value); } return new StorageCredentials(builder.ToString()); } return null; } internal static string GetHash( SharedAccessAccountPolicy policy, string accountName, string sasVersion, byte[] keyValue) { string stringToSign = string.Format( CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}", accountName, SharedAccessAccountPolicy.PermissionsToString(policy.Permissions), SharedAccessAccountPolicy.ServicesToString(policy.Services), SharedAccessAccountPolicy.ResourceTypesToString(policy.ResourceTypes), GetDateTimeOrEmpty(policy.SharedAccessStartTime), GetDateTimeOrEmpty(policy.SharedAccessExpiryTime), policy.IPAddressOrRange == null ? string.Empty : policy.IPAddressOrRange.ToString(), GetProtocolString(policy.Protocols), sasVersion, string.Empty); Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign); return CryptoUtility.ComputeHmac256(keyValue, stringToSign); } } }
44.566667
160
0.600812
[ "Apache-2.0" ]
JoeLiang1983/Azure-Storage-Net
Lib/Common/Core/Auth/SharedAccessSignatureHelper.cs
9,359
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeskApiClient.models { class DeskCase { public int id { get; set; } //public int external_id { get; set; } public string subject { get; set; } public DateTime? created_at { get; set; } public DateTime? updated_at { get; set; } public DateTime? changed_at { get; set; } public int priority { get; set; } = 4; public string type { get; set; } public string status { get; set; } public string description { get; set; } public string[] labels { get; set; } public DeskCustomer customer { get; set; } public DeskMessage message { get; set; } public IDictionary<string, string> custom_fields { get; set; } } }
29.586207
70
0.614219
[ "MIT" ]
gmandrsn/Desk.com-case-csharp-api
DeskApiClient/models/DeskCase.cs
860
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace SecurityConventionsApi.Controllers { [ApiController] [Route("[controller]")] [Authorize] public class ItsHierarchicalDerivedController : ItsHierarchicalBaseController { private readonly ILogger<ItsAuthorizedController> _logger; public ItsHierarchicalDerivedController(ILogger<ItsAuthorizedController> logger) : base(logger) { _logger = logger; } } }
27.05
103
0.730129
[ "MIT" ]
greyhamwoohoo/net-controller-security-conventions
src/SecurityConventionsApi/Controllers/ItsHierarchicalDerivedController.cs
543
C#
using System.Collections.Generic; using System.Linq; using AdventOfCode.IntCode; using AdventOfCode.Utilities; namespace AdventOfCode { /// <summary> /// Solver for Day 11 /// </summary> public class Day11 { private const int Black = 0; private const int White = 1; public int Part1(string[] input) { Dictionary<(int x, int y), int> panels = RunPaintingRobot(input, Black); return panels.Keys.Count; } public string Part2(string[] input) { Dictionary<(int x, int y), int> panels = RunPaintingRobot(input, White); // map to a char grid so we can print it int maxX = panels.Keys.Max(k => k.x); int maxY = panels.Keys.Max(k => k.y) + 1; var grid = new char[maxY, maxX]; // initialise to all black grid.ForEach((x, y, _) => grid[y, x] = ' '); // colour in the painted squares foreach (KeyValuePair<(int x, int y), int> pair in panels.Where(p => p.Value == White)) { grid[pair.Key.y, pair.Key.x] = '█'; } return grid.Print(); } private static Dictionary<(int x, int y), int> RunPaintingRobot(IReadOnlyList<string> input, int startingColour) { var position = (0, 0); var direction = Bearing.North; var vm = new IntCodeEmulator(input); var panels = new Dictionary<(int x, int y), int> { [position] = startingColour }; while (!vm.Halted) { vm.StdIn.Enqueue(panels.GetOrCreate(position)); while (!(vm.Halted || vm.WaitingForInput)) { vm.Step(); } // paint int paint = (int)vm.StdOut.Dequeue(); panels[position] = paint; // turn and move var turn = (TurnDirection)(int)vm.StdOut.Dequeue(); direction = direction.Turn(turn); position = position.Move(direction); } return panels; } } }
28.088608
120
0.49662
[ "MIT" ]
adamrodger/advent-2019
src/AdventOfCode/Day11.cs
2,223
C#
using System; namespace Itc4net.Text { public enum TokenKind : byte { LParen, RParen, Comma, IntegerLiteral, EndOfText, Error }; }
13.642857
32
0.518325
[ "MIT" ]
fallin/Itc4net
src/Itc4net/Text/TokenKind.cs
191
C#
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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.Security.Claims; using System.Security.Cryptography.X509Certificates; using Microsoft.IdentityModel.Protocols.WsFederation; using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens.Saml; using Microsoft.IdentityModel.Xml; using static Microsoft.IdentityModel.Xml.XmlSignatureConstants; namespace Microsoft.IdentityModel.TestUtils { public class XmlTestSet { public string Xml { get; set; } public string TestId { get; set; } } #region Saml public class SamlActionTestSet : XmlTestSet { public SamlAction Action { get; set; } } public class SamlAdviceTestSet : XmlTestSet { public SamlAdvice Advice { get; set; } } public class SamlAssertionTestSet : XmlTestSet { public SamlAssertion Assertion { get; set; } } public class SamlAudienceRestrictionConditionTestSet : XmlTestSet { public SamlAudienceRestrictionCondition AudienceRestrictionCondition { get; set; } } public class SamlAttributeTestSet : XmlTestSet { public SamlAttribute Attribute { get; set; } } public class SamlAttributeStatementTestSet : XmlTestSet { public SamlAttributeStatement AttributeStatement { get; set; } } public class SamlAuthenticationStatementTestSet : XmlTestSet { public SamlAuthenticationStatement AuthenticationStatement { get; set; } } public class SamlAuthorizationDecisionStatementTestSet : XmlTestSet { public SamlAuthorizationDecisionStatement AuthorizationDecision { get; set; } } public class SamlConditionsTestSet : XmlTestSet { public SamlConditions Conditions { get; set; } } public class SamlEvidenceTestSet : XmlTestSet { public SamlEvidence Evidence { get; set; } } public class SamlSubjectTestSet : XmlTestSet { public SamlSubject Subject { get; set; } } public class SamlTokenTestSet : XmlTestSet { public SecurityToken SecurityToken { get; set; } public IEnumerable<ClaimsIdentity> Identities { get; set; } } //public class SamlSecurityTokenTestSet : XmlTestSet //{ // public SamlSecurityToken SamlSecurityToken // { // get; // set; // } //} #endregion public class TransformTestSet : XmlTestSet { private static string DSigNS { get => "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\""; } private static string DSigPrefix { get => XmlSignatureConstants.PreferredPrefix + ":"; } public Transform Transform { get; set; } public CanonicalizingTransfrom CanonicalizingTransfrom { get; set; } public static TransformTestSet AlgorithmUnknown { get => new TransformTestSet { TestId = nameof(AlgorithmUnknown), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.Aes128CbcHmacSha256, "") }, DSigNS) }; } public static TransformTestSet AlgorithmNull { get => new TransformTestSet { TestId = nameof(AlgorithmNull), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List <string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", null, "") }, DSigNS) }; } public static TransformTestSet ElementUnknown { get => new TransformTestSet { TestId = nameof(ElementUnknown), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "ElementUnknown", "Algorithm", SecurityAlgorithms.Aes128CbcHmacSha256, "") }, DSigNS) }; } public static TransformTestSet Enveloped_AlgorithmAttributeMissing { get => new TransformTestSet { TestId = nameof(Enveloped_AlgorithmAttributeMissing), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "_Algorithm", SecurityAlgorithms.EnvelopedSignature, "") }, DSigNS) }; } public static TransformTestSet Enveloped { get => new TransformTestSet { TestId = nameof(Enveloped), Transform = new EnvelopedSignatureTransform(), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.EnvelopedSignature, "") }, DSigNS) }; } public static TransformTestSet Enveloped_WithNS { get => new TransformTestSet { TestId = nameof(Enveloped_WithNS), Transform = new EnvelopedSignatureTransform(), Xml = XmlGenerator.TransformsXml(DSigPrefix,new List <string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.EnvelopedSignature, DSigNS) }, DSigNS) }; } public static TransformTestSet Enveloped_WithoutPrefix { get => new TransformTestSet { TestId = nameof(Enveloped_WithoutPrefix), Transform = new EnvelopedSignatureTransform(), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List <string> { XmlGenerator.TransformXml("", "Algorithm", SecurityAlgorithms.EnvelopedSignature, "") }, DSigNS) }; } public static TransformTestSet C14n_WithComments { get => new TransformTestSet { CanonicalizingTransfrom = new ExclusiveCanonicalizationTransform(true), TestId = nameof(C14n_WithComments), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.ExclusiveC14nWithComments, "") }, DSigNS) }; } public static TransformTestSet C14n_WithInclusivePrefix { get => new TransformTestSet { CanonicalizingTransfrom = new ExclusiveCanonicalizationTransform(true) { InclusiveNamespacesPrefixList = "#default saml ds xs xsi" }, TestId = nameof(C14n_WithInclusivePrefix), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformWithInclusivePrefixXml(DSigPrefix, "Algorithm", SecurityAlgorithms.ExclusiveC14nWithComments, "", "<InclusiveNamespaces PrefixList=\"#default saml ds xs xsi\" xmlns=\"http://www.w3.org/2001/10/xml-exc-c14n#\" />" ) }, DSigNS) }; } public static TransformTestSet C14n_WithComments_WithoutPrefix { get => new TransformTestSet { TestId = nameof(C14n_WithComments_WithoutPrefix), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml("", "Algorithm", SecurityAlgorithms.ExclusiveC14nWithComments, "") }, DSigNS) }; } public static TransformTestSet C14n_WithComments_WithNS { get => new TransformTestSet { CanonicalizingTransfrom = new ExclusiveCanonicalizationTransform(true), TestId = nameof(C14n_WithComments_WithNS), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.ExclusiveC14nWithComments, DSigNS) }, DSigNS) }; } public static TransformTestSet C14n_WithoutComments { get => new TransformTestSet { CanonicalizingTransfrom = new ExclusiveCanonicalizationTransform(false), TestId = nameof(C14n_WithoutComments), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.ExclusiveC14n, "") }, DSigNS) }; } public static TransformTestSet C14n_WithNS { get => new TransformTestSet { TestId = nameof(C14n_WithNS), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", SecurityAlgorithms.ExclusiveC14n, "") }, DSigNS) }; } public static TransformTestSet C14n_WithoutNS { get => new TransformTestSet { TestId = nameof(C14n_WithoutNS), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml("", "Algorithm", SecurityAlgorithms.ExclusiveC14n, "") }, DSigNS) }; } public static TransformTestSet TransformNull { get => new TransformTestSet { TestId = nameof(TransformNull), Xml = XmlGenerator.TransformsXml(DSigPrefix, new List<string> { XmlGenerator.TransformXml(DSigPrefix, "Algorithm", null, "") }, DSigNS) }; } public static TransformTestSet MultipleTransforms(int numberOfTransforms, string testVariation, string transform, CanonicalizingTransfrom canonicalizingTransfrom) { var transforms = new List<string>(); for (int i = 0; i < numberOfTransforms; i++) transforms.Add(XmlGenerator.TransformXml(DSigPrefix, "Algorithm", transform, DSigNS)); return new TransformTestSet { CanonicalizingTransfrom = canonicalizingTransfrom, TestId = testVariation, Xml = XmlGenerator.TransformsXml(DSigPrefix, transforms, DSigNS) }; } } public class KeyInfoTestSet : XmlTestSet { public KeyInfo KeyInfo { get; set; } public static KeyInfoTestSet KeyInfoFullyPopulated { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))) { IssuerSerial = new IssuerSerial("CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP", "12345678"), SKI = "31d97bd7", SubjectName = "X509SubjectName" }; var keyInfo = new KeyInfo { RetrievalMethodUri = "http://RetrievalMethod", RSAKeyValue = new RSAKeyValue( "rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==", "AQAB"), KeyName = "KeyName" }; keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithAllElements), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <KeyName>KeyName</KeyName> <RetrievalMethod URI = ""http://RetrievalMethod""/> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> <X509SKI>31d97bd7</X509SKI> <X509SubjectName>X509SubjectName</X509SubjectName> </X509Data> <KeyValue> <RSAKeyValue> <Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus> <Exponent>AQAB</Exponent> </RSAKeyValue> </KeyValue> </KeyInfo>" }; } } public static KeyInfoTestSet MalformedCertificate { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))); var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(MalformedCertificate), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509Certificate>%%MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet MultipleCertificates { get { var data = new X509Data(new List<X509Certificate2> { new X509Certificate2(Convert.FromBase64String(Default.CertificateData)), new X509Certificate2(Convert.FromBase64String(Default.CertificateData)) } ); var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(MultipleCertificates), Xml = XmlGenerator.KeyInfoXml( "http://www.w3.org/2000/09/xmldsig#", new XmlEement("X509Data", new List<XmlEement> { new XmlEement("X509Certificate", Default.CertificateData), new XmlEement("X509Certificate", Default.CertificateData) })) }; } } public static KeyInfoTestSet MultipleIssuerSerial { get { return new KeyInfoTestSet { TestId = nameof(MultipleIssuerSerial), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet MultipleSKI { get { return new KeyInfoTestSet { TestId = nameof(MultipleSKI), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509SKI>31d97bd7</X509SKI> <X509SKI>31d97bd7</X509SKI> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet MultipleSubjectName { get { return new KeyInfoTestSet { TestId = nameof(MultipleSubjectName), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509SubjectName>X509SubjectName</X509SubjectName> <X509SubjectName>X509SubjectName</X509SubjectName> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet SingleCertificate { get { return new KeyInfoTestSet { KeyInfo = Default.KeyInfo, TestId = nameof(SingleCertificate), Xml = XmlGenerator.Generate(Default.KeyInfo), }; } } public static KeyInfoTestSet SingleIssuerSerial { get { var data = new X509Data { IssuerSerial = new IssuerSerial("CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP", "12345678") }; var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(SingleIssuerSerial), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet SingleSKI { get { var data = new X509Data { SKI = "31d97bd7" }; var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(SingleSKI), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509SKI>31d97bd7</X509SKI> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet SingleSubjectName { get { var data = new X509Data { SubjectName = "X509SubjectName" }; var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(SingleSubjectName), Xml = XmlGenerator.Generate(keyInfo), }; } } public static KeyInfoTestSet MultipleX509Data { get { var data1 = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))); var data2 = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQXxLnqm1cOoVGe62j7W7wZzANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDMyNjAwMDAwMFoXDTE5MDMyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKJGarCm4IF0/Gz5Xx/zyZwD2rdJJZtO2Ukk1Oz+Br1sLVY8I5vj5esB+lotmLEblA9N/w188vmTvykaEzUl49NA4s86x44SW6WtdQbGJ0IjpQJUalUMyy91vIBkK/7K3nBXeVBsRk7tm528leoQ05/aZ+1ycJBIU+1oGYThv8MOjyHAlXJmCaGXwXTisZ+hHjcwlMk/+ZEutHflKLIpPUNEi7j4Xw+zp9UKo5pzWIr/iJ4HjvCkFofW90AMF2xp8dMhpbVcfJGS/Ii3J66LuNLCH/HtSZ42FO+tnRL/nNzzFWUhGT92Q5VFVngfWJ3PAg1zz8I1wowLD2fiB2udGXcCAwEAAaMhMB8wHQYDVR0OBBYEFFXPbFXjmMR3BluF+2MeSXd1NQ3rMA0GCSqGSIb3DQEBCwUAA4IBAQAsd3wGVilJxDtbY1K2oAsWLdNJgmCaYdrtdlAsjGlarSQSzBH0Ybf78fcPX//DYaLXlvaEGKVKp0jPq+RnJ17oP/RJpJTwVXPGRIlZopLIgnKpWlS/PS0uKAdNvLmz1zbGSILdcF+Qf41OozD4QNsS1c9YbDO4vpC9v8x3PVjfJvJwPonzNoOsLXA+8IONSXwCApsnmrwepKu8sifsFYSwgrwxRPGTEAjkdzRJ0yMqiY/VoJ7lqJ/FBJqqAjGPGq/yI9rVoG+mbO1amrIDWHHTKgfbKk0bXGtVUbsayyHR5jSgadmkLBh5AaN/HcgDK/jINrnpiQ+/2ewH/8qLaQ3B"))); var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data1); keyInfo.X509Data.Add(data2); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithRSAKeyValue), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> </X509Data> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQXxLnqm1cOoVGe62j7W7wZzANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDMyNjAwMDAwMFoXDTE5MDMyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKJGarCm4IF0/Gz5Xx/zyZwD2rdJJZtO2Ukk1Oz+Br1sLVY8I5vj5esB+lotmLEblA9N/w188vmTvykaEzUl49NA4s86x44SW6WtdQbGJ0IjpQJUalUMyy91vIBkK/7K3nBXeVBsRk7tm528leoQ05/aZ+1ycJBIU+1oGYThv8MOjyHAlXJmCaGXwXTisZ+hHjcwlMk/+ZEutHflKLIpPUNEi7j4Xw+zp9UKo5pzWIr/iJ4HjvCkFofW90AMF2xp8dMhpbVcfJGS/Ii3J66LuNLCH/HtSZ42FO+tnRL/nNzzFWUhGT92Q5VFVngfWJ3PAg1zz8I1wowLD2fiB2udGXcCAwEAAaMhMB8wHQYDVR0OBBYEFFXPbFXjmMR3BluF+2MeSXd1NQ3rMA0GCSqGSIb3DQEBCwUAA4IBAQAsd3wGVilJxDtbY1K2oAsWLdNJgmCaYdrtdlAsjGlarSQSzBH0Ybf78fcPX//DYaLXlvaEGKVKp0jPq+RnJ17oP/RJpJTwVXPGRIlZopLIgnKpWlS/PS0uKAdNvLmz1zbGSILdcF+Qf41OozD4QNsS1c9YbDO4vpC9v8x3PVjfJvJwPonzNoOsLXA+8IONSXwCApsnmrwepKu8sifsFYSwgrwxRPGTEAjkdzRJ0yMqiY/VoJ7lqJ/FBJqqAjGPGq/yI9rVoG+mbO1amrIDWHHTKgfbKk0bXGtVUbsayyHR5jSgadmkLBh5AaN/HcgDK/jINrnpiQ+/2ewH/8qLaQ3B</X509Certificate> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet WithRSAKeyValue { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))); var keyInfo = new KeyInfo() { RSAKeyValue = new RSAKeyValue( "rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==", "AQAB") }; keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithRSAKeyValue), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> </X509Data> <KeyValue> <RSAKeyValue> <Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus> <Exponent>AQAB</Exponent> </RSAKeyValue> </KeyValue> </KeyInfo>" }; } } public static KeyInfoTestSet WithWhitespace { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))); var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithWhitespace), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet WithUnknownX509DataElements { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))); var keyInfo = new KeyInfo(); keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithUnknownX509DataElements), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <X509Data> <Unknown>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</Unknown> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet WithAllElements { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))) { IssuerSerial = new IssuerSerial("CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP", "12345678"), SKI = "31d97bd7", SubjectName = "X509SubjectName" }; var keyInfo = new KeyInfo { RetrievalMethodUri = "http://RetrievalMethod", }; keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithAllElements), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <RetrievalMethod URI = ""http://RetrievalMethod"" >some info </RetrievalMethod> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> <X509SKI>31d97bd7</X509SKI> <X509SubjectName>X509SubjectName</X509SubjectName> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet WithUnknownElements { get { var data = new X509Data(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD"))) { IssuerSerial = new IssuerSerial("CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP", "12345678"), SKI = "31d97bd7", SubjectName = "X509SubjectName" }; var keyInfo = new KeyInfo { RetrievalMethodUri = "http://RetrievalMethod", }; keyInfo.X509Data.Add(data); return new KeyInfoTestSet { KeyInfo = keyInfo, TestId = nameof(WithUnknownElements), Xml = @"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <UnknownElement>some data</UnknownElement> <RetrievalMethod URI = ""http://RetrievalMethod"" >some info </RetrievalMethod> <X509Data> <X509Certificate>MIIDBTCCAe2gAwIBAgIQY4RNIR0dX6dBZggnkhCRoDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE3MDIxMzAwMDAwMFoXDTE5MDIxNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBEizU1OJms31S/ry7iav/IICYVtQ2MRPhHhYknHImtU03sgVk1Xxub4GD7R15i9UWIGbzYSGKaUtGU9lP55wrfLpDjQjEgaXi4fE6mcZBwa9qc22is23B6R67KMcVyxyDWei+IP3sKmCcMX7Ibsg+ubZUpvKGxXZ27YgqFTPqCT2znD7K81YKfy+SVg3uW6epW114yZzClTQlarptYuE2mujxjZtx7ZUlwc9AhVi8CeiLwGO1wzTmpd/uctpner6oc335rvdJikNmc1cFKCK+2irew1bgUJHuN+LJA0y5iVXKvojiKZ2Ii7QKXn19Ssg1FoJ3x2NWA06wc0CnruLsCAwEAAaMhMB8wHQYDVR0OBBYEFDAr/HCMaGqmcDJa5oualVdWAEBEMA0GCSqGSIb3DQEBCwUAA4IBAQAiUke5mA86R/X4visjceUlv5jVzCn/SIq6Gm9/wCqtSxYvifRXxwNpQTOyvHhrY/IJLRUp2g9/fDELYd65t9Dp+N8SznhfB6/Cl7P7FRo99rIlj/q7JXa8UB/vLJPDlr+NREvAkMwUs1sDhL3kSuNBoxrbLC5Jo4es+juQLXd9HcRraE4U3UZVhUS2xqjFOfaGsCbJEqqkjihssruofaxdKT1CPzPMANfREFJznNzkpJt4H0aMDgVzq69NxZ7t1JiIuc43xRjeiixQMRGMi1mAB75fTyfFJ/rWQ5J/9kh0HMZVtHsqICBF1tHMTMIK5rwoweY0cuCIpN7A/zMOQtoD</X509Certificate> <X509IssuerSerial> <X509IssuerName>CN=TAMURA Kent, OU=TRL, O=IBM, L=Yamato-shi, ST=Kanagawa, C=JP</X509IssuerName> <X509SerialNumber>12345678</X509SerialNumber> </X509IssuerSerial> <X509SKI>31d97bd7</X509SKI> <X509SubjectName>X509SubjectName</X509SubjectName> </X509Data> </KeyInfo>" }; } } public static KeyInfoTestSet WrongElement { get { return new KeyInfoTestSet { KeyInfo = Default.KeyInfo, TestId = nameof(WithUnknownElements), Xml = XmlGenerator.Generate(Default.KeyInfo).Replace("<KeyInfo", "<NotKeyInfo>").Replace("/KeyInfo>", "/NotKeyInfo>") }; } } public static KeyInfoTestSet WrongNamespace { get { return new KeyInfoTestSet { KeyInfo = Default.KeyInfo, TestId = nameof(WrongNamespace), Xml = XmlGenerator.Generate(Default.KeyInfo).Replace(XmlSignatureConstants.Namespace, $"_{XmlSignatureConstants.Namespace}_") }; } } public static KeyInfoTestSet KeyInfoEmpty { get { return new KeyInfoTestSet { KeyInfo = new KeyInfo(), TestId = nameof(KeyInfoEmpty), Xml = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"/>" }; } } public static KeyInfoTestSet X509DataEmpty { get { return new KeyInfoTestSet { KeyInfo = new KeyInfo(), TestId = nameof(X509DataEmpty), Xml = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data/></KeyInfo>" }; } } public static KeyInfoTestSet IssuerSerialEmpty { get { return new KeyInfoTestSet { KeyInfo = new KeyInfo(), TestId = nameof(IssuerSerialEmpty), Xml = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data><X509IssuerSerial/></X509Data></KeyInfo>" }; } } public static KeyInfoTestSet RSAKeyValueEmpty { get { return new KeyInfoTestSet { KeyInfo = new KeyInfo(), TestId = nameof(RSAKeyValueEmpty), Xml = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue><RSAKeyValue/></KeyValue></KeyInfo>" }; } } } public class SignatureTestSet : XmlTestSet { public SecurityKey SecurityKey { get; set; } = KeyingMaterial.DefaultAADSigningKey; public Signature Signature { get; set; } public static SignatureTestSet UnknownSignatureAlgorithm { get { var signature = Default.SignatureNS; signature.SignedInfo.SignatureMethod = $"_{SecurityAlgorithms.RsaSha256Signature}"; return new SignatureTestSet { Signature = signature, TestId = nameof(UnknownSignatureAlgorithm), Xml = XmlGenerator.Generate(Default.SignatureNS).Replace(SecurityAlgorithms.RsaSha256Signature, $"_{SecurityAlgorithms.RsaSha256Signature}" ) }; } } public static SignatureTestSet SignatureFullyPopulated { get { var signatureBytes = XmlUtilities.GenerateSignatureBytes(SignedInfoTestSet.SignedInfoFullyPopulated.SignedInfo, Default.AsymmetricSigningKey); var signatureValue = Convert.ToBase64String(signatureBytes); var signature = new Signature() { SignedInfo = SignedInfoTestSet.SignedInfoFullyPopulated.SignedInfo, SignatureValue = signatureValue, KeyInfo = KeyInfoTestSet.KeyInfoFullyPopulated.KeyInfo, Id = "SignatureFullyPopulated" }; return new SignatureTestSet { Signature = signature, TestId = nameof(SignatureFullyPopulated), Xml = XmlGenerator.Generate(signature) }; } } } public class SignedInfoTestSet : XmlTestSet { public SignedInfo SignedInfo { get; set; } public static SignedInfoTestSet SignedInfoEmpty { get { return new SignedInfoTestSet { SignedInfo = new SignedInfo(), TestId = nameof(SignedInfoEmpty), Xml = "<SignedInfo xmlns = \"http://www.w3.org/2000/09/xmldsig#\"/>" }; } } public static SignedInfoTestSet StartsWithWhiteSpace { get { var signedInfo = Default.SignedInfo; signedInfo.References[0] = Default.ReferenceWithNullTokenStream; return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(StartsWithWhiteSpace), Xml = " " + XmlGenerator.Generate(signedInfo) }; } } public static SignedInfoTestSet CanonicalizationMethodMissing { get { return new SignedInfoTestSet { TestId = nameof(CanonicalizationMethodMissing), Xml = XmlGenerator.Generate(Default.SignedInfoNS).Replace("CanonicalizationMethod", "_CanonicalizationMethod") }; } } public static SignedInfoTestSet ReferenceDigestValueNotBase64 { get { var digestValue = Guid.NewGuid().ToString(); var reference = Default.ReferenceWithNullTokenStreamNS; reference.DigestValue = digestValue; var signedInfo = Default.SignedInfoNS; signedInfo.References.Clear(); signedInfo.References.Add(reference); signedInfo.Prefix = ""; return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(ReferenceDigestValueNotBase64), Xml = XmlGenerator.SignedInfoXml( XmlSignatureConstants.Namespace, SecurityAlgorithms.ExclusiveC14n, SecurityAlgorithms.RsaSha256Signature, XmlGenerator.ReferenceXml( Default.ReferencePrefix + ":", Default.ReferenceId, Default.ReferenceType, Default.ReferenceUriWithPrefix, SecurityAlgorithms.EnvelopedSignature, SecurityAlgorithms.ExclusiveC14n, Default.ReferenceDigestMethod, digestValue)) }; } } public static SignedInfoTestSet ReferenceMissing { get { return new SignedInfoTestSet { TestId = nameof(ReferenceMissing), Xml = XmlGenerator.Generate(Default.SignedInfoNS).Replace("Reference", "_Reference") }; } } public static SignedInfoTestSet NoTransforms { get { var signedInfo = Default.SignedInfo; signedInfo.References.Clear(); signedInfo.References.Add(new Reference { DigestMethod = SecurityAlgorithms.Sha256Digest, DigestValue = Default.ReferenceDigestValue }); return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(NoTransforms), Xml = XmlGenerator.Generate(signedInfo) }; } } public static SignedInfoTestSet TwoReferences { get { var signedInfo = Default.SignedInfoNS; signedInfo.References.Add(new Reference { DigestMethod = SecurityAlgorithms.Sha256Digest, DigestValue = Default.ReferenceDigestValue }); return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(SignedInfoTestSet), Xml = XmlGenerator.Generate(signedInfo) }; } } public static SignedInfoTestSet TransformsMissing { get { var signedInfo = Default.SignedInfo; signedInfo.References.Clear(); signedInfo.References.Add(new Reference { DigestMethod = SecurityAlgorithms.Sha256Digest, DigestValue = Default.ReferenceDigestValue, }); return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(TransformsMissing), Xml = XmlGenerator.Generate(signedInfo) }; } } public static SignedInfoTestSet UnknownReferenceTransform { get { var signedInfo = Default.SignedInfoNS; var reference = Default.ReferenceWithNullTokenStreamNS; var unknownTransform = "_http://www.w3.org/2000/09/xmldsig#enveloped-signature"; reference.Transforms.Clear(); reference.Transforms.Add(new EnvelopedSignatureTransform()); reference.CanonicalizingTransfrom = new ExclusiveCanonicalizationTransform(); signedInfo.References.Clear(); signedInfo.References.Add(reference); return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(UnknownReferenceTransform), Xml = XmlGenerator.SignedInfoXml( XmlSignatureConstants.Namespace, SecurityAlgorithms.ExclusiveC14n, SecurityAlgorithms.RsaSha256Signature, XmlGenerator.ReferenceXml( "ds:", Default.ReferenceId, Default.ReferenceType, Default.ReferenceUriWithPrefix, unknownTransform, SecurityAlgorithms.ExclusiveC14n, SecurityAlgorithms.Sha256Digest, Default.ReferenceDigestValue)) }; } } public static SignedInfoTestSet MissingDigestMethod { get { return new SignedInfoTestSet { TestId = nameof(MissingDigestMethod), Xml = XmlGenerator.Generate(Default.SignedInfoNS).Replace("DigestMethod", "_DigestMethod") }; } } public static SignedInfoTestSet MissingDigestValue { get { return new SignedInfoTestSet { TestId = nameof(MissingDigestValue), Xml = XmlGenerator.Generate(Default.SignedInfoNS).Replace("DigestValue", "_DigestValue") }; } } public static SignedInfoTestSet Valid { get { var signedInfo = Default.SignedInfo; signedInfo.References[0] = Default.ReferenceWithNullTokenStream; return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(Valid), Xml = XmlGenerator.Generate(signedInfo) }; } } public static SignedInfoTestSet SignedInfoFullyPopulated { get { var signedInfo = new SignedInfo(Default.ReferenceWithNullTokenStream) { CanonicalizationMethod = SecurityAlgorithms.ExclusiveC14n, Id = "SignedInfoFullyPopulated", SignatureMethod = SecurityAlgorithms.RsaSha256Signature }; return new SignedInfoTestSet { SignedInfo = signedInfo, TestId = nameof(SignedInfoFullyPopulated), Xml = XmlGenerator.Generate(signedInfo) }; } } } public class ReferenceTestSet : XmlTestSet { public Reference Reference { get; set; } public static ReferenceTestSet ReferenceEmpty { get { return new ReferenceTestSet { Reference = new Reference(), TestId = nameof(ReferenceEmpty), Xml = "<ds:Reference Id=\"#abcdef\" Type=\"http://referenceType\" URI=\"http://referenceUri\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>" }; } } public static ReferenceTestSet ReferenceWithId { get { return new ReferenceTestSet { Reference = new Reference() { Id = "#test", DigestMethod = Default.ReferenceDigestMethod, DigestValue = Default.ReferenceDigestValue }, TestId = nameof(ReferenceWithId), Xml = @"<Reference Id=""#test"" xmlns=""http://www.w3.org/2000/09/xmldsig#""><Transforms/><DigestMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#sha256""/><DigestValue>rMea6HlsYH8lHYR11ouxgmyzb39HY1YE07J/1Dyqimw=</DigestValue></Reference>" }; } } public static ReferenceTestSet ReferenceWithIdAndUri { get { return new ReferenceTestSet { Reference = new Reference() { Id = Default.ReferenceId, Uri = Default.ReferenceUriWithPrefix, DigestMethod = Default.ReferenceDigestMethod, DigestValue = Default.ReferenceDigestValue }, TestId = nameof(ReferenceWithIdAndUri), Xml = string.Format(@"<Reference Id=""{0}"" URI=""{1}"" xmlns=""http://www.w3.org/2000/09/xmldsig#""><Transforms/><DigestMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#sha256""/><DigestValue>rMea6HlsYH8lHYR11ouxgmyzb39HY1YE07J/1Dyqimw=</DigestValue></Reference>", Default.ReferenceId, Default.ReferenceUriWithPrefix) }; } } // The reason for this version, is so that we test outbound URI without a # will be written with the # public static ReferenceTestSet ReferenceWithIdAndUriWithoutPrefix { get { return new ReferenceTestSet { Reference = new Reference() { Id = Default.ReferenceId, Uri = Default.ReferenceUriWithOutPrefix, DigestMethod = Default.ReferenceDigestMethod, DigestValue = Default.ReferenceDigestValue }, TestId = nameof(ReferenceWithIdAndUri), Xml = string.Format(@"<Reference Id=""{0}"" URI=""{1}"" xmlns=""http://www.w3.org/2000/09/xmldsig#""><Transforms/><DigestMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#sha256""/><DigestValue>rMea6HlsYH8lHYR11ouxgmyzb39HY1YE07J/1Dyqimw=</DigestValue></Reference>", Default.ReferenceId, Default.ReferenceUriWithPrefix) }; } } } public class TransformsTestSet : XmlTestSet { public Reference Reference { get; set; } public List<Transform> Transforms { get; set; } public static TransformsTestSet TransformsEmpty { get { return new TransformsTestSet { Reference = new Reference(), Transforms = new List<Transform>(), TestId = nameof(TransformsEmpty), Xml = "<Transforms/>" }; } } } public class WsFederationMessageTestSet : XmlTestSet { public WsFederationMessage WsFederationMessage { get; set; } } }
56.106599
1,129
0.648768
[ "MIT" ]
AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet
test/Microsoft.IdentityModel.TestUtils/TestSets.cs
66,318
C#
using ExpressEntryCalculator.Api.Services; using System; namespace ExpressEntryCalculator.AcceptanceTests { public class TestSystemTime : ISystemTime { private readonly DateTime _utcNow; public TestSystemTime(DateTime utcNow) { _utcNow = utcNow; } public DateTime UtcNow => _utcNow; } }
19.722222
48
0.661972
[ "MIT" ]
annaked/ExpressEntryCalculator
ExpressEntryCalculator.AcceptanceTests/TestSystemTime.cs
357
C#
using Grapevine.Interfaces.Shared; namespace Grapevine.Shared.Loggers { public static class LoggerExtensions { public static void BeginRouting (this IGrapevineLogger logger, string message) { logger.Info($"Routing Request : {message}"); } public static void EndRouting(this IGrapevineLogger logger, string message) { logger.Trace($"Routing Complete : {message}"); } public static void RouteInvoked(this IGrapevineLogger logger, string message) { logger.Trace($"Route Invoked : {message}"); } } }
28.318182
86
0.621188
[ "Apache-2.0" ]
07artem132/Grapevine
src/Grapevine_shared/Shared/Loggers/LoggerExtensions.cs
625
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. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Text { #if MONO [Serializable] #endif public class UTF7Encoding : Encoding { private const String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. private const String directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. private const String optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // Used by Encoding.UTF7 for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly UTF7Encoding s_default = new UTF7Encoding(); // The set of base 64 characters. private byte[] _base64Bytes; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. private sbyte[] _base64Values; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. private bool[] _directEncode; private bool _allowOptionals; private const int UTF7_CODEPAGE = 65000; public UTF7Encoding() : this(false) { } public UTF7Encoding(bool allowOptionals) : base(UTF7_CODEPAGE) //Set the data item. { // Allowing optionals? _allowOptionals = allowOptionals; // Make our tables MakeTables(); } private void MakeTables() { // Build our tables _base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) _base64Bytes[i] = (byte)base64Chars[i]; _base64Values = new sbyte[128]; for (int i = 0; i < 128; i++) _base64Values[i] = -1; for (int i = 0; i < 64; i++) _base64Values[_base64Bytes[i]] = (sbyte)i; _directEncode = new bool[128]; int count = directChars.Length; for (int i = 0; i < count; i++) { _directEncode[directChars[i]] = true; } if (_allowOptionals) { count = optionalChars.Length; for (int i = 0; i < count; i++) { _directEncode[optionalChars[i]] = true; } } } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. internal override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevant because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) this.encoderFallback = new EncoderReplacementFallback(String.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } public override bool Equals(Object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) { return (_allowOptionals == that._allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } // Compared to all the other encodings, variations of UTF7 are unlikely public override int GetHashCode() { return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string s) { // Validate input if (s==null) throw new ArgumentNullException("s"); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (count == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; // Default bits & count int bits = 0; int bitCount = -1; // prepare our helpers Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { bits = encoder.bits; bitCount = encoder.bitCount; // May have had too many left over while (bitCount >= 6) { bitCount -= 6; // If we fail we'll never really have enough room if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) ThrowBytesOverflow(encoder, buffer.Count == 0); } } while (buffer.MoreData) { char currentChar = buffer.GetNextChar(); if (currentChar < 0x80 && _directEncode[currentChar]) { if (bitCount >= 0) { if (bitCount > 0) { // Try to add the next byte if (!buffer.AddByte(_base64Bytes[bits << 6 - bitCount & 0x3F])) break; // Stop here, didn't throw bitCount = 0; } // Need to get emit '-' and our char, 2 bytes total if (!buffer.AddByte((byte)'-')) break; // Stop here, didn't throw bitCount = -1; } // Need to emit our char if (!buffer.AddByte((byte)currentChar)) break; // Stop here, didn't throw } else if (bitCount < 0 && currentChar == '+') { if (!buffer.AddByte((byte)'+', (byte)'-')) break; // Stop here, didn't throw } else { if (bitCount < 0) { // Need to emit a + and 12 bits (3 bytes) // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time if (!buffer.AddByte((byte)'+')) break; // Stop here, didn't throw // We're now in bit mode, but haven't stored data yet bitCount = 0; } // Add our bits bits = bits << 16 | currentChar; bitCount += 16; while (bitCount >= 6) { bitCount -= 6; if (!buffer.AddByte(_base64Bytes[(bits >> bitCount) & 0x3F])) { bitCount += 6; // We didn't use these bits currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte // --'d it when we ran out of space break; // Stop here, not enough room for bytes } } if (bitCount >= 6) break; // Didn't have room to encode enough bits } } // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) { if (buffer.AddByte(_base64Bytes[(bits << (6 - bitCount)) & 0x3F])) { // Emitted spare bits, 0 bits left bitCount = 0; } } // If converting and failed bitCount above, then we'll fail this too if (buffer.AddByte((byte)'-')) { // turned off bit mode'; bits = 0; bitCount = -1; } else // If not successful, convert will maintain state for next time, also // AddByte will have decremented our char count, however we need it to remain the same buffer.GetNextChar(); } // Do we have an encoder we're allowed to use? // bytes == null if counting, so don't use encoder then if (bytes != null && encoder != null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; encoder.bitCount = bitCount; encoder._charsUsed = buffer.CharsUsed; } return buffer.Count; } internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder)baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( this, decoder, chars, charCount, bytes, byteCount); // Get decoder info int bits = 0; int bitCount = -1; bool firstByte = false; if (decoder != null) { bits = decoder.bits; bitCount = decoder.bitCount; firstByte = decoder.firstByte; Debug.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } // We may have had bits in the decoder that we couldn't output last time, so do so now if (bitCount >= 16) { // Check our decoder buffer if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF))) ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert // Used this one, clean up extra bits bitCount -= 16; } // Loop through the input while (buffer.MoreData) { byte currentByte = buffer.GetNextByte(); int c; if (bitCount >= 0) { // // Modified base 64 encoding. // sbyte v; if (currentByte < 0x80 && ((v = _base64Values[currentByte]) >= 0)) { firstByte = false; bits = (bits << 6) | ((byte)v); bitCount += 6; if (bitCount >= 16) { c = (bits >> (bitCount - 16)) & 0xFFFF; bitCount -= 16; } // If not enough bits just continue else continue; } else { // If it wasn't a base 64 byte, everything's going to turn off base 64 mode bitCount = -1; if (currentByte != '-') { // >= 0x80 (because of 1st if statemtn) // We need this check since the _base64Values[b] check below need b <= 0x7f. // This is not a valid base 64 byte. Terminate the shifted-sequence and // emit this byte. // not in base 64 table // According to the RFC 1642 and the example code of UTF-7 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte // Chars won't be updated unless this works, try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Used that byte, we're done with it continue; } // // The encoding for '+' is "+-". // if (firstByte) c = '+'; // We just turn it off if not emitting a +, so we're done. else continue; } // // End of modified base 64 encoding block. // } else if (currentByte == '+') { // // Found the start of a modified base 64 encoding block or a plus sign. // bitCount = 0; firstByte = true; continue; } else { // Normal character if (currentByte >= 0x80) { // Try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Done falling back continue; } // Use the normal character c = currentByte; } if (c >= 0) { // Check our buffer if (!buffer.AddChar((char)c)) { // No room. If it was a plain char we'll try again later. // Note, we'll consume this byte and stick it in decoder, even if we can't output it if (bitCount >= 0) // Can we rememmber this byte (char) { buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed bitCount += 16; // We'll still need that char we have in our bits } break; // didn't throw, stop } } } // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) if (chars != null && decoder != null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) { // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = bits; decoder.bitCount = bitCount; decoder.firstByte = firstByte; } decoder._bytesUsed = buffer.BytesUsed; } // else ignore any hanging bits. // Return our count return buffer.Count; } public override System.Text.Decoder GetDecoder() { return new UTF7Encoding.Decoder(this); } public override System.Text.Encoder GetEncoder() { return new UTF7Encoding.Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark. // Therefore, the max byte should be: // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6); // That is always <= 2 + 3 * charCount; // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char. // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off // encoding if MustFlush is true. // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char. // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3 // bytes allows us to turn off and then back on base64 mode if necessary. // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all // code points are encodable int UTF7. long byteCount = (long)charCount * 3 + 2; // check for overflow if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. int charCount = byteCount; if (charCount == 0) charCount = 1; return charCount; } // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change #if MONO [Serializable] #endif private sealed class Decoder : DecoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; /*private*/ internal bool firstByte; public Decoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bits = 0; this.bitCount = -1; this.firstByte = false; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { // NOTE: This forces the last -, which some encoder might not encode. If we // don't see it we don't think we're done reading. return (this.bitCount != -1); } } } // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change #if MONO [Serializable] #endif private sealed class Encoder : EncoderNLS { /*private*/ internal int bits; /*private*/ internal int bitCount; public Encoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.bitCount = -1; this.bits = 0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { return (this.bits != 0 || this.bitCount != -1); } } } // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. #if MONO [Serializable] #endif private sealed class DecoderUTF7Fallback : DecoderFallback { // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderUTF7Fallback() { } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderUTF7FallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { // returns 1 char per bad byte return 1; } } public override bool Equals(Object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) { return true; } return (false); } public override int GetHashCode() { return 984; } } private sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { // Store our default string private char cFallback = (char)0; private int iCount = -1; private int iSize; // Construction public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback) { } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; // Any of the fallback characters can be handled except for 0 if (cFallback == 0) { return false; } iCount = iSize = 1; return true; } public override char GetNextChar() { if (iCount-- > 0) return cFallback; // Note: this means that 0 in UTF7 stream will never be emitted. return (char)0; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } // return true if we were allowed to do this return (iCount >= 0 && iCount <= iSize); } // Return # of chars left in this fallback public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } // Can't fallback a byte 0, so return for that case, 1 otherwise. return bytes[0] == 0 ? 0 : 1; } } } }
41.339051
148
0.522909
[ "MIT" ]
BrzVlad/corefx
src/Common/src/CoreLib/System/Text/UTF7Encoding.cs
40,967
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Management.Compute.Models { public partial class StorageProfile : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(ImageReference)) { writer.WritePropertyName("imageReference"); writer.WriteObjectValue(ImageReference); } if (Optional.IsDefined(OsDisk)) { writer.WritePropertyName("osDisk"); writer.WriteObjectValue(OsDisk); } if (Optional.IsCollectionDefined(DataDisks)) { writer.WritePropertyName("dataDisks"); writer.WriteStartArray(); foreach (var item in DataDisks) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); } internal static StorageProfile DeserializeStorageProfile(JsonElement element) { Optional<ImageReference> imageReference = default; Optional<OSDisk> osDisk = default; Optional<IList<DataDisk>> dataDisks = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("imageReference")) { imageReference = ImageReference.DeserializeImageReference(property.Value); continue; } if (property.NameEquals("osDisk")) { osDisk = OSDisk.DeserializeOSDisk(property.Value); continue; } if (property.NameEquals("dataDisks")) { List<DataDisk> array = new List<DataDisk>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(DataDisk.DeserializeDataDisk(item)); } dataDisks = array; continue; } } return new StorageProfile(imageReference.Value, osDisk.Value, Optional.ToList(dataDisks)); } } }
34
102
0.532194
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/testcommon/Azure.Management.Compute.2019_12/src/Generated/Models/StorageProfile.Serialization.cs
2,516
C#
using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using static Bud.Option; namespace Bud.Reactive { /// <summary> /// Calming extension methods for <see cref="IObservable{T}"/>. /// </summary> public static class ObservableCalming { /// <summary> /// Transforms the given <paramref name="observable" /> into a new observable. The new observable /// waits until some time (given by the <paramref name="calmingPeriod" /> parameter) has passed from the /// last-produced element in the original obervable. This last element will then end up in the /// new observable. After this, the new observable waits for a new element from the original observable /// and repeats the procedure. /// </summary> /// <typeparam name="T"> /// the type of elements in the returned and given <paramref name="observable" />. /// </typeparam> /// <param name="observable">the observable from which to construct a calmed observable.</param> /// <param name="calmingPeriod"> /// the amount of time to wait from the last-produced element in /// the given <paramref name="observable" />. /// </param> /// <param name="scheduler"> /// The scheduler that will be used to determine calming windows. This parameter /// is optional, by default <see cref="DefaultScheduler.Instance" /> is used. /// </param> /// <returns> /// a new observable that produces only those elements from the given <paramref name="observable" /> /// after which there were no elements for the amount of time given by the <paramref name="calmingPeriod" /> /// parameter. /// </returns> public static IObservable<T> Calmed<T>(this IObservable<T> observable, TimeSpan calmingPeriod, IScheduler scheduler = null) { var shared = observable.Publish().RefCount(); scheduler = scheduler ?? DefaultScheduler.Instance; return shared.Window(CalmingWindows(shared, calmingPeriod, scheduler)) .SelectMany(o => o.Aggregate(None<T>(), (element, nextElement) => Some(nextElement))) .Gather(); } /// <summary> /// This method is similar to <see cref="Calmed{T}" /> with one difference: /// the observable returned by this method immeditately returns the first element that comes from the /// given <paramref name="observable" />. Only after that it starts behaving the same as <see cref="Calmed{T}" />. /// </summary> /// <typeparam name="T"> /// the type of elements in the returned and given <paramref name="observable" />. /// </typeparam> /// <param name="observable">the observable from which to construct a calmed observable.</param> /// <param name="calmingPeriod"> /// the amount of time to wait from the last-produced element in /// the given <paramref name="observable" />. /// </param> /// <param name="scheduler"> /// The scheduler that will be used to determine calming windows. This parameter /// is optional, by default <see cref="DefaultScheduler.Instance" /> is used. /// </param> /// <returns> /// a new observable that produces the first element from the given <paramref name="observable" /> and afterwards /// those elements from the given <paramref name="observable" /> after which there were no elements for the amount /// of time given by the <paramref name="calmingPeriod" /> parameter. /// </returns> public static IObservable<T> FirstThenCalmed<T>(this IObservable<T> observable, TimeSpan calmingPeriod, IScheduler scheduler = null) { var sharedInput = observable.Publish().RefCount(); return sharedInput.Take(1) .Concat(sharedInput.Skip(1).Calmed(calmingPeriod, scheduler)); } /// <summary> /// Transforms the given <paramref name="observable" /> into a new observable. The new observable /// collects all elements produced by the given observable until it hits an element, after which /// some time (given by the <paramref name="calmingPeriod" /> parameter) has passed without any /// newly produced elements. At this point, the new observable will produce an element that is a /// collection of all the elements collected so far from the original observable. /// After this, the new observable waits for a new element from the original observable /// and repeats the procedure. /// </summary> /// <typeparam name="T"> /// the type of elements in the returned and given <paramref name="observable" />. /// </typeparam> /// <param name="observable">the observable from which to construct a calmed observable.</param> /// <param name="calmingPeriod"> /// the amount of time to wait from the last-produced element in /// the given <paramref name="observable" />. /// </param> /// <param name="scheduler"> /// The scheduler that will be used to determine calming windows. This parameter /// is optional, by default <see cref="DefaultScheduler.Instance" /> is used. /// </param> /// <returns> /// a new observable that produces a collection of elements collected from the given <paramref name="observable" /> /// during the time that it wated for the first such element after which there were no elements for the /// duration given by the <paramref name="calmingPeriod" /> parameter. /// </returns> public static IObservable<ImmutableArray<T>> CalmedBatches<T>(this IObservable<T> observable, TimeSpan calmingPeriod, IScheduler scheduler = null) { var shared = observable.Publish().RefCount(); scheduler = scheduler ?? DefaultScheduler.Instance; return shared.Window(CalmingWindows(shared, calmingPeriod, scheduler)) .SelectMany(o => o.Aggregate(ImmutableArray.CreateBuilder<T>(), (collectedSoFar, nextElement) => { collectedSoFar.Add(nextElement); return collectedSoFar; })) .Where(list => list.Count > 0) .Select(builder => builder.ToImmutable()); } [SuppressMessage("ReSharper", "ArgumentsStyleAnonymousFunction")] private static IObservable<Unit> CalmingWindows<T>(IObservable<T> observable, TimeSpan calmingPeriod, IScheduler scheduler) => Observable.Create<Unit>(observer => { var calmingTimer = new MultipleAssignmentDisposable(); var calmingWindows = new Subject<Unit>(); var calmerSubscription = observable.Subscribe( onNext: next => { calmingTimer.Disposable?.Dispose(); calmingTimer.Disposable = scheduler.Schedule( calmingPeriod, () => calmingWindows.OnNext(Unit.Default)); }, onError: exception => { calmingTimer.Dispose(); calmingWindows.OnError(exception); }, onCompleted: () => { calmingTimer.Dispose(); calmingWindows.OnCompleted(); }); return new CompositeDisposable { calmingTimer, calmerSubscription, calmingWindows.Subscribe(observer), calmingWindows }; }); } }
52.887417
121
0.608189
[ "MIT" ]
urbas/Bud.Reactive
Bud.Reactive/ObservableCalming.cs
7,988
C#
using System; namespace RTPSWebCore { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.25
69
0.60274
[ "MIT" ]
Apprentice-doa/result_and_transcript_system
web_src/RTPS_ASP_NET/RTPSWebCore/WeatherForecast.cs
292
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Color_TD { class BlackDot : Dot { public BlackDot () : base(1, 100, 0.125f, 10, 0) { } public override EnemyType EnemyType => EnemyType.BlackDot; } }
19.352941
66
0.683891
[ "MIT" ]
EMattfolk/Color-TD
Color TD/Enemies/BlackDot.cs
331
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewCakeProblems.Arrays { /// <summary> /// Problem $43 /// We have our lists of orders sorted numerically already, in arrays. /// Write a method to merge our arrays of orders into one sorted array. /// </summary> public class MergeSortedArrays { public int[] MergeArrays(int[] firstArray, int[] secondArray) { int[] mergedArray = new int[firstArray.Length + secondArray.Length]; int firstIndex = 0; int secondIndex = 0; int mergedIndex = 0; while (firstIndex < firstArray.Length || secondIndex < secondArray.Length) { if (firstIndex < firstArray.Length && firstArray[firstIndex] <= secondArray[secondIndex]) { mergedArray[mergedIndex] = firstArray[firstIndex]; firstIndex++; } else if (secondIndex < secondArray.Length) { mergedArray[mergedIndex] = secondArray[secondIndex]; secondIndex++; } mergedIndex++; } return mergedArray; } } }
29.311111
105
0.554966
[ "MIT" ]
coshea/DSandAlgosCSharp
InterviewProblems/InterviewCakeProblems/Arrays/MergeSortedArrays.cs
1,321
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace JOD.Writer.Models.content { public class TextSequenceDecl { [XmlAttribute(ContentKeyword.text_display_outline_level)] public string text_display_outline_level { get; set; } [XmlAttribute(ContentKeyword.text_name)] public string text_name { get; set; } } }
24.235294
65
0.723301
[ "MIT" ]
moncci/JOD
JOD/JOD/Writer/Models/content/TextSequenceDecl.cs
414
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/msxml.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IXMLAttribute" /> struct.</summary> public static unsafe class IXMLAttributeTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IXMLAttribute" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IXMLAttribute).GUID, Is.EqualTo(IID_IXMLAttribute)); } /// <summary>Validates that the <see cref="IXMLAttribute" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IXMLAttribute>(), Is.EqualTo(sizeof(IXMLAttribute))); } /// <summary>Validates that the <see cref="IXMLAttribute" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IXMLAttribute).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IXMLAttribute" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IXMLAttribute), Is.EqualTo(8)); } else { Assert.That(sizeof(IXMLAttribute), Is.EqualTo(4)); } } } }
36.057692
145
0.6272
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/msxml/IXMLAttributeTests.cs
1,877
C#
namespace GodSeekerPlus.Modules.QoL; [ToggleableLevel(ToggleableLevel.ChangeScene)] [DefaultEnabled] internal sealed class CorrectRadianceHP : Module { private static readonly int shift = -720; private protected override void Load() { On.HealthManager.Start += ModifyAbsRadStartHP; On.PlayMakerFSM.Start += ModifyAbsRadPhaseHP; } private protected override void Unload() { On.HealthManager.Start -= ModifyAbsRadStartHP; On.PlayMakerFSM.Start -= ModifyAbsRadPhaseHP; } private void ModifyAbsRadStartHP(On.HealthManager.orig_Start orig, HealthManager self) { if (self.gameObject is { scene.name: "GG_Radiance", name: "Absolute Radiance" }) { self.hp += shift; Logger.LogDebug("AbsRad start health modified"); } orig(self); } private void ModifyAbsRadPhaseHP(On.PlayMakerFSM.orig_Start orig, PlayMakerFSM self) { orig(self); if (self.gameObject is { scene.name: "GG_Radiance", name: "Absolute Radiance" }) { ModifyAbsRadPhaseHP(self); } } private static void ModifyAbsRadPhaseHP(PlayMakerFSM fsm) { if (fsm.FsmName == "Control") { fsm.GetState("Scream").Actions .OfType<SetHP>().First() .hp.Value += shift; fsm.GetVariable<FsmInt>("Death HP").Value += shift; Logger.LogDebug("AbsRad death health modified"); } else if (fsm.FsmName == "Phase Control") { fsm.GetVariable<FsmInt>("P2 Spike Waves").Value += shift; fsm.GetVariable<FsmInt>("P3 A1 Rage").Value += shift; fsm.GetVariable<FsmInt>("P4 Stun1").Value += shift; fsm.GetVariable<FsmInt>("P5 Acend").Value += shift; // Why TC Logger.LogDebug("AbsRad phase health modified"); } } }
26.836066
89
0.708613
[ "MIT" ]
Clazex/HollowKnight.GodSeekerPlus
GodSeekerPlus/Modules/QoL/CorrectRadianceHP.cs
1,637
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Shouldly; using Xunit; #pragma warning disable 0219 namespace Microsoft.Build.UnitTests { public class TaskItemTests { // Make sure a TaskItem can be constructed using an ITaskItem [Fact] public void ConstructWithITaskItem() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.SetMetadata("Dog", "Bingo"); from.SetMetadata("Cat", "Morris"); TaskItem to = new TaskItem((ITaskItem)from); to.ItemSpec.ShouldBe("Monkey.txt"); ((string)to).ShouldBe("Monkey.txt"); to.GetMetadata("Dog").ShouldBe("Bingo"); to.GetMetadata("Cat").ShouldBe("Morris"); // Test that item metadata are case-insensitive. to.SetMetadata("CaT", ""); to.GetMetadata("Cat").ShouldBe(""); // manipulate the item-spec a bit to.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("Monkey"); to.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".txt"); to.GetMetadata(FileUtilities.ItemSpecModifiers.RelativeDir).ShouldBe(string.Empty); } // Make sure metadata can be cloned from an existing ITaskItem [Fact] public void CopyMetadataFromITaskItem() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.SetMetadata("Dog", "Bingo"); from.SetMetadata("Cat", "Morris"); from.SetMetadata("Bird", "Big"); TaskItem to = new TaskItem(); to.ItemSpec = "Bonobo.txt"; to.SetMetadata("Sponge", "Bob"); to.SetMetadata("Dog", "Harriet"); to.SetMetadata("Cat", "Mike"); from.CopyMetadataTo(to); to.ItemSpec.ShouldBe("Bonobo.txt"); // ItemSpec is never overwritten to.GetMetadata("Sponge").ShouldBe("Bob"); // Metadata not in source are preserved. to.GetMetadata("Dog").ShouldBe("Harriet"); // Metadata present on destination are not overwritten. to.GetMetadata("Cat").ShouldBe("Mike"); to.GetMetadata("Bird").ShouldBe("Big"); } [Fact] public void NullITaskItem() { Should.Throw<ArgumentNullException>(() => { ITaskItem item = null; TaskItem taskItem = new TaskItem(item); // no NullReferenceException } ); } /// <summary> /// Even without any custom metadata metadatanames should /// return the built in metadata /// </summary> [Fact] public void MetadataNamesNoCustomMetadata() { TaskItem taskItem = new TaskItem("x"); taskItem.MetadataNames.Count.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); taskItem.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); // Now add one taskItem.SetMetadata("m", "m1"); taskItem.MetadataNames.Count.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); taskItem.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); } [Fact] public void NullITaskItemCast() { Should.Throw<ArgumentNullException>(() => { TaskItem item = null; string result = (string)item; // no NullReferenceException } ); } [Fact] public void ConstructFromDictionary() { Hashtable h = new Hashtable(); h[FileUtilities.ItemSpecModifiers.Filename] = "foo"; h[FileUtilities.ItemSpecModifiers.Extension] = "bar"; h["custom"] = "hello"; TaskItem t = new TaskItem("bamboo.baz", h); // item-spec modifiers were not overridden by dictionary passed to constructor t.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("bamboo"); t.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".baz"); t.GetMetadata("CUSTOM").ShouldBe("hello"); } [Fact] public void CannotChangeModifiers() { Should.Throw<ArgumentException>(() => { TaskItem t = new TaskItem("foo"); try { t.SetMetadata(FileUtilities.ItemSpecModifiers.FullPath, "bazbaz"); } catch (Exception e) { // so I can see the exception message in NUnit's "Standard Out" window Console.WriteLine(e.Message); throw; } } ); } [Fact] public void CannotRemoveModifiers() { Should.Throw<ArgumentException>(() => { TaskItem t = new TaskItem("foor"); try { t.RemoveMetadata(FileUtilities.ItemSpecModifiers.RootDir); } catch (Exception e) { // so I can see the exception message in NUnit's "Standard Out" window Console.WriteLine(e.Message); throw; } } ); } [Fact] public void CheckMetadataCount() { TaskItem t = new TaskItem("foo"); t.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length); t.SetMetadata("grog", "RUM"); t.MetadataCount.ShouldBe(FileUtilities.ItemSpecModifiers.All.Length + 1); } [Fact] public void NonexistentRequestFullPath() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.FullPath).ShouldBe( Path.Combine ( Directory.GetCurrentDirectory(), "Monkey.txt" ) ); } [Fact] public void NonexistentRequestRootDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RootDir).ShouldBe(Path.GetPathRoot(from.GetMetadata(FileUtilities.ItemSpecModifiers.FullPath))); } [Fact] public void NonexistentRequestFilename() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Filename).ShouldBe("Monkey"); } [Fact] public void NonexistentRequestExtension() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Extension).ShouldBe(".txt"); } [Fact] public void NonexistentRequestRelativeDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RelativeDir).Length.ShouldBe(0); } [Fact] public void NonexistentRequestDirectory() { TaskItem from = new TaskItem(); from.ItemSpec = NativeMethodsShared.IsWindows ? @"c:\subdir\Monkey.txt" : "/subdir/Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Directory).ShouldBe(NativeMethodsShared.IsWindows ? @"subdir\" : "subdir/"); } [Fact] public void NonexistentRequestDirectoryUNC() { if (!NativeMethodsShared.IsWindows) { return; // "UNC is not implemented except under Windows" } TaskItem from = new TaskItem(); from.ItemSpec = @"\\local\share\subdir\Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Directory).ShouldBe(@"subdir\"); } [Fact] public void NonexistentRequestRecursiveDir() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.RecursiveDir).Length.ShouldBe(0); } [Fact] public void NonexistentRequestIdentity() { TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.Identity).ShouldBe("Monkey.txt"); } [Fact] public void RequestTimeStamps() { TaskItem from = new TaskItem(); from.ItemSpec = FileUtilities.GetTemporaryFile(); from.GetMetadata(FileUtilities.ItemSpecModifiers.ModifiedTime).Length.ShouldBeGreaterThan(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.CreatedTime).Length.ShouldBeGreaterThan(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.AccessedTime).Length.ShouldBeGreaterThan(0); File.Delete(from.ItemSpec); from.GetMetadata(FileUtilities.ItemSpecModifiers.ModifiedTime).Length.ShouldBe(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.CreatedTime).Length.ShouldBe(0); from.GetMetadata(FileUtilities.ItemSpecModifiers.AccessedTime).Length.ShouldBe(0); } /// <summary> /// Verify metadata cannot be created with null name /// </summary> [Fact] public void CreateNullNamedMetadata() { Should.Throw<ArgumentNullException>(() => { TaskItem item = new TaskItem("foo"); item.SetMetadata(null, "x"); } ); } /// <summary> /// Verify metadata cannot be created with empty name /// </summary> [Fact] public void CreateEmptyNamedMetadata() { Should.Throw<ArgumentException>(() => { TaskItem item = new TaskItem("foo"); item.SetMetadata("", "x"); } ); } /// <summary> /// Create a TaskItem with a null metadata value -- this is allowed, but /// internally converted to the empty string. /// </summary> [Fact] public void CreateTaskItemWithNullMetadata() { IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add("m", null); TaskItem item = new TaskItem("bar", (IDictionary)metadata); item.GetMetadata("m").ShouldBe(string.Empty); } /// <summary> /// Set metadata value to null value -- this is allowed, but /// internally converted to the empty string. /// </summary> [Fact] public void SetNullMetadataValue() { TaskItem item = new TaskItem("bar"); item.SetMetadata("m", null); item.GetMetadata("m").ShouldBe(string.Empty); } #if FEATURE_APPDOMAIN /// <summary> /// Test that task items can be successfully constructed based on a task item from another appdomain. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] [Trait("Category", "mono-windows-failing")] public void RemoteTaskItem() { AppDomain appDomain = null; try { appDomain = AppDomain.CreateDomain ( "generateResourceAppDomain", null, AppDomain.CurrentDomain.SetupInformation ); object obj = appDomain.CreateInstanceFromAndUnwrap ( typeof(TaskItemCreator).Module.FullyQualifiedName, typeof(TaskItemCreator).FullName ); TaskItemCreator creator = (TaskItemCreator)obj; IDictionary<string, string> metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("c", "C"); metadata.Add("d", "D"); creator.Run(new[] { "a", "b" }, metadata); ITaskItem[] itemsInThisAppDomain = new ITaskItem[creator.CreatedTaskItems.Length]; for (int i = 0; i < creator.CreatedTaskItems.Length; i++) { itemsInThisAppDomain[i] = new TaskItem(creator.CreatedTaskItems[i]); itemsInThisAppDomain[i].ItemSpec.ShouldBe(creator.CreatedTaskItems[i].ItemSpec); itemsInThisAppDomain[i].MetadataCount.ShouldBe(creator.CreatedTaskItems[i].MetadataCount + 1); foreach (string metadatum in creator.CreatedTaskItems[i].MetadataNames) { if (!string.Equals("OriginalItemSpec", metadatum)) { itemsInThisAppDomain[i].GetMetadata(metadatum).ShouldBe(creator.CreatedTaskItems[i].GetMetadata(metadatum)); } } } } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } } /// <summary> /// Miniature class to be remoted to another appdomain that just creates some TaskItems and makes them available for returning. /// </summary> private sealed class TaskItemCreator #if FEATURE_APPDOMAIN : MarshalByRefObject #endif { /// <summary> /// Task items that will be consumed by the other appdomain /// </summary> public ITaskItem[] CreatedTaskItems { get; private set; } /// <summary> /// Creates task items /// </summary> public void Run(string[] includes, IDictionary<string, string> metadataToAdd) { ErrorUtilities.VerifyThrowArgumentNull(includes, nameof(includes)); CreatedTaskItems = new TaskItem[includes.Length]; for (int i = 0; i < includes.Length; i++) { CreatedTaskItems[i] = new TaskItem(includes[i], (IDictionary)metadataToAdd); } } } #endif } }
34.611494
157
0.54563
[ "MIT" ]
Youssef1313/msbuild
src/Utilities.UnitTests/TaskItem_Tests.cs
15,056
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20210201 { public static class GetVirtualWan { /// <summary> /// VirtualWAN Resource. /// </summary> public static Task<GetVirtualWanResult> InvokeAsync(GetVirtualWanArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetVirtualWanResult>("azure-native:network/v20210201:getVirtualWan", args ?? new GetVirtualWanArgs(), options.WithVersion()); } public sealed class GetVirtualWanArgs : Pulumi.InvokeArgs { /// <summary> /// The resource group name of the VirtualWan. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the VirtualWAN being retrieved. /// </summary> [Input("virtualWANName", required: true)] public string VirtualWANName { get; set; } = null!; public GetVirtualWanArgs() { } } [OutputType] public sealed class GetVirtualWanResult { /// <summary> /// True if branch to branch traffic is allowed. /// </summary> public readonly bool? AllowBranchToBranchTraffic; /// <summary> /// True if Vnet to Vnet traffic is allowed. /// </summary> public readonly bool? AllowVnetToVnetTraffic; /// <summary> /// Vpn encryption to be disabled or not. /// </summary> public readonly bool? DisableVpnEncryption; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Resource location. /// </summary> public readonly string Location; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The office local breakout category. /// </summary> public readonly string Office365LocalBreakoutCategory; /// <summary> /// The provisioning state of the virtual WAN resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// List of VirtualHubs in the VirtualWAN. /// </summary> public readonly ImmutableArray<Outputs.SubResourceResponse> VirtualHubs; /// <summary> /// List of VpnSites in the VirtualWAN. /// </summary> public readonly ImmutableArray<Outputs.SubResourceResponse> VpnSites; [OutputConstructor] private GetVirtualWanResult( bool? allowBranchToBranchTraffic, bool? allowVnetToVnetTraffic, bool? disableVpnEncryption, string etag, string? id, string location, string name, string office365LocalBreakoutCategory, string provisioningState, ImmutableDictionary<string, string>? tags, string type, ImmutableArray<Outputs.SubResourceResponse> virtualHubs, ImmutableArray<Outputs.SubResourceResponse> vpnSites) { AllowBranchToBranchTraffic = allowBranchToBranchTraffic; AllowVnetToVnetTraffic = allowVnetToVnetTraffic; DisableVpnEncryption = disableVpnEncryption; Etag = etag; Id = id; Location = location; Name = name; Office365LocalBreakoutCategory = office365LocalBreakoutCategory; ProvisioningState = provisioningState; Tags = tags; Type = type; VirtualHubs = virtualHubs; VpnSites = vpnSites; } } }
31.34507
179
0.594248
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20210201/GetVirtualWan.cs
4,451
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.34014 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace IHM.Properties { /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [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> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </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("IHM.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.625
169
0.615043
[ "MIT" ]
Paphos/ProjetBFME_XAML
IHM/Properties/Resources.Designer.cs
2,959
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using System.Windows.Forms; using SharpShell.Interop; namespace ServerManager.TestShell { public partial class ShellPreviewHost : UserControl { public ShellPreviewHost() { InitializeComponent(); } public void SetPreviewHandler(Guid previewHandlerGuid) { // Try and create an instance of the preview handler. var previewHandlerType = Type.GetTypeFromCLSID(previewHandlerGuid); previewHandler = Activator.CreateInstance(previewHandlerType); } public void SetPreviewItem(string path) { if (previewHandler is IInitializeWithFile) { ((IInitializeWithFile)previewHandler).Initialize(path, 0); } else if (previewHandler is IInitializeWithStream) { var managedStream = File.Open(path, FileMode.Open); var stream = new StreamWrapper(managedStream); ((IInitializeWithStream)previewHandler).Initialize(stream, 0); } if (previewHandler is IPreviewHandler) { RECT rect = new RECT() {bottom = ClientRectangle.Bottom, left = ClientRectangle.Left, right = ClientRectangle.Right, top = ClientRectangle.Top}; ((IPreviewHandler)previewHandler).SetWindow(Handle, rect); ((IPreviewHandler)previewHandler).DoPreview(); } } private object previewHandler; private void ShellPreviewHost_Resize(object sender, EventArgs e) { // Do we habe a preview handler? if(previewHandler != null && previewHandler is IPreviewHandler) ((IPreviewHandler) previewHandler).SetRect(new RECT {bottom = ClientRectangle.Bottom, left = ClientRectangle.Left, right = ClientRectangle.Right, top = ClientRectangle.Top}); } } /// <summary> /// Provides a bare-bones implementation of System.Runtime.InteropServices.IStream that wraps an System.IO.Stream. /// </summary> [ClassInterface(ClassInterfaceType.AutoDispatch)] internal class StreamWrapper : IStream { private System.IO.Stream mInner; /// <summary> /// Initialises a new instance of the StreamWrapper class, using the specified System.IO.Stream. /// </summary> /// <param name="inner"></param> public StreamWrapper(System.IO.Stream inner) { mInner = inner; } /// <summary> /// This operation is not supported. /// </summary> /// <param name="ppstm"></param> public void Clone(out IStream ppstm) { throw new NotSupportedException(); } /// <summary> /// This operation is not supported. /// </summary> /// <param name="grfCommitFlags"></param> public void Commit(int grfCommitFlags) { throw new NotSupportedException(); } /// <summary> /// This operation is not supported. /// </summary> /// <param name="pstm"></param> /// <param name="cb"></param> /// <param name="pcbRead"></param> /// <param name="pcbWritten"></param> public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) { throw new NotSupportedException(); } /// <summary> /// This operation is not supported. /// </summary> /// <param name="libOffset"></param> /// <param name="cb"></param> /// <param name="dwLockType"></param> public void LockRegion(long libOffset, long cb, int dwLockType) { throw new NotSupportedException(); } /// <summary> /// Reads a sequence of bytes from the underlying System.IO.Stream. /// </summary> /// <param name="pv"></param> /// <param name="cb"></param> /// <param name="pcbRead"></param> public void Read(byte[] pv, int cb, IntPtr pcbRead) { long bytesRead = mInner.Read(pv, 0, cb); if (pcbRead != IntPtr.Zero) Marshal.WriteInt64(pcbRead, bytesRead); } /// <summary> /// This operation is not supported. /// </summary> public void Revert() { throw new NotSupportedException(); } /// <summary> /// Advances the stream to the specified position. /// </summary> /// <param name="dlibMove"></param> /// <param name="dwOrigin"></param> /// <param name="plibNewPosition"></param> public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition) { long pos = mInner.Seek(dlibMove, (System.IO.SeekOrigin)dwOrigin); if (plibNewPosition != IntPtr.Zero) Marshal.WriteInt64(plibNewPosition, pos); } /// <summary> /// This operation is not supported. /// </summary> /// <param name="libNewSize"></param> public void SetSize(long libNewSize) { throw new NotSupportedException(); } /// <summary> /// Returns details about the stream, including its length, type and name. /// </summary> /// <param name="pstatstg"></param> /// <param name="grfStatFlag"></param> public void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, int grfStatFlag) { pstatstg = new System.Runtime.InteropServices.ComTypes.STATSTG(); pstatstg.cbSize = mInner.Length; pstatstg.type = 2; // stream type pstatstg.pwcsName = (mInner is FileStream) ? ((FileStream)mInner).Name : String.Empty; } /// <summary> /// This operation is not supported. /// </summary> /// <param name="libOffset"></param> /// <param name="cb"></param> /// <param name="dwLockType"></param> public void UnlockRegion(long libOffset, long cb, int dwLockType) { throw new NotSupportedException(); } /// <summary> /// Writes a sequence of bytes to the underlying System.IO.Stream. /// </summary> /// <param name="pv"></param> /// <param name="cb"></param> /// <param name="pcbWritten"></param> public void Write(byte[] pv, int cb, IntPtr pcbWritten) { mInner.Write(pv, 0, cb); if (pcbWritten != IntPtr.Zero) Marshal.WriteInt64(pcbWritten, (Int64)cb); } } }
34.477387
190
0.575864
[ "MIT" ]
cfwprpht/sharpshell
SharpShell/Tools/ServerManager/TestShell/ShellPreviewHost.cs
6,863
C#
// This file is part of TagSoup and is Copyright 2002-2008 by John Cowan. // // TagSoup is licensed under the Apache License, // Version 2.0. You may obtain a copy of this license at // http://www.apache.org/licenses/LICENSE-2.0 . You may also have // additional legal rights not granted by this license. // // TagSoup is distributed in the hope that it will be useful, but // unless required by applicable law or agreed to in writing, TagSoup // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied; not even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. using J2N.Text; using Sax.Helpers; using System; using System.Text; namespace TagSoup { /// <summary> /// This class represents an element type in the schema. /// An element type has a name, a content model vector, a member-of vector, /// a flags vector, default attributes, and a schema to which it belongs. /// </summary> /// <seealso cref="Schema" /> public class ElementType { private readonly Attributes atts; // default attributes private readonly string localName; // element type local name private readonly string name; // element type name (Qname) private readonly string @namespace; // element type namespace name private readonly Schema schema; // schema to which this belongs /// <summary> /// Construct an <see cref="ElementType"/>: /// but it's better to use <see cref="Schema.ElementType(string, int, int, int)"/> instead. /// The content model, member-of, and flags vectors are specified as ints. /// </summary> /// <param name="name">The element type name</param> /// <param name="model">ORed-together bits representing the content /// models allowed in the content of this element type</param> /// <param name="memberOf">ORed-together bits representing the content models /// to which this element type belongs</param> /// <param name="flags">ORed-together bits representing the flags associated /// with this element type</param> /// <param name="schema"> /// The schema with which this element type will be associated /// </param> public ElementType(string name, int model, int memberOf, int flags, Schema schema) { this.name = name; Model = model; MemberOf = memberOf; Flags = flags; atts = new Attributes(); this.schema = schema; @namespace = GetNamespace(name, false); localName = GetLocalName(name); } /// <summary> /// Gets the name of this element type. /// </summary> public virtual string Name { get { return name; } } /// <summary> /// Gets the namespace name of this element type. /// </summary> public virtual string Namespace { get { return @namespace; } } /// <summary> /// Gets the local name of this element type. /// </summary> public virtual string LocalName { get { return localName; } } /// <summary> /// Gets or sets the content models of this element type as a vector of bits /// </summary> public virtual int Model { get; set; } /// <summary> /// Gets or sets the content models to which this element type belongs as a vector of bits /// </summary> public virtual int MemberOf { get; set; } /// <summary> /// Gets or sets the flags associated with this element type as a vector of bits /// </summary> public virtual int Flags { get; set; } /// <summary> /// Returns the default attributes associated with this element type. /// Attributes of type CDATA that don't have default values are /// typically not included. Other attributes without default values /// have an internal value of <c>null</c>. /// The return value is an Attributes to allow the caller to mutate /// the attributes. /// </summary> public virtual Attributes Attributes { get { return atts; } } /// <summary> /// Gets or sets the parent element type of this element type. /// </summary> public virtual ElementType Parent { get; set; } /// <summary> /// Gets the schema which this element type is associated with. /// </summary> public virtual Schema Schema { get { return schema; } } /// <summary> /// Return a namespace name from a Qname. /// The attribute flag tells us whether to return an empty namespace /// name if there is no prefix, or use the schema default instead. /// </summary> /// <param name="name">The Qname</param> /// <param name="attribute">True if name is an attribute name</param> /// <returns>The namespace name</returns> public virtual string GetNamespace(string name, bool attribute) { int colon = name.IndexOf(':'); if (colon == -1) { return attribute ? "" : schema.Uri; } string prefix = name.Substring(0, colon); if (prefix.Equals("xml", StringComparison.Ordinal)) { return "http://www.w3.org/XML/1998/namespace"; } return "urn:x-prefix:" + prefix.Intern(); } /// <summary> /// Return a local name from a Qname. /// </summary> /// <param name="name">The Qname</param> /// <returns>The local name</returns> public virtual string GetLocalName(string name) { int colon = name.IndexOf(':'); if (colon == -1) { return name; } return name.Substring(colon + 1).Intern(); } /// <summary> /// Returns <c>true</c> if this element type can contain another element type. /// That is, if any of the models in this element's model vector /// match any of the models in the other element type's member-of /// vector. /// </summary> /// <param name="other">The other element type</param> public virtual bool CanContain(ElementType other) { return (Model & other.MemberOf) != 0; } /// <summary> /// Sets an attribute and its value into an <see cref="Sax.IAttributes"/> object. /// Attempts to set a namespace declaration are ignored. /// </summary> /// <param name="atts">The <see cref="Sax.Helpers.Attributes"/> object</param> /// <param name="name">The name (Qname) of the attribute</param> /// <param name="type">The type of the attribute</param> /// <param name="value">The value of the attribute</param> public virtual void SetAttribute(Attributes atts, string name, string type, string value) { if (name.Equals("xmlns", StringComparison.Ordinal) || name.StartsWith("xmlns:", StringComparison.Ordinal)) { return; } string ns = GetNamespace(name, true); string localName = GetLocalName(name); int i = atts.GetIndex(name); if (i == -1) { name = name.Intern(); if (type == null) { type = "CDATA"; } if (!type.Equals("CDATA", StringComparison.Ordinal)) { value = Normalize(value); } atts.AddAttribute(ns, localName, name, type, value); } else { if (type == null) { type = atts.GetType(i); } if (!type.Equals("CDATA", StringComparison.Ordinal)) { value = Normalize(value); } atts.SetAttribute(i, ns, localName, name, type, value); } } /// <summary> /// Normalize an attribute value (ID-style). /// CDATA-style attribute normalization is already done. /// </summary> /// <param name="value">The value to normalize</param> public static string Normalize(string value) { if (value == null) { return null; } value = value.Trim(); if (value.IndexOf(" ", StringComparison.Ordinal) == -1) { return value; } bool space = false; var b = new StringBuilder(value.Length); foreach (char v in value) { if (v == ' ') { if (!space) { b.Append(v); } space = true; } else { b.Append(v); space = false; } } return b.ToString(); } /// <summary> /// Sets an attribute and its value into this element type. /// </summary> /// <param name="name">The name of the attribute</param> /// <param name="type">The type of the attribute</param> /// <param name="value">The value of the attribute</param> public virtual void SetAttribute(string name, string type, string value) { SetAttribute(atts, name, type, value); } } }
36.446494
118
0.533867
[ "Apache-2.0" ]
bongohrtech/lucenenet
src/Lucene.Net.Benchmark/Support/TagSoup/ElementType.cs
9,879
C#
using OreUnifyGenerator.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OreUnifyGenerator.Model.Texture { public class TextureRegistry : ITextureRegistry { private readonly Dictionary<string, HashSet<string>> categories = new Dictionary<string, HashSet<string>>(); public void AddFromProvider(ITextureProvider provider) { foreach(string category in provider.Categories()) { AddCategory(category); AddFeatures(category, provider.Features(category)); } } public void AddCategory(string category) => this.categories.Put(category, new HashSet<string>()); public void AddCategories(IEnumerable<string> categories) { foreach(string category in categories) { AddCategory(category); } } public void AddFeature(string category, string feature) { if (this.categories.ContainsKey(category)) { this.categories[category].Add(feature); } else { this.categories.Add(category, new HashSet<string>() { feature }); } } public void AddFeatures(string category, IEnumerable<string> features) { if (this.categories.ContainsKey(category)) { var list = this.categories[category]; foreach(string feature in features) { list.Add(feature); } } else { var list = new HashSet<string>(); foreach(string feature in features) { list.Add(feature); } this.categories.Add(category, list); } } public void Clear() { foreach(string category in Categories()) { ClearFeatures(category); } ClearCategories(); } public void ClearCategories() { } public void ClearFeatures(string category) => this.categories.Remove(category); public void RemoveCategory(string category) => this.categories.RemoveSafely(category); public void RemoveFeature(string category, string feature) { if (!this.categories.ContainsKey(category)) { return; } var list = this.categories[category]; list.Remove(feature); } public IEnumerable<string> Categories() => this.categories.Keys; public IEnumerable<string> Features(string category) => this.categories.GetOrEmpty(category); } }
27.634146
111
0.68932
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
yuma140902/OreUnifyGenerator
OreUnifyGenerator/Model/Texture/TextureRegistry.cs
2,268
C#
namespace Presentacion { partial class BuscarAdicional { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); this.label1 = new System.Windows.Forms.Label(); this.BuscarTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.dataGridView1 = new Bunifu.Framework.UI.BunifuCustomDataGrid(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(218, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(293, 29); this.label1.TabIndex = 0; this.label1.Text = "BUSCAR ADICIONALES"; this.label1.Click += new System.EventHandler(this.label1_Click); // // BuscarTextBox // this.BuscarTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.BuscarTextBox.Location = new System.Drawing.Point(267, 67); this.BuscarTextBox.Name = "BuscarTextBox"; this.BuscarTextBox.Size = new System.Drawing.Size(192, 29); this.BuscarTextBox.TabIndex = 2; this.BuscarTextBox.TextChanged += new System.EventHandler(this.BuscarTextBox_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(146, 69); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(86, 25); this.label2.TabIndex = 0; this.label2.Text = "PLACA"; this.label2.Click += new System.EventHandler(this.label1_Click); // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(485, 64); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(98, 37); this.button1.TabIndex = 3; this.button1.Text = "Buscar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView1.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(45)))), ((int)(((byte)(65))))); this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView1.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopCenter; dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(97)))), ((int)(((byte)(216))))); dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White; dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 3); dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.DoubleBuffered = true; this.dataGridView1.EnableHeadersVisualStyles = false; this.dataGridView1.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(97)))), ((int)(((byte)(216))))); this.dataGridView1.HeaderBgColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(97)))), ((int)(((byte)(216))))); this.dataGridView1.HeaderForeColor = System.Drawing.Color.White; this.dataGridView1.Location = new System.Drawing.Point(74, 118); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle3.Padding = new System.Windows.Forms.Padding(0, 2, 0, 2); dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.Black; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; this.dataGridView1.RowHeadersWidth = 10; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(581, 375); this.dataGridView1.TabIndex = 1014; this.dataGridView1.VirtualMode = true; this.dataGridView1.DoubleClick += new System.EventHandler(this.dataGridView1_DoubleClick); // // BuscarAdicional // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(45)))), ((int)(((byte)(60))))); this.ClientSize = new System.Drawing.Size(728, 553); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.button1); this.Controls.Add(this.BuscarTextBox); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "BuscarAdicional"; this.Text = "BuscarAdicional"; this.Load += new System.EventHandler(this.BuscarAdicional_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox BuscarTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button1; private Bunifu.Framework.UI.BunifuCustomDataGrid dataGridView1; } }
61.031447
178
0.64932
[ "MIT" ]
yackfranco/InventarioEquipos
Presentacion/BuscarAdicional.Designer.cs
9,706
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Jannesen.Library.Tasks { public static class TaskHelpers { public static async Task<bool> WhenAllWithTimeout(int milliseconds, params Task[] tasks) { var timeoutCompletionSource = new TaskCompletionSource<object>(); var timeoutTask = timeoutCompletionSource.Task; if (milliseconds <= 0) { for (int i = 0 ; i < tasks.Length ; ++i) { if (tasks[i].Status != TaskStatus.Running) { return false; } } return true; } using (var x = new Timer((object state) => { ((TaskCompletionSource<object>)state).TrySetResult(null); }, timeoutCompletionSource, milliseconds, 0)) { for (int i = 0 ; i < tasks.Length ; ++i) { await Task.WhenAny(tasks[i], timeoutTask); if (timeoutTask.IsCompleted) { return false; } } return true; } } public static async Task WhenAllWithCancellation(Task[] tasks, CancellationToken ct) { if (tasks is null) throw new ArgumentNullException(nameof(tasks)); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); using (var x = ct.Register(() => { tcs.SetException(new TaskCanceledException()); })) { for (int i = 0 ; i < tasks.Length ; ++i) { if (tasks[i] != null) { await Task.WhenAny(tasks[i], tcs.Task); } } } } } }
34.461538
162
0.492746
[ "Apache-2.0" ]
jannesen/Jannesen.Library.Task
src/TaskHelpers.cs
1,794
C#
#region Copyright & License // Copyright © 2012 - 2017 François Chabot, Yves Dierick // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Be.Stateless.BizTalk.Component; using Be.Stateless.BizTalk.ContextProperties; using Be.Stateless.BizTalk.Dsl.Pipeline; using Be.Stateless.BizTalk.Dsl.Pipeline.Interpreters; using Be.Stateless.BizTalk.Message.Extensions; using Be.Stateless.BizTalk.MicroComponent; using Be.Stateless.BizTalk.Unit.Resources; using Microsoft.BizTalk.Message.Interop; using NUnit.Framework; using Winterdom.BizTalk.PipelineTesting; namespace Be.Stateless.BizTalk.Pipelines { [TestFixture] public class ReceivePipelineFixture { [Test] public void DeferredPluginIsAlwaysExecuted() { using (var stream = ResourceManager.Load("Data.Content.zip")) { var pipeline = PipelineFactory.CreateReceivePipeline(typeof(ReceivePipelineInterpreter<ZipPassThruReceive>)); var pluginComponent = (ContextBuilderComponent) pipeline.GetComponent(PipelineStage.Decode, 0); pluginComponent.ExecutionMode = PluginExecutionMode.Deferred; pluginComponent.Builder = typeof(ContextBuilder); var inputMessage = MessageHelper.CreateFromStream(stream); var outputMessages = pipeline.Execute(inputMessage); Assert.That(outputMessages, Is.Not.Null); Assert.That(outputMessages.Count, Is.EqualTo(1)); Assert.That(outputMessages[0].GetProperty(TrackingProperties.Value1), Is.EqualTo("Plugin has been executed.")); } } private class ZipPassThruReceive : ReceivePipeline { public ZipPassThruReceive() { Description = "Unit testable receive pipeline with zip-deflating capability."; Version = new Version(1, 0); VersionDependentGuid = new Guid("f68bbcd2-651e-4c0e-875f-40dce996c6f7"); Stages.Decode .AddComponent(new ContextBuilderComponent { Enabled = true }) .AddComponent(new ZipDecoderComponent { Enabled = true }); } } private class ContextBuilder : IContextBuilder { #region IContextBuilder Members public void Execute(IBaseMessageContext context) { context.SetProperty(TrackingProperties.Value1, "Plugin has been executed."); } #endregion } } }
33.926829
116
0.739756
[ "Apache-2.0" ]
icraftsoftware/BizTalk.Factory
src/BizTalk.Pipelines.Tests/Pipelines/ReceivePipelineFixture.cs
2,786
C#
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using DataBlocks.Core; using LanguageExt; using System.Collections.Immutable; namespace DataBlocks.Json { /// <summary> /// Utilities for decoding JSON /// </summary> public static class JsonDecoder { /// <summary> /// Create a JSON decoder from a function. /// </summary> public static Decoder<JToken, T> Create<T>(Func<string, JToken, Either<DecoderErrors, T>> decode) => new Decoder<JToken, T>(decode, "$"); /// <summary> /// Create a JSON decoder that will return a predetermined result. /// </summary> public static Decoder<JToken, T> Return<T>(Either<DecoderErrors, T> result) => Create((id, _) => result); private static Decoder<JToken, T> Value<T>(string description, Func<JValue, bool> valuePredicate, Func<object, T> convert) => Create( (id, json) => json is JValue v && valuePredicate(v) ? (Either<DecoderErrors, T>)convert(v.Value) : DecoderErrors.Single(id, $"Expected {description} value")); /// <summary> /// Decodes a boolean value. /// </summary> public static readonly Decoder<JToken, bool> Bool = Value("a boolean", v => v.Type == JTokenType.Boolean, Convert.ToBoolean); /// <summary> /// Decodes a decimal value. /// </summary> public static readonly Decoder<JToken, decimal> Decimal = Value("a decimal", v => v.Type == JTokenType.Float || v.Type == JTokenType.Integer, Convert.ToDecimal); /// <summary> /// Decodes a double value. /// </summary> public static readonly Decoder<JToken, double> Double = Value("a double", v => v.Type == JTokenType.Float || v.Type == JTokenType.Integer, Convert.ToDouble); /// <summary> /// Decodes a float value. /// </summary> public static readonly Decoder<JToken, float> Float = Value("a float", v => v.Type == JTokenType.Float || v.Type == JTokenType.Integer, Convert.ToSingle); /// <summary> /// Decodes a GUID value. /// </summary> public static readonly Decoder<JToken, Guid> Guid = Value( "a GUID", v => v.Type == JTokenType.Guid || v.Type == JTokenType.String && System.Guid.TryParse((string)v.Value, out var guid), x => x as Guid? ?? System.Guid.Parse((string)x)); /// <summary> /// Decodes an integer value. /// </summary> public static readonly Decoder<JToken, int> Int = Value("an integer", v => v.Type == JTokenType.Integer, Convert.ToInt32); /// <summary> /// Decodes a string value. /// </summary> public static readonly Decoder<JToken, string> String = Value("a string", v => v.Type == JTokenType.String, x => (string)x); /// <summary> /// Decodes an optional value. /// </summary> public static Decoder<JToken, Option<T>> Nullable<T>(Decoder<JToken, T> valueDecoder) => Create((id, json) => json.Type == JTokenType.Null ? Option<T>.None : valueDecoder.Run(id, json).Map(Option<T>.Some)); /// <summary> /// Decodes an array. /// </summary> public static Decoder<JToken, IEnumerable<T>> Array<T>(Decoder<JToken, T> elementDecoder) => Create((id, json) => { if (json is JArray arr) { var results = arr.Values() .Select((element, i) => elementDecoder.Run($"{id}[{i}]", element)) .Aggregate( new { Results = ImmutableList.Create<T>(), Errors = DecoderErrors.Empty }, (state, r) => r.Match( v => new { Results = state.Results.Add(v), state.Errors }, e => new { state.Results, Errors = state.Errors.Append(e) }) ); return results.Errors.Errors.Any() ? (Either<DecoderErrors, IEnumerable<T>>)results.Errors : results.Results; } else { return DecoderErrors.Single(id, "Expected an array"); } }); /// <summary> /// Creates an empty decoder for decoding an object by specifying fields /// to decode. /// </summary> public static Decoder<JToken, Unit> Object<T>() => Return<Unit>(Unit.Default); private static Decoder<JToken, T> Required<T>(string fieldName, Decoder<JToken, T> fieldDecoder) => Create( (id, json) => { var fieldPath = id == string.Empty ? fieldName : $"{id}.{fieldName}"; return json is JObject obj ? obj.ContainsKey(fieldName) ? fieldDecoder.Run(fieldPath, obj.Property(fieldName).Value) : DecoderErrors.Single(fieldPath, "Value is required") : DecoderErrors.Single(id, "Expected an object"); } ); private static Decoder<JToken, Option<T>> Optional<T>(string fieldName, Decoder<JToken, T> decoder) => Create( (id, json) => { var fieldPath = id == string.Empty ? fieldName : $"{id}.{fieldName}"; return json is JObject obj ? obj.ContainsKey(fieldName) ? Nullable(decoder).Run(fieldPath, obj.Property(fieldName).Value) : Option<T>.None : DecoderErrors.Single(id, "Expected an object"); } ); /// <summary> /// Decodes a required field of an object and adds the result /// to the output. /// </summary> public static Decoder<JToken, T> Required<T>( this Decoder<JToken, Unit> decoder, string fieldName, Decoder<JToken, T> fieldDecoder) => Required(fieldName, fieldDecoder); /// <summary> /// Decodes a required field of an object and adds the result /// to the output. /// </summary> public static Decoder<JToken, Pair<T1, T2>> Required<T1, T2>( this Decoder<JToken, T1> decoder, string fieldName, Decoder<JToken, T2> fieldDecoder) => decoder.Combine(Required(fieldName, fieldDecoder)); /// <summary> /// Decodes an optional field of an object and adds the result /// to the output. /// </summary> public static Decoder<JToken, Option<T>> Optional<T>( this Decoder<JToken, Unit> decoder, string fieldName, Decoder<JToken, T> fieldDecoder) => Optional(fieldName, fieldDecoder); /// <summary> /// Decodes an optional field of an object and adds the result /// to the output. /// </summary> public static Decoder<JToken, Pair<T1, Option<T2>>> Optional<T1, T2>( this Decoder<JToken, T1> decoder, string fieldName, Decoder<JToken, T2> fieldDecoder) => decoder.Combine(Optional(fieldName, fieldDecoder)); } }
36.509346
145
0.512095
[ "MIT" ]
jhbertra/DataBlocks-CSharp
DataBlocks/Json/JsonDecoder.cs
7,813
C#
using System.Collections.Generic; namespace Language { public class Language { public Dictionary<string, string> Phonemes = new Dictionary<string, string>() { {"C", "ptkmnls"}, {"V", "aeiou"}, {"S", "s"}, {"F", "mn"}, {"L", "rl"} }; public string Structure = "CVC"; public int Exponent = 2; public string[] Restricts; public Dictionary<char, string> Cortho = new Dictionary<char, string>(); public Dictionary<char, string> Vortho = new Dictionary<char, string>(); public bool NoOrtho = true; public bool NoMorph = true; public bool NoWordPool = true; public int MinSyll = 1; public int MaxSyll = 1; public Dictionary<string, List<string>> Morphemes = new Dictionary<string, List<string>>(); public Dictionary<string, List<string>> Words = new Dictionary<string, List<string>>(); public List<string> Names = new List<string>(); public char Joiner = ' '; public int MaxChar = 12; public int MinChar = 5; public string Definite; public string Genitive; } }
33.25
99
0.569758
[ "MIT" ]
Choochoo/FantasyMapGenerator
Language/Language.cs
1,199
C#
using System; using System.Numerics; namespace Windows.UI.Composition { public partial class Visual : global::Windows.UI.Composition.CompositionObject { private Vector2 _size; private Vector3 _offset; private Vector3 _scale = new Vector3(1, 1, 1); private Vector3 _centerPoint; private float _rotationAngleInDegrees; private Vector3 _rotationAxis = new Vector3(0, 0, 1); public Vector3 Offset { get { return _offset; } set { _offset = value; OnOffsetChanged(value); } } partial void OnOffsetChanged(Vector3 value); public bool IsVisible { get; set; } public CompositionCompositeMode CompositeMode { get; set; } public Vector3 CenterPoint { get { return _centerPoint; } set { _centerPoint = value; OnCenterPointChanged(value); } } partial void OnCenterPointChanged(Vector3 value); public global::System.Numerics.Vector3 Scale { get { return _scale; } set { _scale = value; OnScaleChanged(value); } } partial void OnScaleChanged(Vector3 value); public float RotationAngleInDegrees { get { return _rotationAngleInDegrees; } set { _rotationAngleInDegrees = value; OnRotationAngleInDegreesChanged(value); } } partial void OnRotationAngleInDegreesChanged(float value); public Vector2 Size { get { return _size; } set { _size = value; OnSizeChanged(value); } } partial void OnSizeChanged(Vector2 value); public float Opacity { get; set; } public Vector3 RotationAxis { get { return _rotationAxis; } set { _rotationAxis = value; OnRotationAxisChanged(value); } } partial void OnRotationAxisChanged(Vector3 value); public ContainerVisual Parent { get; set; } } }
23.305556
83
0.724076
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/UI/Composition/Visual.cs
1,678
C#
using UnityEngine; using UnityEngine.UI; public abstract class LabledButton : MonoBehaviour { [SerializeField] protected Text label = null; [SerializeField] protected Button clickable = null; public Button Clickable => clickable; }
24.6
55
0.756098
[ "Unlicense" ]
nopetrides/ESG
techtest-unity-master/Assets/Scripts/Utility/LabledButton.cs
248
C#
using KdbSharp.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace KdbSharp.Tests.Data { [TestClass] public class KdbFloatVectorTests { private readonly KdbFloatVector _instance = new KdbFloatVector(new double[] { }); [TestMethod] public void KdbTypeIsFloatVector() => Assert.AreEqual(KdbType.FloatVector, _instance.Type); [TestMethod] public void ValueTypeIsDoubleArray() => Assert.AreEqual(typeof(double[]), _instance.Value.GetType()); } }
28.777778
109
0.706564
[ "MIT" ]
dstrachan/KdbSharp
KdbSharp.Tests/Data/KdbFloatVectorTests.cs
520
C#
using Huobi.SDK.Model.Response.WebSocket; using Newtonsoft.Json; namespace Huobi.SDK.Model.Response.Account { /// <summary> /// RequestAccount response /// </summary> public class RequestAccountResponse : WebSocketV1ResponseBase { /// <summary> /// Response body from sub /// </summary> public AccountBalance[] data; public class AccountBalance { /// <summary> /// Account id /// </summary> public int id; /// <summary> /// Account type /// </summary> public string type; /// <summary> /// Account staus /// </summary> public string state; /// <summary> /// The list of account balance /// </summary> public Balance[] list; /// <summary> /// Account balance /// </summary> public class Balance { /// <summary> /// sub-account currency /// </summary> public string currency; /// <summary> /// sub-account type /// Possible values: [including trade, loan, interest] /// </summary> public string type; /// <summary> /// sub-account balance /// </summary> public string balance; } } } }
24.171875
70
0.43245
[ "Apache-2.0" ]
HuobiRDCenter/huobi_CSharp
Huobi.SDK.Model/Response/Account/RequestAccountResponse.cs
1,549
C#
using System; using System.Globalization; using ClearHl7.Helpers; using ClearHl7.Serialization; using ClearHl7.V271.Types; namespace ClearHl7.V271.Segments { /// <summary> /// HL7 Version 2 Segment UAC - User Authentication Credential Segment. /// </summary> public class UacSegment : ISegment { /// <summary> /// Gets the ID for the Segment. This property is read-only. /// </summary> public string Id { get; } = "UAC"; /// <summary> /// Gets or sets the rank, or ordinal, which describes the place that this Segment resides in an ordered list of Segments. /// </summary> public int Ordinal { get; set; } /// <summary> /// UAC.1 - User Authentication Credential Type Code. /// <para>Suggested: 0615 User Authentication Credential Type Code -&gt; ClearHl7.Codes.V271.CodeUserAuthenticationCredentialTypeCode</para> /// </summary> public CodedWithExceptions UserAuthenticationCredentialTypeCode { get; set; } /// <summary> /// UAC.2 - User Authentication Credential. /// </summary> public EncapsulatedData UserAuthenticationCredential { get; set; } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <param name="separators">The separators to use for splitting the string.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } UserAuthenticationCredentialTypeCode = segments.Length > 1 && segments[1].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[1], false, seps) : null; UserAuthenticationCredential = segments.Length > 2 && segments[2].Length > 0 ? TypeSerializer.Deserialize<EncapsulatedData>(segments[2], false, seps) : null; } /// <summary> /// Returns a delimited string representation of this instance. /// </summary> /// <returns>A string.</returns> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 3, Configuration.FieldSeparator), Id, UserAuthenticationCredentialTypeCode?.ToDelimitedString(), UserAuthenticationCredential?.ToDelimitedString() ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
48.816092
181
0.62656
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7/V271/Segments/UacSegment.cs
4,249
C#
using System.ComponentModel; using Pchp.Core; /// <summary> /// Interface to provide accessing objects as arrays. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] [PhpType(PhpTypeAttribute.InheritName)] public interface ArrayAccess { /// <summary> /// Returns the value at specified offset. /// </summary> PhpValue offsetGet(PhpValue offset); /// <summary> /// Assigns a value to the specified offset. /// </summary> void offsetSet(PhpValue offset, PhpValue value); /// <summary> /// Unsets an offset. /// </summary> void offsetUnset(PhpValue offset); /// <summary> /// Whether an offset exists. /// </summary> /// <remarks>This method is executed when using isset() or empty().</remarks> bool offsetExists(PhpValue offset); }
25.46875
81
0.660123
[ "Apache-2.0" ]
JiaFeiX/peachpie
src/Peachpie.Runtime/std/ArrayAccess.cs
817
C#
using UnityEngine; public class DaylightChange : MonoBehaviour { private void OnSelectionChange() { if (GetComponent<UIPopupList>().selection == "DAY") { IN_GAME_MAIN_CAMERA.dayLight = DayLight.Day; } if (GetComponent<UIPopupList>().selection == "DAWN") { IN_GAME_MAIN_CAMERA.dayLight = DayLight.Dawn; } if (GetComponent<UIPopupList>().selection == "NIGHT") { IN_GAME_MAIN_CAMERA.dayLight = DayLight.Night; } } }
24.363636
61
0.583955
[ "MIT" ]
Jagerente/GucciGangMod
Source/DaylightChange.cs
538
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Model; [assembly: LoadableClass(GroupTransform.Summary, typeof(GroupTransform), typeof(GroupTransform.Arguments), typeof(SignatureDataTransform), GroupTransform.UserName, GroupTransform.ShortName)] [assembly: LoadableClass(GroupTransform.Summary, typeof(GroupTransform), null, typeof(SignatureLoadDataTransform), GroupTransform.UserName, GroupTransform.LoaderSignature)] [assembly: EntryPointModule(typeof(GroupingOperations))] namespace Microsoft.ML.Runtime.Data { /// <summary> /// This transform essentially performs the following SQL-like operation: /// SELECT GroupKey1, GroupKey2, ... GroupKeyK, LIST(Value1), LIST(Value2), ... LIST(ValueN) /// FROM Data /// GROUP BY GroupKey1, GroupKey2, ... GroupKeyK. /// /// It assumes that the group keys are contiguous (if a new group key sequence is encountered, the group is over). /// The GroupKeyN and ValueN columns can be of any primitive types. The code requires that every raw type T of the group key column /// is an <see cref="IEquatable{T}"/>, which is currently true for all existing primitive types. /// The produced ValueN columns will be variable-length vectors of the original value column types. /// /// The order of ValueN entries in the lists is preserved. /// /// Example: /// User Item /// Pete Book /// Tom Table /// Tom Kitten /// Pete Chair /// Pete Cup /// /// Result: /// User Item /// Pete [Book] /// Tom [Table, Kitten] /// Pete [Chair, Cup] /// </summary> public sealed class GroupTransform : TransformBase { public const string Summary = "Groups values of a scalar column into a vector, by a contiguous group ID"; public const string UserName = "Group Transform"; public const string ShortName = "Group"; private const string RegistrationName = "GroupTransform"; public const string LoaderSignature = "GroupTransform"; private static VersionInfo GetVersionInfo() { return new VersionInfo( modelSignature: "GRP TRNS", verWrittenCur: 0x00010001, // Initial verReadableCur: 0x00010001, verWeCanReadBack: 0x00010001, loaderSignature: LoaderSignature); } // REVIEW: maybe we want to have an option to keep all non-group scalar columns, as opposed to // explicitly listing the ones to keep. // REVIEW: group keys and keep columns can possibly be vectors, not implemented now. // REVIEW: it might be feasible to have columns that are constant throughout a group, without having to list them // as group keys. public sealed class Arguments : TransformInputBase { [Argument(ArgumentType.Multiple, HelpText = "Columns to group by", ShortName = "g", SortOrder = 1, Purpose = SpecialPurpose.ColumnSelector)] public string[] GroupKey; // The column names remain the same, there's no option to rename the column. [Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "Columns to group together", ShortName = "col", SortOrder = 2)] public string[] Column; } private readonly GroupSchema _schema; /// <summary> /// Convenience constructor for public facing API. /// </summary> /// <param name="env">Host Environment.</param> /// <param name="input">Input <see cref="IDataView"/>. This is the output from previous transform or loader.</param> /// <param name="groupKey">Columns to group by</param> /// <param name="columns">Columns to group together</param> public GroupTransform(IHostEnvironment env, IDataView input, string groupKey, params string[] columns) : this(env, new Arguments() { GroupKey = new[] { groupKey }, Column = columns }, input) { } public GroupTransform(IHostEnvironment env, Arguments args, IDataView input) : base(env, RegistrationName, input) { Host.CheckValue(args, nameof(args)); Host.CheckUserArg(Utils.Size(args.GroupKey) > 0, nameof(args.GroupKey), "There must be at least one group key"); _schema = new GroupSchema(Host, Source.Schema, args.GroupKey, args.Column ?? new string[0]); } public static GroupTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(GetVersionInfo()); env.CheckValue(input, nameof(input)); var h = env.Register(RegistrationName); return h.Apply("Loading Model", ch => new GroupTransform(h, ctx, input)); } private GroupTransform(IHost host, ModelLoadContext ctx, IDataView input) : base(host, input) { Host.AssertValue(ctx); // *** Binary format *** // (schema) _schema = new GroupSchema(input.Schema, host, ctx); } public override void Save(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); ctx.SetVersionInfo(GetVersionInfo()); // *** Binary format *** // (schema) _schema.Save(ctx); } public override long? GetRowCount(bool lazy = true) { // We have no idea how many total rows we'll have. return null; } public override ISchema Schema { get { return _schema; } } protected override IRowCursor GetRowCursorCore(Func<int, bool> predicate, IRandom rand = null) { Host.CheckValue(predicate, nameof(predicate)); Host.CheckValueOrNull(rand); return new Cursor(this, predicate); } protected override bool? ShouldUseParallelCursors(Func<int, bool> predicate) { // There's no way to parallelize the processing: we can't ensure every group belongs to one batch. Host.AssertValue(predicate); return false; } public override bool CanShuffle { get { return false; } } public override IRowCursor[] GetRowCursorSet(out IRowCursorConsolidator consolidator, Func<int, bool> predicate, int n, IRandom rand = null) { Host.CheckValue(predicate, nameof(predicate)); Host.CheckValueOrNull(rand); consolidator = null; return new IRowCursor[] { GetRowCursorCore(predicate) }; } /// <summary> /// For group columns, the schema information is intact. /// /// For keep columns, the type is Vector of original type and variable length. /// The only metadata preserved is the KeyNames and IsNormalized. /// /// All other columns are dropped. /// </summary> private sealed class GroupSchema : ISchema { private static readonly string[] _preservedMetadata = new[] { MetadataUtils.Kinds.IsNormalized, MetadataUtils.Kinds.KeyValues }; private readonly IExceptionContext _ectx; private readonly ISchema _input; private readonly string[] _groupColumns; private readonly string[] _keepColumns; public readonly int[] GroupIds; public readonly int[] KeepIds; private readonly int _groupCount; private readonly ColumnType[] _columnTypes; private readonly Dictionary<string, int> _columnNameMap; public GroupSchema(IExceptionContext ectx, ISchema inputSchema, string[] groupColumns, string[] keepColumns) { Contracts.AssertValue(ectx); _ectx = ectx; _ectx.AssertValue(inputSchema); _ectx.AssertNonEmpty(groupColumns); _ectx.AssertValue(keepColumns); _input = inputSchema; _groupColumns = groupColumns; GroupIds = GetColumnIds(inputSchema, groupColumns, x => _ectx.ExceptUserArg(nameof(Arguments.GroupKey), x)); _groupCount = GroupIds.Length; _keepColumns = keepColumns; KeepIds = GetColumnIds(inputSchema, keepColumns, x => _ectx.ExceptUserArg(nameof(Arguments.Column), x)); _columnTypes = BuildColumnTypes(_input, KeepIds); _columnNameMap = BuildColumnNameMap(); } public GroupSchema(ISchema inputSchema, IHostEnvironment env, ModelLoadContext ctx) { Contracts.AssertValue(env); _ectx = env.Register(LoaderSignature); _ectx.AssertValue(inputSchema); _ectx.AssertValue(ctx); // *** Binary format *** // int: G - number of group columns // int[G]: ids of group column names // int: K: number of keep columns // int[K]: ids of keep column names _input = inputSchema; int g = ctx.Reader.ReadInt32(); _ectx.CheckDecode(g > 0); _groupColumns = new string[g]; for (int i = 0; i < g; i++) _groupColumns[i] = ctx.LoadNonEmptyString(); int k = ctx.Reader.ReadInt32(); _ectx.CheckDecode(k >= 0); _keepColumns = new string[k]; for (int i = 0; i < k; i++) _keepColumns[i] = ctx.LoadNonEmptyString(); GroupIds = GetColumnIds(inputSchema, _groupColumns, _ectx.Except); _groupCount = GroupIds.Length; KeepIds = GetColumnIds(inputSchema, _keepColumns, _ectx.Except); _columnTypes = BuildColumnTypes(_input, KeepIds); _columnNameMap = BuildColumnNameMap(); } private Dictionary<string, int> BuildColumnNameMap() { var map = new Dictionary<string, int>(); for (int i = 0; i < _groupCount; i++) map[_groupColumns[i]] = i; for (int i = 0; i < _keepColumns.Length; i++) map[_keepColumns[i]] = i + _groupCount; return map; } private static ColumnType[] BuildColumnTypes(ISchema input, int[] ids) { var types = new ColumnType[ids.Length]; for (int i = 0; i < ids.Length; i++) { var srcType = input.GetColumnType(ids[i]); Contracts.Assert(srcType.IsPrimitive); types[i] = new VectorType(srcType.AsPrimitive, size: 0); } return types; } public void Save(ModelSaveContext ctx) { _ectx.AssertValue(ctx); // *** Binary format *** // int: G - number of group columns // int[G]: ids of group column names // int: K: number of keep columns // int[K]: ids of keep column names _ectx.AssertNonEmpty(_groupColumns); ctx.Writer.Write(_groupColumns.Length); foreach (var name in _groupColumns) { _ectx.AssertNonEmpty(name); ctx.SaveString(name); } _ectx.AssertValue(_keepColumns); ctx.Writer.Write(_keepColumns.Length); foreach (var name in _keepColumns) { _ectx.AssertNonEmpty(name); ctx.SaveString(name); } } private int[] GetColumnIds(ISchema schema, string[] names, Func<string, Exception> except) { Contracts.AssertValue(schema); Contracts.AssertValue(names); var ids = new int[names.Length]; for (int i = 0; i < names.Length; i++) { int col; if (!schema.TryGetColumnIndex(names[i], out col)) throw except(string.Format("Could not find column '{0}'", names[i])); var colType = schema.GetColumnType(col); if (!colType.IsPrimitive) throw except(string.Format("Column '{0}' has type '{1}', but must have a primitive type", names[i], colType)); ids[i] = col; } return ids; } public int ColumnCount { get { return _groupCount + KeepIds.Length; } } public void CheckColumnInRange(int col) { _ectx.Check(0 <= col && col < _groupCount + KeepIds.Length); } public bool TryGetColumnIndex(string name, out int col) { return _columnNameMap.TryGetValue(name, out col); } public string GetColumnName(int col) { CheckColumnInRange(col); if (col < _groupCount) return _groupColumns[col]; return _keepColumns[col - _groupCount]; } public ColumnType GetColumnType(int col) { CheckColumnInRange(col); if (col < _groupCount) return _input.GetColumnType(GroupIds[col]); return _columnTypes[col - _groupCount]; } public IEnumerable<KeyValuePair<string, ColumnType>> GetMetadataTypes(int col) { CheckColumnInRange(col); if (col < _groupCount) return _input.GetMetadataTypes(GroupIds[col]); col -= _groupCount; var result = new List<KeyValuePair<string, ColumnType>>(); foreach (var kind in _preservedMetadata) { var colType = _input.GetMetadataTypeOrNull(kind, KeepIds[col]); if (colType != null) result.Add(colType.GetPair(kind)); } return result; } public ColumnType GetMetadataTypeOrNull(string kind, int col) { CheckColumnInRange(col); if (col < _groupCount) return _input.GetMetadataTypeOrNull(kind, GroupIds[col]); col -= _groupCount; if (_preservedMetadata.Contains(kind)) return _input.GetMetadataTypeOrNull(kind, KeepIds[col]); return null; } public void GetMetadata<TValue>(string kind, int col, ref TValue value) { CheckColumnInRange(col); if (col < _groupCount) { _input.GetMetadata(kind, GroupIds[col], ref value); return; } col -= _groupCount; if (_preservedMetadata.Contains(kind)) { _input.GetMetadata(kind, KeepIds[col], ref value); return; } throw _ectx.ExceptGetMetadata(); } } /// <summary> /// This cursor will create two cursors on the input data view: /// - The leading cursor will activate all the group columns, and will advance until it hits the end of the contiguous group. /// - The trailing cursor will activate all the requested columns, and will go through the group /// (as identified by the leading cursor), and aggregate the keep columns. /// /// The getters are as follows: /// - The group column getters are taken directly from the trailing cursor. /// - The keep column getters are provided by the aggregators. /// </summary> public sealed class Cursor : RootCursorBase, IRowCursor { /// <summary> /// This class keeps track of the previous group key and tests the current group key against the previous one. /// </summary> private sealed class GroupKeyColumnChecker { public readonly Func<bool> IsSameKey; private static Func<bool> MakeSameChecker<T>(IRow row, int col) where T : IEquatable<T> { T oldValue = default(T); T newValue = default(T); bool first = true; ValueGetter<T> getter = row.GetGetter<T>(col); return () => { getter(ref newValue); bool result = first || oldValue.Equals(newValue); oldValue = newValue; first = false; return result; }; } public GroupKeyColumnChecker(IRow row, int col) { Contracts.AssertValue(row); var type = row.Schema.GetColumnType(col); Func<IRow, int, Func<bool>> del = MakeSameChecker<int>; var mi = del.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(type.RawType); IsSameKey = (Func<bool>)mi.Invoke(null, new object[] { row, col }); } } // REVIEW: potentially, there could be other aggregators. // REVIEW: Currently, it always produces dense buffers. The anticipated use cases don't include many // default values at the moment. /// <summary> /// This class handles the aggregation of one 'keep' column into a vector. It wraps around an <see cref="IRow"/>'s /// column, reads the data and aggregates. /// </summary> private abstract class KeepColumnAggregator { public abstract ValueGetter<T> GetGetter<T>(IExceptionContext ctx); public abstract void SetSize(int size); public abstract void ReadValue(int position); public static KeepColumnAggregator Create(IRow row, int col) { Contracts.AssertValue(row); var colType = row.Schema.GetColumnType(col); Contracts.Assert(colType.IsPrimitive); var type = typeof(ListAggregator<>); var cons = type.MakeGenericType(colType.RawType).GetConstructor(new[] { typeof(IRow), typeof(int) }); return cons.Invoke(new object[] { row, col }) as KeepColumnAggregator; } private sealed class ListAggregator<TValue> : KeepColumnAggregator { private readonly ValueGetter<TValue> _srcGetter; private readonly Delegate _getter; private TValue[] _buffer; private int _size; public ListAggregator(IRow row, int col) { Contracts.AssertValue(row); _srcGetter = row.GetGetter<TValue>(col); _getter = (ValueGetter<VBuffer<TValue>>)Getter; } private void Getter(ref VBuffer<TValue> dst) { var values = (Utils.Size(dst.Values) < _size) ? new TValue[_size] : dst.Values; Array.Copy(_buffer, values, _size); dst = new VBuffer<TValue>(_size, values, dst.Indices); } public override ValueGetter<T> GetGetter<T>(IExceptionContext ctx) { ctx.Check(typeof(T) == typeof(VBuffer<TValue>)); return (ValueGetter<T>)_getter; } public override void SetSize(int size) { Array.Resize(ref _buffer, size); _size = size; } public override void ReadValue(int position) { Contracts.Assert(0 <= position && position < _size); _srcGetter(ref _buffer[position]); } } } private readonly GroupTransform _parent; private readonly bool[] _active; private readonly int _groupCount; private readonly IRowCursor _leadingCursor; private readonly IRowCursor _trailingCursor; private readonly GroupKeyColumnChecker[] _groupCheckers; private readonly KeepColumnAggregator[] _aggregators; public override long Batch { get { return 0; } } public ISchema Schema { get { return _parent.Schema; } } public Cursor(GroupTransform parent, Func<int, bool> predicate) : base(parent.Host) { Ch.AssertValue(predicate); _parent = parent; var schema = _parent._schema; _active = Utils.BuildArray(schema.ColumnCount, predicate); _groupCount = schema.GroupIds.Length; bool[] srcActiveLeading = new bool[_parent.Source.Schema.ColumnCount]; foreach (var col in schema.GroupIds) srcActiveLeading[col] = true; _leadingCursor = parent.Source.GetRowCursor(x => srcActiveLeading[x]); bool[] srcActiveTrailing = new bool[_parent.Source.Schema.ColumnCount]; for (int i = 0; i < _groupCount; i++) { if (_active[i]) srcActiveTrailing[schema.GroupIds[i]] = true; } for (int i = 0; i < schema.KeepIds.Length; i++) { if (_active[i + _groupCount]) srcActiveTrailing[schema.KeepIds[i]] = true; } _trailingCursor = parent.Source.GetRowCursor(x => srcActiveTrailing[x]); _groupCheckers = new GroupKeyColumnChecker[_groupCount]; for (int i = 0; i < _groupCount; i++) _groupCheckers[i] = new GroupKeyColumnChecker(_leadingCursor, _parent._schema.GroupIds[i]); _aggregators = new KeepColumnAggregator[_parent._schema.KeepIds.Length]; for (int i = 0; i < _aggregators.Length; i++) { if (_active[i + _groupCount]) _aggregators[i] = KeepColumnAggregator.Create(_trailingCursor, _parent._schema.KeepIds[i]); } } public override ValueGetter<UInt128> GetIdGetter() { return _trailingCursor.GetIdGetter(); } public bool IsColumnActive(int col) { _parent._schema.CheckColumnInRange(col); return _active[col]; } protected override bool MoveNextCore() { // If leading cursor is not started, start it. if (_leadingCursor.State == CursorState.NotStarted) { _leadingCursor.MoveNext(); } if (_leadingCursor.State == CursorState.Done) { // Leading cursor reached the end of the input on the previous MoveNext. return false; } // Then, advance the leading cursor until it hits the end of the group (or the end of the data). int groupSize = 0; while (_leadingCursor.State == CursorState.Good && IsSameGroup()) { groupSize++; _leadingCursor.MoveNext(); } // The group can only be empty if the leading cursor immediately reaches the end of the data. // This is handled by the check above. Ch.Assert(groupSize > 0); // Catch up with the trailing cursor and populate all the aggregates. // REVIEW: this could be done lazily, but still all aggregators together. foreach (var agg in _aggregators.Where(x => x != null)) agg.SetSize(groupSize); for (int i = 0; i < groupSize; i++) { var res = _trailingCursor.MoveNext(); Ch.Assert(res); foreach (var agg in _aggregators.Where(x => x != null)) agg.ReadValue(i); } return true; } private bool IsSameGroup() { bool result = true; foreach (var checker in _groupCheckers) { // Even if the result is false, we need to call every checker so that they can memorize // the current key value. result = checker.IsSameKey() & result; } return result; } public override void Dispose() { _leadingCursor.Dispose(); _trailingCursor.Dispose(); base.Dispose(); } public ValueGetter<TValue> GetGetter<TValue>(int col) { _parent._schema.CheckColumnInRange(col); if (!_active[col]) throw Ch.ExceptParam(nameof(col), "Column #{0} is not active", col); if (col < _groupCount) return _trailingCursor.GetGetter<TValue>(_parent._schema.GroupIds[col]); Ch.AssertValue(_aggregators[col - _groupCount]); return _aggregators[col - _groupCount].GetGetter<TValue>(Ch); } } } public static partial class GroupingOperations { [TlcModule.EntryPoint(Name = "Transforms.CombinerByContiguousGroupId", Desc = GroupTransform.Summary, UserName = GroupTransform.UserName, ShortName = GroupTransform.ShortName, XmlInclude = new[] { @"<include file='../Microsoft.ML.Transforms/doc.xml' path='doc/members/member[@name=""Group""]/*' />" })] public static CommonOutputs.TransformOutput Group(IHostEnvironment env, GroupTransform.Arguments input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(input, nameof(input)); var h = EntryPointUtils.CheckArgsAndCreateHost(env, "GroupTransform", input); var view = new GroupTransform(h, input, input.Data); return new CommonOutputs.TransformOutput() { Model = new TransformModel(h, view, input.Data), OutputData = view }; } } }
40.515284
148
0.542466
[ "MIT" ]
SolyarA/machinelearning
src/Microsoft.ML.Transforms/GroupTransform.cs
27,834
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; //무난하게 사용할 공통 팝업. 가장 많이 쓰는 유형인 1버튼 (확인), 2버튼(확인/취소) 팝업을 생성 namespace Kupa { public class CommonPopup : MonoBehaviourUI { [SerializeField] private TMP_Text titleText; [SerializeField] private TMP_Text descriptionText; [SerializeField] private Button okBtn; [SerializeField] private Button cancelBtn; private bool is1Btn; private bool isEnableEscape; public void Set2BtnPopup(string title, string description, string okText, string cancelText, UnityAction okListener, UnityAction cancelListener, bool isEnableEscape = true) { titleText.text = title; descriptionText.text = description; okBtn.GetComponentInChildren<TMP_Text>().text = okText; cancelBtn.GetComponentInChildren<TMP_Text>().text = cancelText; okBtn.onClick.AddListener(okListener); cancelBtn.onClick.AddListener(cancelListener); is1Btn = false; this.isEnableEscape = isEnableEscape; } public void Set2BtnPopup(string title, string description, UnityAction okListener, UnityAction cancelListener, bool isEnableEscape = true) { titleText.text = title; descriptionText.text = description; okBtn.onClick.AddListener(okListener); cancelBtn.onClick.AddListener(cancelListener); is1Btn = false; this.isEnableEscape = isEnableEscape; } public void Set1BtnPopup(string title, string description, string okText, UnityAction okListener, bool isEnableEscape = true) { titleText.text = title; descriptionText.text = description; cancelBtn.gameObject.SetActive(false); okBtn.GetComponentInChildren<TMP_Text>().text = okText; okBtn.onClick.AddListener(okListener); is1Btn = true; this.isEnableEscape = isEnableEscape; } public void Set1BtnPopup(string title, string description, UnityAction okListener, bool isEnableEscape = true) { titleText.text = title; descriptionText.text = description; cancelBtn.gameObject.SetActive(false); okBtn.onClick.AddListener(okListener); is1Btn = true; this.isEnableEscape = isEnableEscape; } protected override void Close() //일부 팝업은 꼭 버튼을 눌러야만 넘어갈 수 있도록 조건부로 Escape 버튼을 무시하도록 한다. { if (isEnableEscape) { if (is1Btn) DestroyPopup(); else cancelBtn.onClick.Invoke(); } } public void DestroyPopup() { Destroy(gameObject); } } }
36.730769
180
0.631763
[ "MIT" ]
jab724/Kupa3DRPG
Kupa3DRPG_SRC/Assets/01. Scripts/UI/CommonPopup.cs
3,005
C#