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 FluentNHibernate.Mapping; namespace ItWebSite.Core.DbModel.Mappings { public class WebContentMapping : ClassMap<WebContent> { public WebContentMapping() { Id(x => x.Id).UniqueKey("Id").GeneratedBy.Identity(); Map(x => x.CreateDate); Map(x => x.Creater); Map(x => x.IsDelete); Map(x => x.LastModifier); Map(x => x.LastModifyDate); Map(x => x.Content).Length(5000); Map(x => x.WebContentTypeId); Map(x => x.DisplayOrder); } } }
26.318182
65
0.528497
[ "Apache-2.0" ]
snbbgyth/ItWebSite
Source/ItWebSite.Core/DbModel/Mappings/WebContentMapping.cs
581
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using DXInfo.Data.Contracts; using GalaSoft.MvvmLight.Messaging; namespace FairiesCoolerCash.Business { /// <summary> /// 消费分类统计 /// </summary> public partial class WRReport4UserControl : UserControl { public WRReport4UserControl() { InitializeComponent(); Messenger.Default.Send(new DataGridMessageToken() { MyDataGrid = this.MemberList }); } } }
24.967742
96
0.724806
[ "Apache-2.0" ]
zhenghua75/DXInfo
FairiesCoolerCash/View/WRReport/WRReport4UserControl.xaml.cs
788
C#
using FluentNHibernate.AspNet.Identity.Entities; using FluentNHibernate.Mapping; namespace FluentNHibernate.AspNet.Identity.Mapping { internal class AspNetUserClaimMap : ClassMap<AspNetUserClaim> { public AspNetUserClaimMap() { Table("`AspNetUserClaim`"); LazyLoad(); Id(i => i.Id).GeneratedBy.Identity().Column("`Id`"); References(i => i.User).Column("`UserId`").Not.Nullable(); Map(i => i.Type).Column("`Type`").Length(4001); Map(i => i.Value).Column("`Value`").Length(4001); } } }
32.888889
70
0.599662
[ "Apache-2.0" ]
xavierjefferson/FluentNHibernateIdentity
FluentNHibernate.AspNet.Identity/Mapping/AspNetUserClaimMap.cs
592
C#
namespace BuildingEconomy.Components { // Transportable storage with additional values for resource containers. internal class ContainerStorage : TransportableStorage { /// <summary> /// How many total items can the stored, including items in containers. /// </summary> /// <remarks> /// A value of 0 means unlimited. /// </remarks> public uint TotalCapacity; } }
31.714286
83
0.614865
[ "MIT" ]
Beliaar/BuildingEconomy
BuildingEconomy/BuildingEconomy.Game/Components/ContainerStorage.cs
446
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Compiler.Framework.Transform.Auto.ConstantMove { /// <summary> /// Xor64 /// </summary> public sealed class Xor64 : BaseTransformation { public Xor64() : base(IRInstruction.Xor64) { } public override bool Match(Context context, TransformContext transformContext) { if (!IsResolvedConstant(context.Operand1)) return false; if (IsResolvedConstant(context.Operand2)) return false; return true; } public override void Transform(Context context, TransformContext transformContext) { var result = context.Result; var t1 = context.Operand1; var t2 = context.Operand2; context.SetInstruction(IRInstruction.Xor64, result, t2, t1); } } }
21.4
84
0.723131
[ "BSD-3-Clause" ]
AnErrupTion/MOSA-Project
Source/Mosa.Compiler.Framework/Transform/Auto/ConstantMove/Xor64.cs
856
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpDX; using SharpDX.Windows; using SharpDX.DXGI; using SharpDX.Direct3D11; using Common; // Resolve class name conflicts by explicitly stating // which class they refer to: using Buffer = SharpDX.Direct3D11.Buffer; namespace Direct3D11_RenderingCubeTexture { public class SphereRenderer : Common.RendererBase { Buffer vertexBuffer; Buffer indexBuffer; VertexBufferBinding vertexBinding; ShaderResourceView textureView; SamplerState samplerState; int totalVertexCount = 0; protected override void CreateDeviceDependentResources() { RemoveAndDispose(ref vertexBuffer); RemoveAndDispose(ref indexBuffer); // Retrieve our SharpDX.Direct3D11.Device1 instance var device = this.DeviceManager.Direct3DDevice; // Load texture (a DDS cube map) textureView = TextureLoader.ShaderResourceViewFromFile(device, "CubeMap.dds"); // Create our sampler state samplerState = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, BorderColor = new Color4(0, 0, 0, 0), ComparisonFunction = Comparison.Never, Filter = Filter.MinMagMipLinear, MaximumLod = 9, // Our cube map has 10 mip map levels (0-9) MinimumLod = 0, MipLodBias = 0.0f }); Vertex[] vertices; int[] indices; GeometricPrimitives.GenerateSphere(out vertices, out indices, Color.Gray); vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices)); vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0); indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, indices)); totalVertexCount = indices.Length; } protected override void DoRender() { var context = this.DeviceManager.Direct3DContext; context.PixelShader.SetShaderResource(0, textureView); context.PixelShader.SetSampler(0, samplerState); // Tell the IA we are using triangles context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; // Set the index buffer context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); // Pass in the quad vertices (note: only 4 vertices) context.InputAssembler.SetVertexBuffers(0, vertexBinding); // Draw the 36 vertices that make up the two triangles in the quad // using the vertex indices context.DrawIndexed(totalVertexCount, 0, 0); // Note: we have called DrawIndexed so that the index buffer will be used } } }
34.822222
103
0.644544
[ "BSD-2-Clause" ]
THISISAGOODNAME/DXBasic
D3DBasic/Direct3D11_RenderingCubeTexture/SphereRenderer.cs
3,136
C#
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KML2SQL { public static class Utility { public static string GetApplicationFolder() { var path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ConfigurationManager.AppSettings["AppFolder"] ); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } public static string GetDefaultScriptSaveLoc() { var path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Kml2Sql.sql" ); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } }
25.575
85
0.560117
[ "BSD-2-Clause" ]
JCVasquez2019/KML2SQL
src/KML2SQL/Utility.cs
1,025
C#
using System.Collections.Generic; namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public partial class OTA_ResRetrieveRSReservationsList { private List<object> _items; public OTA_ResRetrieveRSReservationsList() { this._items = new List<object>(); } [System.Xml.Serialization.XmlElementAttribute("AirReservation", typeof(OTA_ResRetrieveRSReservationsListAirReservation))] [System.Xml.Serialization.XmlElementAttribute("CruiseReservation", typeof(CruiseReservationType))] [System.Xml.Serialization.XmlElementAttribute("GlobalReservation", typeof(OTA_ResRetrieveRSReservationsListGlobalReservation))] [System.Xml.Serialization.XmlElementAttribute("GolfReservation", typeof(OTA_ResRetrieveRSReservationsListGolfReservation))] [System.Xml.Serialization.XmlElementAttribute("HotelReservation", typeof(HotelReservationType))] [System.Xml.Serialization.XmlElementAttribute("PackageReservation", typeof(OTA_ResRetrieveRSReservationsListPackageReservation))] [System.Xml.Serialization.XmlElementAttribute("RailReservation", typeof(RailReservationSummaryType))] [System.Xml.Serialization.XmlElementAttribute("VehicleReservation", typeof(OTA_ResRetrieveRSReservationsListVehicleReservation))] public List<object> Items { get { return this._items; } set { this._items = value; } } } }
46.925
137
0.711241
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/OTA_ResRetrieveRSReservationsList.cs
1,877
C#
namespace KafkaBus.Common { public class MessageContext { public KafkaMessagePacket Request { get; set; } public string ReplyToQueue { get; set; } public string CorrelationId { get; set; } /// <summary> /// Broker specific message item. /// </summary> public object Dispatch { get; set; } } }
22.75
55
0.57967
[ "MIT" ]
yang-xiaodong/kafkabus-net
KafkaBus/Common/MessageContext.cs
366
C#
using System; using System.Collections.Generic; using Lyra.Core.Blocks; using Lyra.Core.Blocks.Transactions; using Lyra.Core.Cryptography; using Lyra.Core.API; using Lyra.Core.Accounts.Node; using Lyra.Node2.Services; using Lyra.Core.Protos; namespace Lyra.Node2.Authorizers { public class ReceiveTransferAuthorizer: BaseAuthorizer { public ReceiveTransferAuthorizer(ServiceAccount serviceAccount, IAccountCollection accountCollection): base (serviceAccount, accountCollection) { } public override APIResultCodes Authorize<T>(ref T tblock) { if (!(tblock is ReceiveTransferBlock)) return APIResultCodes.InvalidBlockType; var block = tblock as ReceiveTransferBlock; // 1. check if the account already exists if (!_accountCollection.AccountExists(block.AccountID)) return APIResultCodes.AccountDoesNotExist; TransactionBlock lastBlock = _accountCollection.FindLatestBlock(block.AccountID); if (lastBlock == null) return APIResultCodes.CouldNotFindLatestBlock; var result = VerifyBlock(block, lastBlock); if (result != APIResultCodes.Success) return result; result = VerifyTransactionBlock(block); if (result != APIResultCodes.Success) return result; if (!block.ValidateTransaction(lastBlock)) return APIResultCodes.ReceiveTransactionValidationFailed; result = ValidateReceiveTransAmount(block, block.GetTransaction(lastBlock)); if (result != APIResultCodes.Success) return result; result = ValidateNonFungible(block, lastBlock); if (result != APIResultCodes.Success) return result; // Check duplicate receives (kind of double spending up down) var duplicate_block = _accountCollection.FindBlockBySourceHash(block.SourceHash); if (duplicate_block != null) return APIResultCodes.DuplicateReceiveBlock; Sign(ref block); _accountCollection.AddBlock(block); return base.Authorize(ref tblock); } protected override APIResultCodes ValidateFee(TransactionBlock block) { if (block.FeeType != AuthorizationFeeTypes.NoFee) return APIResultCodes.InvalidFeeAmount; if (block.Fee != 0) return APIResultCodes.InvalidFeeAmount; return APIResultCodes.Success; } protected APIResultCodes ValidateReceiveTransAmount(ReceiveTransferBlock block, TransactionInfo receiveTransaction) { //find the corresponding send block and validate the added transaction amount var sourceBlock = _accountCollection.FindBlockByHash(block.SourceHash); if (sourceBlock == null) return APIResultCodes.SourceSendBlockNotFound; // find the actual amount of transaction TransactionBlock prevToSendBlock = _accountCollection.FindBlockByHash(sourceBlock.PreviousHash); if (prevToSendBlock == null) return APIResultCodes.CouldNotTraceSendBlockChain; TransactionInfo sendTransaction; if (block.BlockType == BlockTypes.ReceiveTransfer || block.BlockType == BlockTypes.OpenAccountWithReceiveTransfer) { if ((sourceBlock as SendTransferBlock).DestinationAccountId != block.AccountID) return APIResultCodes.InvalidDestinationAccountId; sendTransaction = sourceBlock.GetTransaction(prevToSendBlock); if (!sourceBlock.ValidateTransaction(prevToSendBlock)) return APIResultCodes.SendTransactionValidationFailed; //originallySentAmount = sendTransaction.Amount; //originallySentAmount = // prevToSendBlock.Balances[LyraGlobal.LYRA_TICKER_CODE] - sourceBlock.Balances[LyraGlobal.LYRA_TICKER_CODE] - (sourceBlock as IFeebleBlock).Fee; } else if (block.BlockType == BlockTypes.ReceiveFee || block.BlockType == BlockTypes.OpenAccountWithReceiveFee) { sendTransaction = new TransactionInfo() { TokenCode = LyraGlobal.LYRA_TICKER_CODE, Amount = sourceBlock.Fee }; } else return APIResultCodes.InvalidBlockType; if (sendTransaction.Amount != receiveTransaction.Amount) return APIResultCodes.TransactionAmountDoesNotMatch; if (sendTransaction.TokenCode != receiveTransaction.TokenCode) return APIResultCodes.TransactionTokenDoesNotMatch; return APIResultCodes.Success; } protected override APIResultCodes ValidateNonFungible(TransactionBlock send_or_receice_block, TransactionBlock previousBlock) { var result = base.ValidateNonFungible(send_or_receice_block, previousBlock); if (result != APIResultCodes.Success) return result; if (send_or_receice_block.NonFungibleToken == null) return APIResultCodes.Success; var originBlock = _accountCollection.FindBlockByHash((send_or_receice_block as ReceiveTransferBlock).SourceHash); if (originBlock == null) return APIResultCodes.OriginNonFungibleBlockNotFound; if (!originBlock.ContainsNonFungibleToken()) return APIResultCodes.OriginNonFungibleBlockNotFound; if (originBlock.NonFungibleToken.Hash != send_or_receice_block.NonFungibleToken.Hash) return APIResultCodes.OriginNonFungibleBlockHashDoesNotMatch; return APIResultCodes.Success; } } }
39.510067
164
0.661457
[ "MIT" ]
LYRA-Block-Lattice/Lyra-Core
Core/Lyra.Node2/Authorizers/ReceiveTransferAuthorizer.cs
5,889
C#
#if !NET40 using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Dapper { public static partial class SqlMapper { /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<IEnumerable<dynamic>> QueryAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryAsync<dynamic>(cnn, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))); /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<IEnumerable<dynamic>> QueryAsync(this IDbConnection cnn, CommandDefinition command) => QueryAsync<dynamic>(cnn, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QueryFirstAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.First, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QueryFirstOrDefaultAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.FirstOrDefault, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QuerySingleAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.Single, typeof(DapperRow), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <remarks>Note: the row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks> public static Task<dynamic> QuerySingleOrDefaultAsync(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<dynamic>(cnn, Row.SingleOrDefault, typeof(DapperRow), command); /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type of results to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <returns> /// A sequence of data of <typeparamref name="T"/>; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive). /// </returns> public static Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryAsync<T>(cnn, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<T> QueryFirstAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.First, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<T> QueryFirstOrDefaultAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.FirstOrDefault, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type of result to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<T> QuerySingleAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.Single, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<T> QuerySingleOrDefaultAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<T>(cnn, Row.SingleOrDefault, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<dynamic> QueryFirstAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.First, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<dynamic> QueryFirstOrDefaultAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.FirstOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<dynamic> QuerySingleAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.Single, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> public static Task<dynamic> QuerySingleOrDefaultAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryRowAsync<dynamic>(cnn, Row.SingleOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public static Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type == null) throw new ArgumentNullException(nameof(type)); return QueryAsync<object>(cnn, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))); } /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public static Task<object> QueryFirstAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type == null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.First, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); } /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public static Task<object> QueryFirstOrDefaultAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type == null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.FirstOrDefault, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); } /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public static Task<object> QuerySingleAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type == null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.Single, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); } /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="sql">The SQL to execute for the query.</param> /// <param name="param">The parameters to pass, if any.</param> /// <param name="transaction">The transaction to use, if any.</param> /// <param name="commandTimeout">The command timeout (in seconds).</param> /// <param name="commandType">The type of command to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> is <c>null</c>.</exception> public static Task<object> QuerySingleOrDefaultAsync(this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { if (type == null) throw new ArgumentNullException(nameof(type)); return QueryRowAsync<object>(cnn, Row.SingleOrDefault, type, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken))); } /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> /// <returns> /// A sequence of data of <typeparamref name="T"/>; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive). /// </returns> public static Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryAsync<T>(cnn, typeof(T), command); /// <summary> /// Execute a query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryAsync<object>(cnn, type, command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QueryFirstAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.First, type, command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QueryFirstAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.First, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QueryFirstOrDefaultAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.FirstOrDefault, type, command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QueryFirstOrDefaultAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.FirstOrDefault, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QuerySingleAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.Single, type, command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QuerySingleAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.Single, typeof(T), command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="type">The type to return.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<object> QuerySingleOrDefaultAsync(this IDbConnection cnn, Type type, CommandDefinition command) => QueryRowAsync<object>(cnn, Row.SingleOrDefault, type, command); /// <summary> /// Execute a single-row query asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command used to query on this connection.</param> public static Task<T> QuerySingleOrDefaultAsync<T>(this IDbConnection cnn, CommandDefinition command) => QueryRowAsync<T>(cnn, Row.SingleOrDefault, typeof(T), command); private static Task<DbDataReader> ExecuteReaderWithFlagsFallbackAsync(DbCommand cmd, bool wasClosed, CommandBehavior behavior, CancellationToken cancellationToken) { var task = cmd.ExecuteReaderAsync(GetBehavior(wasClosed, behavior), cancellationToken); if (task.Status == TaskStatus.Faulted && Settings.DisableCommandBehaviorOptimizations(behavior, task.Exception.InnerException)) { // we can retry; this time it will have different flags return cmd.ExecuteReaderAsync(GetBehavior(wasClosed, behavior), cancellationToken); } return task; } /// <summary> /// Attempts to open a connection asynchronously, with a better error message for unsupported usages. /// </summary> private static Task TryOpenAsync(this IDbConnection cnn, CancellationToken cancel) { if (cnn is DbConnection dbConn) { return dbConn.OpenAsync(cancel); } else { throw new InvalidOperationException("Async operations require use of a DbConnection or an already-open IDbConnection"); } } /// <summary> /// Attempts setup a <see cref="DbCommand"/> on a <see cref="DbConnection"/>, with a better error message for unsupported usages. /// </summary> private static DbCommand TrySetupAsyncCommand(this CommandDefinition command, IDbConnection cnn, Action<IDbCommand, object> paramReader) { if (command.SetupCommand(cnn, paramReader) is DbCommand dbCommand) { return dbCommand; } else { throw new InvalidOperationException("Async operations require use of a DbConnection or an IDbConnection where .CreateCommand() returns a DbCommand"); } } private static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command) { object param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; var cancel = command.CancellationToken; using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader)) { DbDataReader reader = null; try { if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false); reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, cancel).ConfigureAwait(false); var tuple = info.Deserializer; int hash = GetColumnHash(reader); if (tuple.Func == null || tuple.Hash != hash) { if (reader.FieldCount == 0) return Enumerable.Empty<T>(); tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false)); if (command.AddToCache) SetQueryCache(identity, info); } var func = tuple.Func; if (command.Buffered) { var buffer = new List<T>(); var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType; while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { object val = func(reader); if (val == null || val is T) { buffer.Add((T)val); } else { buffer.Add((T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture)); } } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ } command.OnCompleted(); return buffer; } else { // can't use ReadAsync / cancellation; but this will have to do wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior var deferred = ExecuteReaderSync<T>(reader, func, command.Parameters); reader = null; // to prevent it being disposed before the caller gets to see it return deferred; } } finally { using (reader) { /* dispose if non-null */ } if (wasClosed) cnn.Close(); } } } private static async Task<T> QueryRowAsync<T>(this IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) { object param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; var cancel = command.CancellationToken; using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader)) { DbDataReader reader = null; try { if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false); reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, (row & Row.Single) != 0 ? CommandBehavior.SequentialAccess | CommandBehavior.SingleResult // need to allow multiple rows, to check fail condition : CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow, cancel).ConfigureAwait(false); T result = default(T); if (await reader.ReadAsync(cancel).ConfigureAwait(false) && reader.FieldCount != 0) { var tuple = info.Deserializer; int hash = GetColumnHash(reader); if (tuple.Func == null || tuple.Hash != hash) { tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false)); if (command.AddToCache) SetQueryCache(identity, info); } var func = tuple.Func; object val = func(reader); if (val == null || val is T) { result = (T)val; } else { var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType; result = (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture); } if ((row & Row.Single) != 0 && await reader.ReadAsync(cancel).ConfigureAwait(false)) ThrowMultipleRows(row); while (await reader.ReadAsync(cancel).ConfigureAwait(false)) { /* ignore rows after the first */ } } else if ((row & Row.FirstOrDefault) == 0) // demanding a row, and don't have one { ThrowZeroRows(row); } while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore result sets after the first */ } return result; } finally { using (reader) { /* dispose if non-null */ } if (wasClosed) cnn.Close(); } } } /// <summary> /// Execute a command asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>The number of rows affected.</returns> public static Task<int> ExecuteAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => ExecuteAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))); /// <summary> /// Execute a command asynchronously using .NET 4.5 Task. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute on this connection.</param> /// <returns>The number of rows affected.</returns> public static Task<int> ExecuteAsync(this IDbConnection cnn, CommandDefinition command) { object param = command.Parameters; IEnumerable multiExec = GetMultiExec(param); if (multiExec != null) { return ExecuteMultiImplAsync(cnn, command, multiExec); } else { return ExecuteImplAsync(cnn, command, param); } } private struct AsyncExecState { public readonly DbCommand Command; public readonly Task<int> Task; public AsyncExecState(DbCommand command, Task<int> task) { Command = command; Task = task; } } private static async Task<int> ExecuteMultiImplAsync(IDbConnection cnn, CommandDefinition command, IEnumerable multiExec) { bool isFirst = true; int total = 0; bool wasClosed = cnn.State == ConnectionState.Closed; try { if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); CacheInfo info = null; string masterSql = null; if ((command.Flags & CommandFlags.Pipelined) != 0) { const int MAX_PENDING = 100; var pending = new Queue<AsyncExecState>(MAX_PENDING); DbCommand cmd = null; try { foreach (var obj in multiExec) { if (isFirst) { isFirst = false; cmd = command.TrySetupAsyncCommand(cnn, null); masterSql = cmd.CommandText; var identity = new Identity(command.CommandText, cmd.CommandType, cnn, null, obj.GetType(), null); info = GetCacheInfo(identity, obj, command.AddToCache); } else if (pending.Count >= MAX_PENDING) { var recycled = pending.Dequeue(); total += await recycled.Task.ConfigureAwait(false); cmd = recycled.Command; cmd.CommandText = masterSql; // because we do magic replaces on "in" etc cmd.Parameters.Clear(); // current code is Add-tastic } else { cmd = command.TrySetupAsyncCommand(cnn, null); } info.ParamReader(cmd, obj); var task = cmd.ExecuteNonQueryAsync(command.CancellationToken); pending.Enqueue(new AsyncExecState(cmd, task)); cmd = null; // note the using in the finally: this avoids a double-dispose } while (pending.Count != 0) { var pair = pending.Dequeue(); using (pair.Command) { /* dispose commands */ } total += await pair.Task.ConfigureAwait(false); } } finally { // this only has interesting work to do if there are failures using (cmd) { /* dispose commands */ } while (pending.Count != 0) { // dispose tasks even in failure using (pending.Dequeue().Command) { /* dispose commands */ } } } } else { using (var cmd = command.TrySetupAsyncCommand(cnn, null)) { foreach (var obj in multiExec) { if (isFirst) { masterSql = cmd.CommandText; isFirst = false; var identity = new Identity(command.CommandText, cmd.CommandType, cnn, null, obj.GetType(), null); info = GetCacheInfo(identity, obj, command.AddToCache); } else { cmd.CommandText = masterSql; // because we do magic replaces on "in" etc cmd.Parameters.Clear(); // current code is Add-tastic } info.ParamReader(cmd, obj); total += await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false); } } } command.OnCompleted(); } finally { if (wasClosed) cnn.Close(); } return total; } private static async Task<int> ExecuteImplAsync(IDbConnection cnn, CommandDefinition command, object param) { var identity = new Identity(command.CommandText, command.CommandType, cnn, null, param?.GetType(), null); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader)) { try { if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); var result = await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false); command.OnCompleted(); return result; } finally { if (wasClosed) cnn.Close(); } } } /// <summary> /// Perform a asynchronous multi-mapping query with 2 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 2 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, command, map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 3 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 3 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TThird, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, command, map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 4 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 4 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, command, map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 5 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 5 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(cnn, command, map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 6 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TSixth">The sixth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 6 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TSixth">The sixth type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(cnn, command, map, splitOn); /// <summary> /// Perform a asynchronous multi-mapping query with 7 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TSixth">The sixth type in the recordset.</typeparam> /// <typeparam name="TSeventh">The seventh type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn); /// <summary> /// Perform an asynchronous multi-mapping query with 7 input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TFirst">The first type in the recordset.</typeparam> /// <typeparam name="TSecond">The second type in the recordset.</typeparam> /// <typeparam name="TThird">The third type in the recordset.</typeparam> /// <typeparam name="TFourth">The fourth type in the recordset.</typeparam> /// <typeparam name="TFifth">The fifth type in the recordset.</typeparam> /// <typeparam name="TSixth">The sixth type in the recordset.</typeparam> /// <typeparam name="TSeventh">The seventh type in the recordset.</typeparam> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="command">The command to execute.</param> /// <param name="map">The function to map row types to the return type.</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, CommandDefinition command, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, string splitOn = "Id") => MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, command, map, splitOn); private static async Task<IEnumerable<TReturn>> MultiMapAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, CommandDefinition command, Delegate map, string splitOn) { object param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandType, cnn, typeof(TFirst), param?.GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) }); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; try { if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader)) using (var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, command.CancellationToken).ConfigureAwait(false)) { if (!command.Buffered) wasClosed = false; // handing back open reader; rely on command-behavior var results = MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, CommandDefinition.ForCallback(command.Parameters), map, splitOn, reader, identity, true); return command.Buffered ? results.ToList() : results; } } finally { if (wasClosed) cnn.Close(); } } /// <summary> /// Perform a asynchronous multi-mapping query with an arbitrary number of input types. /// This returns a single type, combined from the raw types via <paramref name="map"/>. /// </summary> /// <typeparam name="TReturn">The combined type to return.</typeparam> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="types">Array of types in the recordset.</param> /// <param name="map">The function to map row types to the return type.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="buffered">Whether to buffer the results in memory.</param> /// <param name="splitOn">The field we should split and read the second object from (default: "Id").</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An enumerable of <typeparamref name="TReturn"/>.</returns> public static Task<IEnumerable<TReturn>> QueryAsync<TReturn>(this IDbConnection cnn, string sql, Type[] types, Func<object[], TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { var command = new CommandDefinition(sql, param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)); return MultiMapAsync(cnn, command, types, map, splitOn); } private static async Task<IEnumerable<TReturn>> MultiMapAsync<TReturn>(this IDbConnection cnn, CommandDefinition command, Type[] types, Func<object[], TReturn> map, string splitOn) { if (types.Length < 1) { throw new ArgumentException("you must provide at least one type to deserialize"); } object param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandType, cnn, types[0], param?.GetType(), types); var info = GetCacheInfo(identity, param, command.AddToCache); bool wasClosed = cnn.State == ConnectionState.Closed; try { if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader)) using (var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, command.CancellationToken).ConfigureAwait(false)) { var results = MultiMapImpl(null, default(CommandDefinition), types, map, splitOn, reader, identity, true); return command.Buffered ? results.ToList() : results; } } finally { if (wasClosed) cnn.Close(); } } private static IEnumerable<T> ExecuteReaderSync<T>(IDataReader reader, Func<IDataReader, object> func, object parameters) { using (reader) { while (reader.Read()) { yield return (T)func(reader); } while (reader.NextResult()) { /* ignore subsequent result sets */ } (parameters as IParameterCallbacks)?.OnCompleted(); } } /// <summary> /// Execute a command that returns multiple result sets, and access each in turn. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="sql">The SQL to execute for this query.</param> /// <param name="param">The parameters to use for this query.</param> /// <param name="transaction">The transaction to use for this query.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> public static Task<GridReader> QueryMultipleAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => QueryMultipleAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered)); /// <summary> /// Execute a command that returns multiple result sets, and access each in turn. /// </summary> /// <param name="cnn">The connection to query on.</param> /// <param name="command">The command to execute for this query.</param> public static async Task<GridReader> QueryMultipleAsync(this IDbConnection cnn, CommandDefinition command) { object param = command.Parameters; var identity = new Identity(command.CommandText, command.CommandType, cnn, typeof(GridReader), param?.GetType(), null); CacheInfo info = GetCacheInfo(identity, param, command.AddToCache); DbCommand cmd = null; IDataReader reader = null; bool wasClosed = cnn.State == ConnectionState.Closed; try { if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader); reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess, command.CancellationToken).ConfigureAwait(false); var result = new GridReader(cmd, reader, identity, command.Parameters as DynamicParameters, command.AddToCache, command.CancellationToken); wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader // with the CloseConnection flag, so the reader will deal with the connection; we // still need something in the "finally" to ensure that broken SQL still results // in the connection closing itself return result; } catch { if (reader != null) { if (!reader.IsClosed) { try { cmd.Cancel(); } catch { /* don't spoil the existing exception */ } } reader.Dispose(); } cmd?.Dispose(); if (wasClosed) cnn.Close(); throw; } } /// <summary> /// Execute parameterized SQL and return an <see cref="IDataReader"/>. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use for this command.</param> /// <param name="transaction">The transaction to use for this command.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns> /// <remarks> /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/> /// or <see cref="T:DataSet"/>. /// </remarks> /// <example> /// <code> /// <![CDATA[ /// DataTable table = new DataTable("MyTable"); /// using (var reader = ExecuteReader(cnn, sql, param)) /// { /// table.Load(reader); /// } /// ]]> /// </code> /// </example> public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => ExecuteReaderImplAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered), CommandBehavior.Default); /// <summary> /// Execute parameterized SQL and return an <see cref="IDataReader"/>. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute.</param> /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns> /// <remarks> /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/> /// or <see cref="T:DataSet"/>. /// </remarks> public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, CommandDefinition command) => ExecuteReaderImplAsync(cnn, command, CommandBehavior.Default); /// <summary> /// Execute parameterized SQL and return an <see cref="IDataReader"/>. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute.</param> /// <param name="commandBehavior">The <see cref="CommandBehavior"/> flags for this reader.</param> /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns> /// <remarks> /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/> /// or <see cref="T:DataSet"/>. /// </remarks> public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, CommandDefinition command, CommandBehavior commandBehavior) => ExecuteReaderImplAsync(cnn, command, commandBehavior); private static async Task<IDataReader> ExecuteReaderImplAsync(IDbConnection cnn, CommandDefinition command, CommandBehavior commandBehavior) { Action<IDbCommand, object> paramReader = GetParameterReader(cnn, ref command); DbCommand cmd = null; bool wasClosed = cnn.State == ConnectionState.Closed; try { cmd = command.TrySetupAsyncCommand(cnn, paramReader); if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, commandBehavior, command.CancellationToken).ConfigureAwait(false); wasClosed = false; return reader; } finally { if (wasClosed) cnn.Close(); cmd?.Dispose(); } } /// <summary> /// Execute parameterized SQL that selects a single value. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use for this command.</param> /// <param name="transaction">The transaction to use for this command.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>The first cell returned, as <see cref="object"/>.</returns> public static Task<object> ExecuteScalarAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => ExecuteScalarImplAsync<object>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered)); /// <summary> /// Execute parameterized SQL that selects a single value. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to execute on.</param> /// <param name="sql">The SQL to execute.</param> /// <param name="param">The parameters to use for this command.</param> /// <param name="transaction">The transaction to use for this command.</param> /// <param name="commandTimeout">Number of seconds before command execution timeout.</param> /// <param name="commandType">Is it a stored proc or a batch?</param> /// <returns>The first cell returned, as <typeparamref name="T"/>.</returns> public static Task<T> ExecuteScalarAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) => ExecuteScalarImplAsync<T>(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered)); /// <summary> /// Execute parameterized SQL that selects a single value. /// </summary> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute.</param> /// <returns>The first cell selected as <see cref="object"/>.</returns> public static Task<object> ExecuteScalarAsync(this IDbConnection cnn, CommandDefinition command) => ExecuteScalarImplAsync<object>(cnn, command); /// <summary> /// Execute parameterized SQL that selects a single value /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="cnn">The connection to execute on.</param> /// <param name="command">The command to execute.</param> /// <returns>The first cell selected as <typeparamref name="T"/>.</returns> public static Task<T> ExecuteScalarAsync<T>(this IDbConnection cnn, CommandDefinition command) => ExecuteScalarImplAsync<T>(cnn, command); private static async Task<T> ExecuteScalarImplAsync<T>(IDbConnection cnn, CommandDefinition command) { Action<IDbCommand, object> paramReader = null; object param = command.Parameters; if (param != null) { var identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null); paramReader = GetCacheInfo(identity, command.Parameters, command.AddToCache).ParamReader; } DbCommand cmd = null; bool wasClosed = cnn.State == ConnectionState.Closed; object result; try { cmd = command.TrySetupAsyncCommand(cnn, paramReader); if (wasClosed) await cnn.TryOpenAsync(command.CancellationToken).ConfigureAwait(false); result = await cmd.ExecuteScalarAsync(command.CancellationToken).ConfigureAwait(false); command.OnCompleted(); } finally { if (wasClosed) cnn.Close(); cmd?.Dispose(); } return Parse<T>(result); } } } #endif
66.424513
409
0.609201
[ "Apache-2.0" ]
hd2y/dapper_net40
Dapper/SqlMapper.Async.cs
81,837
C#
using System; using System.Collections.Generic; using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Organizations; using Abp.Runtime.Caching; using iProof.Authorization.Roles; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace iProof.Authorization.Users { public class UserManager : AbpUserManager<Role, User> { public UserManager( RoleManager roleManager, UserStore store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<User> passwordHasher, IEnumerable<IUserValidator<User>> userValidators, IEnumerable<IPasswordValidator<User>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<User>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( roleManager, store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, permissionManager, unitOfWorkManager, cacheManager, organizationUnitRepository, userOrganizationUnitRepository, organizationUnitSettings, settingManager) { } } }
34.966102
84
0.63112
[ "MIT" ]
bquadre/iProof
aspnet-core/src/iProof.Core/Authorization/Users/UserManager.cs
2,065
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; namespace CKAN { public partial class Main { private List<ModChange> changeSet; public void UpdateChangesDialog(List<ModChange> changeset, BackgroundWorker installWorker) { changeSet = changeset; this.installWorker = installWorker; ChangesListView.Items.Clear(); if (changeset == null) { return; } // We're going to split our change-set into two parts: updated/removed mods, // and everything else (which right now is replacing and installing mods, but we may have // other types in the future). changeSet = new List<ModChange>(); changeSet.AddRange(changeset.Where(change => change.ChangeType == GUIModChangeType.Remove)); changeSet.AddRange(changeset.Where(change => change.ChangeType == GUIModChangeType.Update)); IEnumerable<ModChange> leftOver = changeset.Where(change => change.ChangeType != GUIModChangeType.Remove && change.ChangeType != GUIModChangeType.Update); // Now make our list more human-friendly (dependencies for a mod are listed directly // after it.) CreateSortedModList(leftOver); changeset = changeSet; foreach (var change in changeset) { if (change.ChangeType == GUIModChangeType.None) { continue; } CkanModule m = change.Mod; ListViewItem item = new ListViewItem() { Text = m.IsMetapackage ? string.Format(Properties.Resources.MainChangesetMetapackage, m.name, m.version) : Manager.Cache.IsMaybeCachedZip(m) ? string.Format(Properties.Resources.MainChangesetCached, m.name, m.version) : string.Format(Properties.Resources.MainChangesetHostSize, m.name, m.version, m.download.Host ?? "", CkanModule.FmtSize(m.download_size)), Tag = change.Mod }; var sub_change_type = new ListViewItem.ListViewSubItem {Text = change.ChangeType.ToString()}; ListViewItem.ListViewSubItem description = new ListViewItem.ListViewSubItem(); description.Text = change.Reason.Reason.Trim(); if (change.ChangeType == GUIModChangeType.Update) { description.Text = String.Format(Properties.Resources.MainChangesetUpdateSelected, change.Mod.version); } if (change.ChangeType == GUIModChangeType.Install && change.Reason is SelectionReason.UserRequested) { description.Text = Properties.Resources.MainChangesetNewInstall; } item.SubItems.Add(sub_change_type); item.SubItems.Add(description); ChangesListView.Items.Add(item); } } private void ClearChangeSet() { foreach (DataGridViewRow row in mainModList.full_list_of_mod_rows.Values) { GUIMod mod = row.Tag as GUIMod; if (mod.IsInstallChecked != mod.IsInstalled) { mod.SetInstallChecked(row, Installed, mod.IsInstalled); } mod.SetUpgradeChecked(row, UpdateCol, false); mod.SetReplaceChecked(row, ReplaceCol, false); } } /// <summary> /// This method creates the Install part of the changeset /// It arranges the changeset in a human-friendly order /// The requested mod is listed first, it's dependencies right after it /// So we get for example "ModuleRCSFX" directly after "USI Exploration Pack" /// /// It is very likely that this is forward-compatible with new ChangeTypes's, /// like a "reconfigure" changetype, but only the future will tell /// </summary> /// <param name="changes">Every leftover ModChange that should be sorted</param> /// <param name="parent"></param> private void CreateSortedModList(IEnumerable<ModChange> changes, ModChange parent=null) { foreach (ModChange change in changes) { bool goDeeper = parent == null || change.Reason.Parent.identifier == parent.Mod.identifier; if (goDeeper) { if (!changeSet.Any(c => c.Mod.identifier == change.Mod.identifier && c.ChangeType != GUIModChangeType.Remove)) changeSet.Add(change); CreateSortedModList(changes.Where(c => !(c.Reason is SelectionReason.UserRequested)), change); } } } private void CancelChangesButton_Click(object sender, EventArgs e) { ClearChangeSet(); UpdateChangesDialog(null, installWorker); tabController.ShowTab("ManageModsTabPage"); } private void ConfirmChangesButton_Click(object sender, EventArgs e) { if (changeSet == null) return; menuStrip1.Enabled = false; RetryCurrentActionButton.Visible = false; //Using the changeset passed in can cause issues with versions. // An example is Mechjeb for FAR at 25/06/2015 with a 1.0.2 install. // TODO Work out why this is. installWorker.RunWorkerAsync( new KeyValuePair<List<ModChange>, RelationshipResolverOptions>( mainModList.ComputeUserChangeSet(RegistryManager.Instance(Main.Instance.CurrentInstance).registry).ToList(), RelationshipResolver.DependsOnlyOpts() ) ); } } }
40.766667
130
0.574816
[ "MIT" ]
Richienb/CKAN
GUI/MainChangeset.cs
6,117
C#
// ReSharper disable CheckNamespace using Jitter.Dynamics; namespace Protogame { /// <summary> /// An event that signals that two rigid bodies have stopped colliding in the game. /// </summary> /// <module>Physics</module> public class PhysicsCollisionEndEvent : PhysicsEvent { /// <summary> /// Initializes a new instance of a <see cref="PhysicsCollisionEndEvent"/>. This constructor /// is intended to be used internally within the framework. /// </summary> /// <param name="gameContext">The current game context, or null if running on a server.</param> /// <param name="serverContext">The current server context, or null if running on a client.</param> /// <param name="updateContext">The current update context.</param> /// <param name="body1">The first body involved in the collision.</param> /// <param name="body2">The second body involved in the collision.</param> /// <param name="owner1">The owner of the first body.</param> /// <param name="owner2">The owner of the second body.</param> public PhysicsCollisionEndEvent( IGameContext gameContext, IServerContext serverContext, IUpdateContext updateContext, RigidBody body1, RigidBody body2, object owner1, object owner2) : base( gameContext, serverContext, updateContext) { Body1 = body1; Body2 = body2; Owner1 = owner1; Owner2 = owner2; } /// <summary> /// The first body involved in the collision. /// </summary> public RigidBody Body1 { get; } /// <summary> /// The second body involved in the collision. /// </summary> public RigidBody Body2 { get; } /// <summary> /// The owner of the first body. /// </summary> public object Owner1 { get; } /// <summary> /// The owner of the second body. /// </summary> public object Owner2 { get; } } }
34.285714
107
0.57037
[ "Unlicense", "MIT" ]
RedpointGames/Protogame
Protogame/Physics/PhysicsCollisionEndEvent.cs
2,162
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("LeetCode406")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LeetCode406")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("c267cb12-216b-41b0-976e-a8aefe0e6cd1")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.324324
56
0.716115
[ "MIT" ]
Armin1995/LeetCode
LeetCode406/Properties/AssemblyInfo.cs
1,278
C#
namespace MAZE.Api.Contracts { public enum ObstacleType { ForceField, Lock, Stone, Ghost, } }
12.636364
29
0.510791
[ "Unlicense" ]
kits-ab/MAZE
src/MAZE.Api/Contracts/ObstacleType.cs
141
C#
using AutoMapper; using JWTAPI.Controllers.Resources; using JWTAPI.Core.Models; using JWTAPI.Core.Services; using Microsoft.AspNetCore.Mvc; namespace JWTAPI.Controllers { [ApiController] [Route("/api/[controller]")] public class UsersController : Controller { private readonly IMapper _mapper; private readonly IUserService _userService; public UsersController(IUserService userService, IMapper mapper) { _userService = userService; _mapper = mapper; } [HttpPost] public async Task<IActionResult> CreateUserAsync([FromBody] UserCredentialsResource userCredentials) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = _mapper.Map<UserCredentialsResource, User>(userCredentials); var response = await _userService.CreateUserAsync(user, ApplicationRole.Common); if(!response.Success) { return BadRequest(response.Message); } var userResource = _mapper.Map<User, UserResource>(response.User); return Ok(userResource); } } }
29.190476
108
0.620718
[ "MIT" ]
dumpvn/jwt-api
src/JWTAPI/JWTAPI/Controllers/UsersController.cs
1,226
C#
// Copyright (c) 2007-2014 Joe White // // 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.Text; using DGrok.Framework; using DGrok.Visitors; using NUnit.Framework; namespace DGrok.Tests.Visitors { [TestFixture] public class FindVariantRecordsTests : CodeBaseActionTestCase { protected override ICodeBaseAction CreateAction() { return new FindVariantRecords(); } [Test] public void NoHits() { IList<Hit> hits = HitsFor( "unit Foo;", "interface", "type", " TFoo = record", " end;", "implementation", "end."); Assert.That(hits.Count, Is.EqualTo(0)); } [Test] public void Type() { IList<Hit> hits = HitsFor( "unit Foo;", "interface", "type", " TBar = record", " A: Integer;", " case B: Integer of", " 0: ()", " end;", "implementation", "end."); Assert.That(hits.Count, Is.EqualTo(1)); Assert.That(hits[0].Description, Is.EqualTo("TBar = record ... case B: Integer of")); } [Test] public void Constant() { IList<Hit> hits = HitsFor( "unit Foo;", "interface", "const", " Bar: record", " A: Integer;", " case B: Integer of", " 0: ()", " end = ();", "implementation", "end."); Assert.That(hits.Count, Is.EqualTo(1)); Assert.That(hits[0].Description, Is.EqualTo("Bar: record ... case B: Integer of")); } [Test] public void Field() { IList<Hit> hits = HitsFor( "unit Foo;", "interface", "type", " TBar = class", " strict private", " FBaz: record", " A: Integer;", " case B: Integer of", " 0: ()", " end;", " end;", "implementation", "end."); Assert.That(hits.Count, Is.EqualTo(1)); Assert.That(hits[0].Description, Is.EqualTo("FBaz: record ... case B: Integer of")); } [Test] public void Var() { IList<Hit> hits = HitsFor( "unit Foo;", "interface", "var", " Bar: record", " A: Integer;", " case B: Integer of", " 0: ()", " end;", "implementation", "end."); Assert.That(hits.Count, Is.EqualTo(1)); Assert.That(hits[0].Description, Is.EqualTo("Bar: record ... case B: Integer of")); } } }
34.219512
97
0.49014
[ "MIT" ]
leightonbb/dgrok2015
Source/DGrok.Tests/Visitors/FindVariantRecordsTests.cs
4,209
C#
#region << 版 本 注 释 >> /*---------------------------------------------------------------- * Copyright (C) 2018 天下商机(txooo.com)版权所有 * * 文 件 名:UserFactory * 所属项目:Iwenli.Mobile * 创建用户:iwenli(HouWeiya) * 创建时间:2018/5/22 15:58:55 * * 功能描述: * 1、 * * 修改标识: * 修改描述: * 修改时间: * 待 完 善: * 1、 ----------------------------------------------------------------*/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Iwenli.Mobile { public class UserFactory { #region 订阅处理事件 static Queue<KeyValuePair<AccountInfo, UserInfo>> m_subscribeQueue = new Queue<KeyValuePair<AccountInfo, UserInfo>>(); static Queue<KeyValuePair<AccountInfo, UserInfo>> m_unSubscribeUserQueue = new Queue<KeyValuePair<AccountInfo, UserInfo>>(); public static void AddSubscribeUser(AccountInfo account, UserInfo user) { m_subscribeQueue.Enqueue(new KeyValuePair<AccountInfo, UserInfo>(account, user)); } public static void AddUnSubscribeUser(AccountInfo account, UserInfo user) { m_unSubscribeUserQueue.Enqueue(new KeyValuePair<AccountInfo, UserInfo>(account, user)); } #endregion #region 更新用户信息 /// <summary> /// 更新用户信息 /// </summary> /// <param name="user"></param> public static void UpdateUserInfo(UserInfo user) { try { using (DataHelper helper = DataHelper.GetDataHelper("IwenliMobile")) { //获取用户ID helper.SpFileValue["@platform"] = (int)user.Platform; helper.SpFileValue["@openid"] = user.OpenId; helper.SpFileValue["@nickname"] = System.Web.HttpUtility.HtmlEncode(user.Nickname); helper.SpFileValue["@sex"] = user.Sex; helper.SpFileValue["@city"] = user.City; helper.SpFileValue["@country"] = user.Country; helper.SpFileValue["@province"] = user.Province; helper.SpFileValue["@language"] = user.Language; helper.SpFileValue["@headimgurl"] = user.HeadimgUrl; helper.SpGetReturnValue("SP_Service_MrLee_UpdateUserInfo"); } //this.TxLogInfo("获取usermapid成功:" + _userMapId); } catch (Exception ex) { //this.TxLogInfo("获取usermapid错误:" + ex.Message); } } #endregion #region 记录用户消息 /// <summary> /// 记录用户请求消息 /// </summary> /// <param name="userMapId"></param> /// <param name="reqmsg"></param> public static void NoteUserReqInfo(long userMapId, Platform.ReqMsg reqmsg) { try { using (DataHelper helper = DataHelper.GetDataHelper("IwenliMobile")) { string _jsonStr = LitJson.JsonMapper.ToJson(reqmsg); //获取用户ID helper.SpFileValue["@user_map_id"] = userMapId; helper.SpFileValue["@is_send"] = 0; helper.SpFileValue["@message_type"] = (int)reqmsg.MsgType; helper.SpFileValue["@json_countent"] = _jsonStr; helper.SpGetReturnValue("SP_Service_MrLee_InsertMessage"); } //this.TxLogInfo("获取usermapid成功:" + _userMapId); } catch (Exception ex) { //this.TxLogInfo("获取usermapid错误:" + ex.Message); } } /// <summary> /// 记录向用户发送的消息 /// </summary> /// <param name="userMapId"></param> /// <param name="resmsg"></param> public static void NoteUserResMsg(long userMapId, Platform.ResMsg resmsg) { try { using (DataHelper helper = DataHelper.GetDataHelper("IwenliMobile")) { string _jsonStr = LitJson.JsonMapper.ToJson(resmsg); //获取用户ID helper.SpFileValue["@user_map_id"] = userMapId; helper.SpFileValue["@is_send"] = 1; helper.SpFileValue["@message_type"] = (int)resmsg.MsgType; helper.SpFileValue["@json_countent"] = _jsonStr; helper.SpGetReturnValue("SP_Service_MrLee_InsertMessage"); } //this.TxLogInfo("获取usermapid成功:" + _userMapId); } catch (Exception ex) { //this.TxLogInfo("获取usermapid错误:" + ex.Message); } } #endregion #region 工厂方法 static Hashtable m_userInfoList = new Hashtable(); public static UserInfo GetUserInfo(AccountInfo account, string openId) { string _key = account.Platform + "_" + account.AccountId + "_" + openId; UserInfo _userInfo = m_userInfoList[_key] as UserInfo; long _userMapId = 0; if (_userInfo == null) { //获取用户ID using (DataHelper helper = DataHelper.GetDataHelper("IwenliMobile")) { helper.SpFileValue["@account_id"] = account.AccountId; helper.SpFileValue["@platform"] = (int)account.Platform; helper.SpFileValue["@openid"] = openId; _userMapId = helper.SpGetReturnValue("SP_Service_MrLee_GetUserMapId"); } //从数据库提取数据 _userInfo = UserInfo.GetUserInfoByUserMapId(_userMapId); m_userInfoList[_key] = _userInfo; //if (string.IsNullOrEmpty(_userInfo.Nickname)) //{ // //同步数据 // string _errorInfo; // if (account.ApiHelper.GetUserInfo(3, openId, ref _userInfo, out _errorInfo)) // { // Txooo.Mobile.UserFactory.UpdateUserInfo(_userInfo); // } //} } else if (_userInfo.UserMapId == 0) { //获取用户ID using (DataHelper helper = DataHelper.GetDataHelper("IwenliMobile")) { helper.SpFileValue["@account_id"] = account.AccountId; helper.SpFileValue["@platform"] = (int)account.Platform; helper.SpFileValue["@openid"] = openId; _userMapId = helper.SpGetReturnValue("SP_Service_MrLee_GetUserMapId"); } //从数据库提取数据 _userInfo = UserInfo.GetUserInfoByUserMapId(_userMapId); m_userInfoList[_key] = _userInfo; } Thread _thread = new Thread(new ThreadStart(() => { try { string _errorInfo; UserInfo _remoteUser = new UserInfo(account.Platform, openId); if (account.ApiHelper.GetUserInfo(3, openId, ref _remoteUser, out _errorInfo)) { if (_remoteUser.Nickname != _userInfo.Nickname || _remoteUser.HeadimgUrl != _userInfo.HeadimgUrl) { Iwenli.Mobile.UserFactory.UpdateUserInfo(_remoteUser); m_userInfoList[_key] = _remoteUser; } } } catch (Exception ex) { LogHelper.GetLogger("Txooo.Mobile.UserFactory").Error("同步用户数据错误:" + ex.Message); } })); _thread.Start(); return _userInfo; } #endregion } }
35.20354
132
0.506159
[ "Apache-2.0" ]
iwenli/ILI
Iwenli.Mobile/UserFactory.cs
8,326
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using Contoso.FraudProtection.Web.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Contoso.FraudProtection.Web.Controllers { [Route("")] public class CatalogController : Controller { private readonly ICatalogService _catalogService; public CatalogController(ICatalogService catalogService) { _catalogService = catalogService; } [HttpGet] [HttpPost] public async Task<IActionResult> Index(int? brandFilterApplied, int? typesFilterApplied, int? page) { var itemsPage = 10; var catalogModel = await _catalogService.GetCatalogItems(page ?? 0, itemsPage, brandFilterApplied, typesFilterApplied); return View(catalogModel); } [HttpGet("Error")] public IActionResult Error() { return View(); } } }
27.638889
131
0.642211
[ "MIT" ]
Bhaskers-Blu-Org2/Dynamics-365-Fraud-Protection-Samples
src/Web/Controllers/CatalogController.cs
995
C#
/* * RTaskFactory.cs * * Copyright (C) 2010-2015 by Microsoft Corporation * * This program is licensed to you under the terms of Version 2.0 of the * Apache License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0) for more details. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DeployRBroker { /// <summary> /// Factory class to create instance of the RTask implementations (Discrete, Background or Pooled). /// </summary> /// <remarks></remarks> public class RTaskFactory { /// <summary> /// Utility function for creating a DiscreteTask Instance of RTask /// </summary> /// <param name="filename">Name of repository R Script executed on the discrete task</param> /// <param name="directory">Directory in the repository where the R Script is located</param> /// <param name="author">Author of the repository R Script</param> /// <param name="version">Optional version of the R Script</param> /// <param name="options">Specification of options for the discrete task</param> /// <returns>DiscreteTask instance</returns> /// <remarks></remarks> public static RTask discreteTask(String filename, String directory, String author, String version, DiscreteTaskOptions options) { return new DiscreteTask(filename, directory, author, version, options); } /// <summary> /// Utility function for creating a DiscreteTask Instance of RTask /// </summary> /// <param name="externalURL">URL that represents an R Script executed on the discrete task</param> /// <param name="options">Specification of options for the discrete task</param> /// <returns>DiscreteTask instance</returns> /// <remarks></remarks> public static RTask discreteTask(String externalURL, DiscreteTaskOptions options) { return new DiscreteTask(externalURL, options); } /// <summary> /// Utility function for creating a PooledTask Instance of RTask /// </summary> /// <param name="filename">Name of repository R Script executed on the pooled task</param> /// <param name="directory">Directory in the repository where the R Script is located</param> /// <param name="author">Author of the repository R Script</param> /// <param name="version">Optional version of the R Script</param> /// <param name="options">Specification of options for the pooled task</param> /// <returns>PooledTask instance</returns> /// <remarks></remarks> public static RTask pooledTask(String filename, String directory, String author, String version, PooledTaskOptions options) { return new PooledTask(filename, directory, author, version, options); } /// <summary> /// Utility function for creating a PooledTask Instance of RTask /// </summary> /// <param name="codeBlock">R code to be executed on the pooled task</param> /// <param name="options">Specification of options for the pooled task</param> /// <returns>PooledTask instance</returns> /// <remarks></remarks> public static RTask pooledTask(String codeBlock, PooledTaskOptions options) { return new PooledTask(codeBlock, options); } /// <summary> /// Utility function for creating a PooledTask Instance of RTask /// </summary> /// <param name="externalURL">URL that represents an R Script executed on the pooled task</param> /// <param name="hasURL">Boolean specifying that a URL will be use to execute on the pooled task</param> /// <param name="options">Specification of options for the background task</param> /// <returns>PooledTask instance</returns> /// <remarks></remarks> public static RTask pooledTask(String externalURL, Boolean hasURL, PooledTaskOptions options) { return new PooledTask(externalURL, hasURL, options); } /// <summary> /// Utility function for creating a BackgroundTask Instance of RTask /// </summary> /// <param name="taskName">Name of the background task</param> /// <param name="taskDescription">Description of the background task</param> /// <param name="filename">Name of repository R Script executed on the background task</param> /// <param name="directory">Directory in the repository where the R Script is located</param> /// <param name="author">Author of the repository R Script</param> /// <param name="version">Optional version of the R Script</param> /// <param name="options">Specification of options for the background task</param> /// <returns>BackgroundTask instance</returns> /// <remarks></remarks> public static RTask backgroundTask(String taskName, String taskDescription, String filename, String directory, String author, String version, BackgroundTaskOptions options) { return new BackgroundTask(taskName, taskDescription, filename, directory, author, version, options); } /// <summary> /// Utility function for creating a BackgroundTask Instance of RTask /// </summary> /// <param name="taskName">Name of the background task</param> /// <param name="taskDescription">Description of the background task</param> /// <param name="codeBlock">R code to be executed on the background task</param> /// <param name="options">Specification of options for the background task</param> /// <returns>BackgroundTask instance</returns> /// <remarks></remarks> public static RTask backgroundTask(String taskName, String taskDescription, String codeBlock, BackgroundTaskOptions options) { return new BackgroundTask(taskName, taskDescription, codeBlock, options); } /// <summary> /// Utility function for creating a BackgroundTask Instance of RTask /// </summary> /// <param name="taskName">Name of the background task</param> /// <param name="taskDescription">Description of the background task</param> /// <param name="externalURL">URL that represents an R Script executed on the background task</param> /// <param name="hasURL">Boolean specifying that a URL will be use to execute on the background task</param> /// <param name="options">Specification of options for the background task</param> /// <returns>BackgroundTask instance</returns> /// <remarks></remarks> public static RTask backgroundTask(String taskName, String taskDescription, String externalURL, Boolean hasURL, BackgroundTaskOptions options) { return new BackgroundTask(taskName, taskDescription, externalURL, hasURL, options); } } }
47.641176
116
0.58785
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/dotnet-rbroker-framework
src/DeployRBroker/RTaskFactory.cs
8,101
C#
#if !NET45 extern alias PTL; #endif using System; using System.Windows; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using Confuser.Core; using Confuser.Core.Project; using GalaSoft.MvvmLight.Command; #if !NET45 using PTL::System.Threading; #else using System.Threading; #endif // http://connect.microsoft.com/VisualStudio/feedback/details/615953/ namespace ConfuserEx.ViewModel { internal class ProtectTabVM : TabViewModel, ILogger { private readonly Paragraph documentContent; private CancellationTokenSource cancelSrc; private double? progress = 0; private bool? result; public ProtectTabVM(AppVM app) : base(app, "Protect!") { documentContent = new Paragraph(); LogDocument = new FlowDocument(); LogDocument.Blocks.Add(documentContent); } public ICommand ProtectCmd { get { return new RelayCommand(DoProtect, () => !App.NavigationDisabled); } } public ICommand CancelCmd { get { return new RelayCommand(DoCancel, () => App.NavigationDisabled); } } public double? Progress { get { return progress; } set { SetProperty(ref progress, value, "Progress"); } } public FlowDocument LogDocument { get; private set; } public bool? Result { get { return result; } set { SetProperty(ref result, value, "Result"); } } private void DoProtect() { var parameters = new ConfuserParameters(); parameters.Project = ((IViewModel<ConfuserProject>)App.Project).Model; parameters.Logger = this; documentContent.Inlines.Clear(); cancelSrc = new CancellationTokenSource(); Result = null; Progress = null; begin = DateTime.Now; App.NavigationDisabled = true; ConfuserEngine.Run(parameters, cancelSrc.Token) .ContinueWith(_ => Application.Current.Dispatcher.BeginInvoke(new Action(() => { Progress = 0; App.NavigationDisabled = false; CommandManager.InvalidateRequerySuggested(); }))); } private void DoCancel() { cancelSrc.Cancel(); } private void AppendLine(string format, Brush foreground, params object[] args) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { documentContent.Inlines.Add(new Run(string.Format(format, args)) { Foreground = foreground }); documentContent.Inlines.Add(new LineBreak()); })); } #region Logger Impl private DateTime begin; void ILogger.Debug(string msg) { AppendLine("[DEBUG] {0}", Brushes.Gray, msg); } void ILogger.DebugFormat(string format, params object[] args) { AppendLine("[DEBUG] {0}", Brushes.Gray, string.Format(format, args)); } void ILogger.Info(string msg) { AppendLine(" [INFO] {0}", Brushes.White, msg); } void ILogger.InfoFormat(string format, params object[] args) { AppendLine(" [INFO] {0}", Brushes.White, string.Format(format, args)); } void ILogger.Warn(string msg) { AppendLine(" [WARN] {0}", Brushes.Yellow, msg); } void ILogger.WarnFormat(string format, params object[] args) { AppendLine(" [WARN] {0}", Brushes.Yellow, string.Format(format, args)); } void ILogger.WarnException(string msg, Exception ex) { AppendLine(" [WARN] {0}", Brushes.Yellow, msg); AppendLine("Exception: {0}", Brushes.Yellow, ex); } void ILogger.Error(string msg) { AppendLine("[ERROR] {0}", Brushes.Red, msg); } void ILogger.ErrorFormat(string format, params object[] args) { AppendLine("[ERROR] {0}", Brushes.Red, string.Format(format, args)); } void ILogger.ErrorException(string msg, Exception ex) { AppendLine("[ERROR] {0}", Brushes.Red, msg); AppendLine("Exception: {0}", Brushes.Red, ex); } void ILogger.Progress(int progress, int overall) { Progress = (double)progress / overall; } void ILogger.EndProgress() { Progress = null; } void ILogger.Finish(bool successful) { DateTime now = DateTime.Now; string timeString = string.Format( "at {0}, {1}:{2:d2} elapsed.", now.ToShortTimeString(), (int)now.Subtract(begin).TotalMinutes, now.Subtract(begin).Seconds); if (successful) AppendLine("Finished {0}", Brushes.Lime, timeString); else AppendLine("Failed {0}", Brushes.Red, timeString); Result = successful; } #endregion } }
27.955128
98
0.667049
[ "MIT" ]
ambyte/ConfuserEx
ConfuserEx/ViewModel/UI/ProtectTabVM.cs
4,363
C#
using Proto; using System; using System.Threading.Tasks; namespace Hashgraph { public partial class Client { /// <summary> /// Retrieves the details regarding a file stored on the network. /// </summary> /// <param name="file"> /// Address of the file to query. /// </param> /// <param name="configure"> /// Optional callback method providing an opportunity to modify /// the execution configuration for just this method call. /// It is executed prior to submitting the request to the network. /// </param> /// <returns> /// The details of the network file, excluding content. /// </returns> /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception> /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception> /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception> public async Task<FileInfo> GetFileInfoAsync(Address file, Action<IContext>? configure = null) { return new FileInfo(await ExecuteQueryAsync(new FileGetInfoQuery(file), configure).ConfigureAwait(false)); } } }
41.90625
125
0.630872
[ "Apache-2.0" ]
ZhingShan/Hashgraph
src/Hashgraph/File/GetFileInfo.cs
1,343
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.Transactions; using Xunit; namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class AzureDistributedTransaction { private static readonly string s_connectionString = DataTestUtility.TCPConnectionString; private static readonly string s_tableName = DataTestUtility.GetUniqueNameForSqlServer("Azure"); private static readonly string s_createTableCmd = $"CREATE TABLE {s_tableName} (NAME NVARCHAR(40), AGE INT)"; private static readonly string s_sqlBulkCopyCmd = "SELECT * FROM(VALUES ('Fuller', 33), ('Davon', 49)) AS q (FirstName, Age)"; private static readonly int s_commandTimeout = 30; public static void Test() { try { #if DEBUG Console.WriteLine($"Creating Table {s_tableName}"); #endif // Setup Azure Table Helpers.ExecuteNonQueryAzure(s_connectionString, s_createTableCmd, s_commandTimeout); using (var txScope = new TransactionScope()) { BulkCopy(s_connectionString); txScope.Complete(); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); Assert.Null(ex); } finally { #if DEBUG Console.WriteLine($"Dropping Table {s_tableName}"); #endif // Drop Azure Table Helpers.ExecuteNonQueryAzure(s_connectionString, "DROP TABLE " + s_tableName, s_commandTimeout); } } static void BulkCopy(string connectionString) { using (SqlConnection connectionSrc = new SqlConnection(connectionString)) using (SqlConnection connectionDst = new SqlConnection(connectionString)) using (SqlCommand commandSrc = new SqlCommand(s_sqlBulkCopyCmd, connectionSrc)) using (SqlCommand commandDst = connectionDst.CreateCommand()) { connectionSrc.Open(); connectionDst.Open(); commandSrc.CommandTimeout = s_commandTimeout; using (SqlDataReader reader = commandSrc.ExecuteReader()) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connectionDst)) { sqlBulkCopy.DestinationTableName = s_tableName; sqlBulkCopy.WriteToServer(reader); } reader.Close(); } } } } }
38.643836
134
0.588798
[ "MIT" ]
0xced/SqlClient
src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AzureDistributedTransaction.cs
2,823
C#
namespace VRTK.Prefabs.Interactions.Controllables { using UnityEngine; using System.Collections.Generic; using Malimbe.XmlDocumentationAttribute; using Malimbe.PropertySerializationAttribute; using Malimbe.BehaviourStateRequirementMethod; using Zinnia.Data.Attribute; /// <summary> /// A rotational drive that utilizes a physics joint to control the rotational angle. /// </summary> public class RotationalJointDrive : RotationalDrive { #region Joint Settings /// <summary> /// The joint being used to drive the rotation. /// </summary> [Serialized] [field: Header("Joint Settings"), DocumentedByXml, Restricted] public HingeJoint Joint { get; protected set; } /// <summary> /// The parent <see cref="GameObject"/> of the joint. /// </summary> [Serialized] [field: DocumentedByXml, Restricted] public GameObject JointContainer { get; protected set; } #endregion /// <summary> /// The <see cref="Rigidbody"/> that the joint is using. /// </summary> protected Rigidbody jointRigidbody; /// <summary> /// The motor data to set on the joint. /// </summary> protected JointMotor jointMotor; /// <summary> /// A reusable collection to hold the active state of children of the <see cref="Rigidbody"/>s that are adjusted. /// </summary> protected readonly List<bool> rigidbodyChildrenActiveStates = new List<bool>(); /// <inheritdoc /> [RequiresBehaviourState] public override Vector3 CalculateDriveAxis(DriveAxis.Axis driveAxis) { Vector3 axisDirection = base.CalculateDriveAxis(driveAxis); Joint.axis = axisDirection * -1f; return axisDirection; } /// <inheritdoc /> [RequiresBehaviourState] public override void CalculateHingeLocation(Vector3 newHingeLocation) { Joint.anchor = newHingeLocation; SetJointContainerPosition(); } /// <inheritdoc /> [RequiresBehaviourState] public override void ConfigureAutoDrive(bool autoDrive) { Joint.useMotor = autoDrive; } /// <inheritdoc /> public override void ApplyExistingAngularVelocity(float multiplier = 1f) { jointRigidbody.angularVelocity = AxisDirection * pseudoAngularVelocity * multiplier; } /// <inheritdoc /> protected override void SetUpInternals() { jointMotor.force = Joint.motor.force; jointRigidbody = Joint.GetComponent<Rigidbody>(); ConfigureAutoDrive(Facade.MoveToTargetValue); base.SetUpInternals(); } /// <inheritdoc /> protected override Transform GetDriveTransform() { return Joint.transform; } /// <inheritdoc /> protected override void ProcessAutoDrive(float driveSpeed) { jointMotor.targetVelocity = driveSpeed; Joint.motor = jointMotor; } /// <inheritdoc /> protected override void AttemptApplyLimits() { if (!Joint.useLimits && ApplyLimits()) { jointRigidbody.velocity = Vector3.zero; jointRigidbody.angularVelocity = Vector3.zero; } } /// <summary> /// Sets the <see cref="JointContainer"/> position based on the joint anchor. /// </summary> protected virtual void SetJointContainerPosition() { // Disable any child rigidbody GameObjects of the joint to prevent the anchor position updating their position. Rigidbody[] rigidbodyChildren = Joint.GetComponentsInChildren<Rigidbody>(); rigidbodyChildrenActiveStates.Clear(); for (int index = 0; index < rigidbodyChildren.Length; index++) { if (rigidbodyChildren[index].gameObject == JointContainer || rigidbodyChildren[index] == jointRigidbody) { rigidbodyChildrenActiveStates.Add(false); continue; } rigidbodyChildrenActiveStates.Add(rigidbodyChildren[index].gameObject.activeSelf); rigidbodyChildren[index].gameObject.SetActive(false); } // Set the current joint container to match the joint anchor to provide the correct offset. JointContainer.transform.localPosition = Joint.anchor; JointContainer.transform.localRotation = Quaternion.identity; // Restore the state of child rigidbody GameObjects now the anchor position has been set. for (int index = 0; index < rigidbodyChildren.Length; index++) { if (rigidbodyChildren[index].gameObject == JointContainer || rigidbodyChildren[index] == jointRigidbody) { continue; } rigidbodyChildren[index].gameObject.SetActive(rigidbodyChildrenActiveStates[index]); } } } }
38.021277
124
0.586085
[ "MIT" ]
Yun5141/VRTKtest
Library/PackageCache/io.extendreality.vrtk.prefabs@1.1.7/Interactions/Controllables/SharedResources/Scripts/RotationalJointDrive.cs
5,363
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace ScratchNet { public class TypeColorChangeEventArgs : EventArgs { public object Type { get; internal set; } public Color Color { get; internal set; } } }
21.0625
53
0.715134
[ "MIT" ]
HenJigg/WPF-Blocky
src/ScratchEditor/TypeColorChangeEventArgs.cs
339
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ytg.Scheduler.Comm.Bets.Calculate { /// <summary> /// 前二/前二组选/组选包胆 验证通过 2015/05/24 2016 01 18 /// </summary> public class QeZxbdCalculate : ZhiXuanDanShiDetailsCalculate { protected override void IssueCalculate(string issueCode, string openResult, BasicModel.LotteryBasic.BetDetail item) { var res = openResult.Replace(",", "").Substring(0,2);//后两位 if (res.Distinct().Count() == 2 && res.Contains(item.BetContent)) { item.IsMatch = true; decimal stepAmt = 0; item.WinMoney = TotalWinMoney(item, GetBaseAmt(item, ref stepAmt), stepAmt, 1); } } /// <summary> /// 因为只能选择一个数字,所以就是默认9注 /// </summary> /// <param name="item"></param> /// <returns></returns> public override int TotalBetCount(BasicModel.LotteryBasic.BetDetail item) { return 9; } public override string HtmlContentFormart(string betContent) { int outValue; if (!int.TryParse(betContent, out outValue)) return string.Empty; if (outValue < 0 || outValue > 9) return string.Empty; return betContent; } } }
29.604167
123
0.570021
[ "Apache-2.0" ]
heqinghua/lottery-code-qq-814788821-
YtgProject/Ytg.Scheduler.Comm/Bets/Calculate/Ssc/QianEr/QeZxbdCalculate.cs
1,493
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.EventHubs.Processor { using System; /// <summary> /// An exception thrown during event processing. /// </summary> public class EventProcessorRuntimeException : EventHubsException { internal EventProcessorRuntimeException(string message, string action) : this(message, action, null) { } internal EventProcessorRuntimeException(string message, string action, Exception innerException) : base(true, message, innerException) { this.Action = action; } /// <summary> /// Gets the action that was being performed when the exception occured. /// </summary> public string Action { get; } } }
31.310345
104
0.646476
[ "MIT" ]
0xced/azure-sdk-for-net
sdk/eventhub/Microsoft.Azure.EventHubs.Processor/src/EventProcessorRuntimeException.cs
910
C#
using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using WarHub.ArmouryModel.Source; namespace WarHub.ArmouryModel; /// <summary> /// Represents a mutable bag of diagnostics. You can add diagnostics to the bag, /// and also get all the diagnostics out of the bag (the bag implements /// IEnumerable&lt;Diagnostics&gt;. Once added, diagnostics cannot be removed, and no ordering /// is guaranteed. /// /// It is ok to Add diagnostics to the same bag concurrently on multiple threads. /// It is NOT ok to Add concurrently with Clear or Free operations. /// </summary> /// <remarks>The bag is optimized to be efficient when containing zero errors.</remarks> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] [DebuggerTypeProxy(typeof(DebuggerProxy))] internal class DiagnosticBag { // The lazyBag field is populated lazily -- the first time an error is added. private ConcurrentQueue<Diagnostic>? lazyBag; /// <summary> /// Return true if the bag is completely empty - not even containing void diagnostics. /// </summary> /// <remarks> /// This exists for short-circuiting purposes. Use <see cref="Enumerable.Any{T}(IEnumerable{T})"/> /// to get a resolved Tuple(Of NamedTypeSymbol, ImmutableArray(Of Diagnostic)) (i.e. empty after eliminating void diagnostics). /// </remarks> public bool IsEmptyWithoutResolution { get { // It should be safe to access this here, since we normally have a collect phase and // then a report phase, and we shouldn't be called during the "report" phase. We // also never remove diagnostics, so the worst that happens is that we don't return // an element that is added a split second after this is called. var bag = lazyBag; return bag == null || bag.IsEmpty; } } /// <summary> /// Returns true if the bag has any diagnostics with DefaultSeverity=Error. Does not consider warnings or informationals /// or warnings promoted to error via /warnaserror. /// </summary> /// <remarks> /// Resolves any lazy diagnostics in the bag. /// /// Generally, this should only be called by the creator (modulo pooling) of the bag (i.e. don't use bags to communicate - /// if you need more info, pass more info). /// </remarks> public bool HasAnyErrors() { if (IsEmptyWithoutResolution) { return false; } foreach (var diagnostic in Bag) { if (diagnostic.DefaultSeverity == DiagnosticSeverity.Error) { return true; } } return false; } /// <summary> /// Returns true if the bag has any non-lazy diagnostics with DefaultSeverity=Error. Does not consider warnings or informationals /// or warnings promoted to error via /warnaserror. /// </summary> /// <remarks> /// Does not resolve any lazy diagnostics in the bag. /// /// Generally, this should only be called by the creator (modulo pooling) of the bag (i.e. don't use bags to communicate - /// if you need more info, pass more info). /// </remarks> internal bool HasAnyResolvedErrors() { if (IsEmptyWithoutResolution) { return false; } foreach (var diagnostic in Bag) { if (diagnostic.DefaultSeverity == DiagnosticSeverity.Error) { return true; } } return false; } /// <summary> /// Add a diagnostic to the bag. /// </summary> public void Add(Diagnostic diag) { var bag = Bag; bag.Enqueue(diag); } /// <summary> /// Add multiple diagnostics to the bag. /// </summary> public void AddRange<T>(ImmutableArray<T> diagnostics) where T : Diagnostic { if (!diagnostics.IsDefaultOrEmpty) { var bag = Bag; for (var i = 0; i < diagnostics.Length; i++) { bag.Enqueue(diagnostics[i]); } } } /// <summary> /// Add multiple diagnostics to the bag. /// </summary> public void AddRange(IEnumerable<Diagnostic> diagnostics) { foreach (var diagnostic in diagnostics) { Bag.Enqueue(diagnostic); } } /// <summary> /// Add another DiagnosticBag to the bag. /// </summary> public void AddRange(DiagnosticBag bag) { if (!bag.IsEmptyWithoutResolution) { AddRange(bag.Bag); } } /// <summary> /// Add another DiagnosticBag to the bag and free the argument. /// </summary> public void AddRangeAndFree(DiagnosticBag bag) { AddRange(bag); bag.Free(); } /// <summary> /// Seal the bag so no further errors can be added, while clearing it and returning the old set of errors. /// Return the bag to the pool. /// </summary> public ImmutableArray<TDiagnostic> ToReadOnlyAndFree<TDiagnostic>() where TDiagnostic : Diagnostic { var oldBag = lazyBag; Free(); return ToReadOnlyCore<TDiagnostic>(oldBag); } public ImmutableArray<Diagnostic> ToReadOnlyAndFree() { return ToReadOnlyAndFree<Diagnostic>(); } public ImmutableArray<TDiagnostic> ToReadOnly<TDiagnostic>() where TDiagnostic : Diagnostic { var oldBag = lazyBag; return ToReadOnlyCore<TDiagnostic>(oldBag); } public ImmutableArray<Diagnostic> ToReadOnly() { return ToReadOnly<Diagnostic>(); } private static ImmutableArray<TDiagnostic> ToReadOnlyCore<TDiagnostic>(ConcurrentQueue<Diagnostic>? oldBag) where TDiagnostic : Diagnostic { if (oldBag == null) { return ImmutableArray<TDiagnostic>.Empty; } var builder = ImmutableArray.CreateBuilder<TDiagnostic>(); foreach (TDiagnostic diagnostic in oldBag) // Cast should be safe since all diagnostics should be from same language. { builder.Add(diagnostic); } return builder.ToImmutable(); } /// <remarks> /// Generally, this should only be called by the creator (modulo pooling) of the bag (i.e. don't use bags to communicate - /// if you need more info, pass more info). /// </remarks> public IEnumerable<Diagnostic> AsEnumerable() => Bag; internal IEnumerable<Diagnostic> AsEnumerableWithoutResolution() { // PERF: don't make a defensive copy - callers are internal and won't modify the bag. return lazyBag ?? Enumerable.Empty<Diagnostic>(); } internal int Count => lazyBag?.Count ?? 0; public override string ToString() { if (IsEmptyWithoutResolution) { // TODO(cyrusn): do we need to localize this? return "<no errors>"; } else { var builder = new StringBuilder(); foreach (var diag in Bag) // NOTE: don't force resolution { builder.AppendLine(diag.ToString()); } return builder.ToString(); } } /// <summary> /// Get the underlying concurrent storage, creating it on demand if needed. /// NOTE: Concurrent Adding to the bag is supported, but concurrent Clearing is not. /// If one thread adds to the bug while another clears it, the scenario is /// broken and we cannot do anything about it here. /// </summary> private ConcurrentQueue<Diagnostic> Bag { get { var bag = lazyBag; if (bag != null) { return bag; } var newBag = new ConcurrentQueue<Diagnostic>(); return Interlocked.CompareExchange(ref lazyBag, newBag, null) ?? newBag; } } // clears the bag. /// NOTE: Concurrent Adding to the bag is supported, but concurrent Clearing is not. /// If one thread adds to the bug while another clears it, the scenario is /// broken and we cannot do anything about it here. internal void Clear() { var bag = lazyBag; if (bag != null) { lazyBag = null; } } #region "Poolable" internal static DiagnosticBag GetInstance() { // DiagnosticBag bag = s_poolInstance.Allocate(); // return bag; return new DiagnosticBag(); } internal void Free() { Clear(); // s_poolInstance.Free(this); } // private static readonly ObjectPool<DiagnosticBag> s_poolInstance = CreatePool(128); // private static ObjectPool<DiagnosticBag> CreatePool(int size) // { // return new ObjectPool<DiagnosticBag>(() => new DiagnosticBag(), size); // } #endregion #region Debugger View internal sealed class DebuggerProxy { private readonly DiagnosticBag bag; public DebuggerProxy(DiagnosticBag bag) { this.bag = bag; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object[] Diagnostics { get { var lazyBag = bag.lazyBag; if (lazyBag != null) { return lazyBag.ToArray(); } else { return Array.Empty<object>(); } } } } private string GetDebuggerDisplay() { return "Count = " + (lazyBag?.Count ?? 0); } #endregion }
29.671779
142
0.591337
[ "MIT" ]
CloverFox/phalanx
src/WarHub.ArmouryModel.Extensions/DiagnosticBag.cs
9,673
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Insights { using Azure; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for MetricsOperations. /// </summary> public static partial class MetricsOperationsExtensions { /// <summary> /// **Lists the metric values for a resource**.&lt;br&gt;The **$filter** is /// used to reduce the set of metric data returned. Some common properties for /// this expression will be: name.value, aggregationType, startTime, endTime, /// timeGrain. The filter expression uses these properties with comparison /// operators (eg. eq, gt, lt) and multiple expressions can be combined with /// parentheses and 'and/or' operators.&lt;br&gt;Some example filter /// expressions are:&lt;br&gt;- $filter=(name.value eq 'RunsSucceeded') and /// aggregationType eq 'Total' and startTime eq 2016-02-20 and endTime eq /// 2016-02-21 and timeGrain eq duration'PT1M',&lt;br&gt;- $filter=(name.value /// eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq /// 'Average') and startTime eq 2016-02-20 and endTime eq 2016-02-21 and /// timeGrain eq duration'PT1H',&lt;br&gt;- $filter=(name.value eq /// 'ActionsCompleted' or name.value eq 'RunsSucceeded') and (aggregationType /// eq 'Total' or aggregationType eq 'Average') and startTime eq 2016-02-20 and /// endTime eq 2016-02-21 and timeGrain eq duration'PT1M'.&lt;br&gt;&lt;br&gt; /// &gt;**NOTE**: When a metrics query comes in with multiple metrics, but with /// no aggregation types defined, the service will pick the Primary aggregation /// type of the first metrics to be used as the default aggregation type for /// all the metrics. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IEnumerable<Metric> List(this IMetricsOperations operations, string resourceUri, ODataQuery<Metric> odataQuery = default(ODataQuery<Metric>)) { return operations.ListAsync(resourceUri, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// **Lists the metric values for a resource**.&lt;br&gt;The **$filter** is /// used to reduce the set of metric data returned. Some common properties for /// this expression will be: name.value, aggregationType, startTime, endTime, /// timeGrain. The filter expression uses these properties with comparison /// operators (eg. eq, gt, lt) and multiple expressions can be combined with /// parentheses and 'and/or' operators.&lt;br&gt;Some example filter /// expressions are:&lt;br&gt;- $filter=(name.value eq 'RunsSucceeded') and /// aggregationType eq 'Total' and startTime eq 2016-02-20 and endTime eq /// 2016-02-21 and timeGrain eq duration'PT1M',&lt;br&gt;- $filter=(name.value /// eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq /// 'Average') and startTime eq 2016-02-20 and endTime eq 2016-02-21 and /// timeGrain eq duration'PT1H',&lt;br&gt;- $filter=(name.value eq /// 'ActionsCompleted' or name.value eq 'RunsSucceeded') and (aggregationType /// eq 'Total' or aggregationType eq 'Average') and startTime eq 2016-02-20 and /// endTime eq 2016-02-21 and timeGrain eq duration'PT1M'.&lt;br&gt;&lt;br&gt; /// &gt;**NOTE**: When a metrics query comes in with multiple metrics, but with /// no aggregation types defined, the service will pick the Primary aggregation /// type of the first metrics to be used as the default aggregation type for /// all the metrics. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Metric>> ListAsync(this IMetricsOperations operations, string resourceUri, ODataQuery<Metric> odataQuery = default(ODataQuery<Metric>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceUri, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
54.92381
250
0.613837
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Monitor/Microsoft.Azure.Monitor/Generated/Monitor/MetricsOperationsExtensions.cs
5,767
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AdventureWorks.Data.Entities { using System; using System.Collections.Generic; public partial class vJobCandidateEducation { public int JobCandidateID { get; set; } public string Edu_Level { get; set; } public Nullable<System.DateTime> Edu_StartDate { get; set; } public Nullable<System.DateTime> Edu_EndDate { get; set; } public string Edu_Degree { get; set; } public string Edu_Major { get; set; } public string Edu_Minor { get; set; } public string Edu_GPA { get; set; } public string Edu_GPAScale { get; set; } public string Edu_School { get; set; } public string Edu_Loc_CountryRegion { get; set; } public string Edu_Loc_State { get; set; } public string Edu_Loc_City { get; set; } } }
39.1875
85
0.570175
[ "Apache-2.0" ]
AsimKhan2019/AdventuresWorks-Web-API
AdventureWorks.Data/Entities/vJobCandidateEducation.cs
1,254
C#
using UnityEngine; using System.Collections; public class PCHotkeys : IHotkeys { public KeyCode GetBuildBarracksHotkey() { return KeyCode.N; } public KeyCode GetBuildPlayerBaseHotkey() { return KeyCode.B; } public KeyCode GetCameraMoveDownHotkey() { return KeyCode.S; } public KeyCode GetCameraMoveLeftHotkey() { return KeyCode.A; } public KeyCode GetCameraMoveRightHotkey() { return KeyCode.D; } public KeyCode GetCameraMoveUpHotkey() { return KeyCode.W; } public KeyCode GetInfantryBuildHotkey() { return KeyCode.I; } public KeyCode GetQuitHotkey() { return KeyCode.Escape; } }
16.282609
45
0.612817
[ "MIT" ]
TheDarkWeasel/protogame
BloodBuilder/Assets/Scripts/Hotkeys/PCHotkeys.cs
751
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V23.Group { ///<summary> ///Represents the RAR_RAR_DEFINITION Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: QRD (Query definition segment) </li> ///<li>1: QRF (Query filter segment) optional </li> ///<li>2: RAR_RAR_PATIENT (a Group object) optional </li> ///<li>3: RAR_RAR_ORDER (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class RAR_RAR_DEFINITION : AbstractGroup { ///<summary> /// Creates a new RAR_RAR_DEFINITION Group. ///</summary> public RAR_RAR_DEFINITION(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(QRD), true, false); this.add(typeof(QRF), false, false); this.add(typeof(RAR_RAR_PATIENT), false, false); this.add(typeof(RAR_RAR_ORDER), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RAR_RAR_DEFINITION - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns QRD (Query definition segment) - creates it if necessary ///</summary> public QRD QRD { get{ QRD ret = null; try { ret = (QRD)this.GetStructure("QRD"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns QRF (Query filter segment) - creates it if necessary ///</summary> public QRF QRF { get{ QRF ret = null; try { ret = (QRF)this.GetStructure("QRF"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns RAR_RAR_PATIENT (a Group object) - creates it if necessary ///</summary> public RAR_RAR_PATIENT PATIENT { get{ RAR_RAR_PATIENT ret = null; try { ret = (RAR_RAR_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of RAR_RAR_ORDER (a Group object) - creates it if necessary ///</summary> public RAR_RAR_ORDER GetORDER() { RAR_RAR_ORDER ret = null; try { ret = (RAR_RAR_ORDER)this.GetStructure("ORDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of RAR_RAR_ORDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public RAR_RAR_ORDER GetORDER(int rep) { return (RAR_RAR_ORDER)this.GetStructure("ORDER", rep); } /** * Returns the number of existing repetitions of RAR_RAR_ORDER */ public int ORDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("ORDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the RAR_RAR_ORDER results */ public IEnumerable<RAR_RAR_ORDER> ORDERs { get { for (int rep = 0; rep < ORDERRepetitionsUsed; rep++) { yield return (RAR_RAR_ORDER)this.GetStructure("ORDER", rep); } } } ///<summary> ///Adds a new RAR_RAR_ORDER ///</summary> public RAR_RAR_ORDER AddORDER() { return this.AddStructure("ORDER") as RAR_RAR_ORDER; } ///<summary> ///Removes the given RAR_RAR_ORDER ///</summary> public void RemoveORDER(RAR_RAR_ORDER toRemove) { this.RemoveStructure("ORDER", toRemove); } ///<summary> ///Removes the RAR_RAR_ORDER at the given index ///</summary> public void RemoveORDERAt(int index) { this.RemoveRepetition("ORDER", index); } } }
30.029586
157
0.653399
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V23/Group/RAR_RAR_DEFINITION.cs
5,075
C#
/*----------------------------------------------------------------------------- The MIT License (MIT) This source file is part of GDGeek (Game Develop & Game Engine Extendable Kits) For the latest info, see http://gdgeek.com/ Copyright (c) 2014-2017 GDGeek Software Ltd 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 UnityEngine; using UnityEngine.UI; using System.Collections; namespace GDGeek{ public class SampleAnimation : MonoBehaviour { public Image _image = null; public Sprite[] _sprites = null; public float _interval = 1.0f; private float allTime_ = 0; private int index_ = 0; // Update is called once per frame void Update () { allTime_ += Time.deltaTime; while (allTime_ > _interval) { allTime_-= _interval; index_++; index_ %= _sprites.Length; _image.sprite = _sprites[index_]; } } } }
37.509804
80
0.69838
[ "MIT" ]
gdgeek/GDGeek
Assets/GDGeek/Plugins/GDGeek/Toolkits/SampleAnimation.cs
1,915
C#
using System; using System.Threading.Tasks; using ConsoleInteractive.InputValidation; using Xunit; namespace ConsoleInteractive.Tests.InputValidation { public class ValidationProviderTests { [Fact] public void TestRegisterRetriveValid() { var provider = GetProvider(); var target = "TEST1"; provider.Register(target, ValidatorCollection.Create<long>()); var subject = provider.GetCollection(target); Assert.NotNull(subject); Assert.False(subject is IValidatorCollection<object>); Assert.True(subject is IValidatorCollection<long>); Assert.NotNull(provider.GetCollection<long>(target)); } [Fact] public void TestRegisterRetriveInvalid() { var provider = GetProvider(); var target = "TEST1"; var validTarget = "BATATAS"; provider.Register(validTarget, ValidatorCollection.Create<long>()); var subject = provider.GetCollection(target); Assert.NotNull(subject); Assert.True(subject is IValidatorCollection<object>); Assert.False(subject is IValidatorCollection<long>); Assert.ThrowsAny<InvalidCastException>(() => provider.GetCollection<long>(target)); Assert.ThrowsAny<InvalidCastException>(() => provider.GetCollection<string>(validTarget)); } [Fact] public async Task TestRetriveFlagEnum() { var provider = GetProvider(); var target1 = StringValidator.NotEmpty; var target2 = StringValidator.NotEmpty | StringValidator.MinLength3; var target3 = StringValidator.NotEmpty | StringValidator.MinLength3 | StringValidator.MinLength7; var target4 = StringValidator.NotEmpty | StringValidator.MinLength3 | StringValidator.MinLength7 | StringValidator.Lowercase; var subject1 = provider.GetCollection<StringValidator, string>(target1); var subject2 = provider.GetCollection<StringValidator, string>(target2); var subject3 = provider.GetCollection<StringValidator, string>(target3); var subject4 = provider.GetCollection<StringValidator, string>(target4); Assert.Equal(1, subject1.Count); Assert.Equal(2, subject2.Count); Assert.Equal(3, subject3.Count); Assert.Equal(4, subject4.Count); var (test1_0, _) = await provider.Validate(target1, ""); var (test1_1, _) = await provider.Validate(target1, "BA"); Assert.False(test1_0); Assert.True(test1_1); var (test2_0, _) = await provider.Validate(target2, ""); var (test2_1, _) = await provider.Validate(target2, "BA"); var (test2_2, _) = await provider.Validate(target2, "BATA"); Assert.False(test2_0); Assert.False(test2_1); Assert.True(test2_2); var (test3_0, _) = await provider.Validate(target3, ""); var (test3_1, _) = await provider.Validate(target3, "BA"); var (test3_2, _) = await provider.Validate(target3, "BATA"); var (test3_3, _) = await provider.Validate(target3, "BATATAS"); Assert.False(test3_0); Assert.False(test3_1); Assert.False(test3_2); Assert.True(test3_3); var (test4_0, _) = await provider.Validate(target4, ""); var (test4_1, _) = await provider.Validate(target4, "BA"); var (test4_2, _) = await provider.Validate(target4, "BATA"); var (test4_3, _) = await provider.Validate(target4, "BATATAS"); var (test4_4, _) = await provider.Validate(target4, "batatas"); Assert.False(test4_0); Assert.False(test4_1); Assert.False(test4_2); Assert.False(test4_3); Assert.True(test4_4); } private ValidatorProvider GetProvider() { var provider = new ValidatorProvider(); provider.Register( StringValidator.NotEmpty, ValidatorCollection.Create<string>() .Add(e => (!string.IsNullOrEmpty(e), "Can't be empty"))); provider.Register( StringValidator.MinLength3, ValidatorCollection.Create<string>() .Add(e => (e.Length >= 3, "Length must be at least 3"))); provider.Register( StringValidator.MinLength7, ValidatorCollection.Create<string>() .Add(e => (e.Length >= 7, "Length must be at least 7"))); provider.Register( StringValidator.Lowercase, ValidatorCollection.Create<string>() .Add(e => (e == e.ToLower(), "Must be in lowercase"))); return provider; } } [Flags] enum StringValidator { NotEmpty = 1, MinLength3 = 2, MinLength7 = 4, Lowercase = 8, } }
40.277778
137
0.589754
[ "MIT" ]
Davidblkx/ConsoleInteractive
ConsoleInteractive.Tests/InputValidation/ValidationProviderTests.cs
5,075
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Yue.Bookings.Contract; using Yue.Bookings.Model; using Yue.Common.Repository; using Dapper; using Yue.Bookings.Handler; using Yue.Bookings.Repository.Model; using Yue.Bookings.Contract.Commands; namespace Yue.Bookings.Repository.Write { public class BookingWriteRepository : BaseRepository, IBookingWriteRepository { public BookingWriteRepository(SqlOption option) : base(option) { } private static readonly string[] _bookingColumns = new string[] { "BookingId", "ResourceId", "State", "From", "To", "Minutes", "CreateBy", "UpdateBy", "CreateAt", "UpdateAt" }; private static readonly string[] _bookingUpdateColumns = new string[] { "State", "From", "To", "Minutes", "UpdateBy", "UpdateAt" }; private static readonly string[] _activityColumns = new string[] { "ActivityId", "ResourceId", "BookingId", "CreateBy", "CreateAt", "Type", "From", "To", "Minutes", "Message" }; public Booking GetForUpdate(int bookingId) { using (IDbConnection connection = OpenConnection()) { var booking = connection.Query<BookingPM>( string.Format(@"SELECT {0} FROM `bookings` WHERE `BookingId` = @BookingId FOR UPDATE;", SqlHelper.Columns(_bookingColumns)), new { BookingId = bookingId }).SingleOrDefault(); if (booking == null) return null; return BookingPM.FromPM(booking); } } public bool Add(Booking booking) { using (IDbConnection connection = OpenConnection()) { return 1 == connection.Execute( string.Format(@"INSERT INTO `bookings` ({0}) VALUES ({1});", SqlHelper.Columns(_bookingColumns), SqlHelper.Params(_bookingColumns)), BookingPM.ToPM(booking)); } } public bool Update(Booking booking) { using (IDbConnection connection = OpenConnection()) { return 1 == connection.Execute( string.Format(@"UPDATE `bookings` SET {0} WHERE `BookingId` = @BookingId;", SqlHelper.Sets(_bookingUpdateColumns)), BookingPM.ToPM(booking)); } } public bool AddAction(BookingCommandBase activity) { using (IDbConnection connection = OpenConnection()) { return 1 == connection.Execute( string.Format(@"INSERT INTO `booking_activities` ({0}) VALUES ({1});", SqlHelper.Columns(_activityColumns), SqlHelper.Params(_activityColumns)), BookingActivityPM.ToPM(activity)); } } } }
38.051282
110
0.581536
[ "Apache-2.0" ]
hotjk/yue
Yue.Bookings.Repository.Write/BookingWriteRepository.cs
2,970
C#
using OpenTK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyEngine { public struct Sphere { public Vector3 center; public float radius; public Sphere(Vector3 center, float radius) { this.center = center; this.radius = radius; } } }
15.952381
45
0.731343
[ "Unlicense" ]
aeroson/procedural-planets-generator
myengine/Mathematical/Sphere.cs
337
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; using UE4.MovieScene; namespace UE4.Sequencer.Native { [StructLayout( LayoutKind.Explicit, Size=384 )] internal unsafe struct MovieSceneCopyableBinding_fields { [FieldOffset(56)] public IntPtr SpawnableObjectTemplate; [FieldOffset(64)] public NativeArray Tracks; [FieldOffset(80)] public MovieSceneBinding Binding; [FieldOffset(144)] public MovieSceneSpawnable Spawnable; [FieldOffset(304)] public MovieScenePossessable Possessable; } internal unsafe struct MovieSceneCopyableBinding_methods { } internal unsafe struct MovieSceneCopyableBinding_events { } }
32.892857
68
0.7557
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/Sequencer/Native/MovieSceneCopyableBinding.cs
921
C#
using Bespoke.DynamicDnsUpdater.Client; using Bespoke.DynamicDnsUpdater.Tests.Base; using NUnit.Framework; namespace Bespoke.DynamicDnsUpdater.Tests { [TestFixture] public class IpAddressResolverTests : BaseFixture { [Test] [Ignore("Manual Test. Only valid when run locally.")] public void CanGetPublicIpAddressFromDynDns() { var resolver = new IpAddressResolver(); var ip = resolver.GetPublicIpAddressFromDynDns(); Assert.AreEqual(ExpectedPublicIpAddress, ip); } [Test] [Ignore("Manual Test. Only valid when run locally.")] public void CanGetPublicIpAddressFromDnsOMatic() { var resolver = new IpAddressResolver(); var ip = resolver.GetPublicIpAddressFromDnsOMatic(); Assert.AreEqual(ExpectedPublicIpAddress, ip); } [Test] public void CanGetIpAddressForHostname() { var resolver = new IpAddressResolver(); var ip = resolver.GetIpAddressForHostname("bespokeindustries.com"); Assert.AreEqual("204.246.37.132", ip); } [Test] public void GetIpAddressForInvalidHostnameReturnsNull() { var resolver = new IpAddressResolver(); var ip = resolver.GetIpAddressForHostname("bogus93937329923.bespokeindustries.com"); Assert.IsNull(ip); } } }
27.979592
97
0.661561
[ "MIT", "Unlicense" ]
dmarchelya/BespokeDynamicDnsUpdater
Source/Tests/Bespoke.DynamicDnsUpdater.Tests/IpAddressResolverTests.cs
1,373
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementNotStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchBody { [OutputConstructor] private WebAclRuleStatementNotStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchBody() { } } }
32.090909
139
0.776204
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementNotStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchBody.cs
706
C#
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; using System.ServiceModel.Syndication; using System.Linq; namespace Firehose.Web.Authors { public class JamesMontemagno : IWorkAtXamarinOrMicrosoft, IFilterMyBlogPosts { public string FirstName => "James"; public string LastName => "Montemagno"; public string StateOrRegion => "Seattle, WA"; public string EmailAddress => ""; public string ShortBioOrTagLine => "is a Principal Program Manager for Mobile Developer Tools"; public Uri WebSite => new Uri("https://montemagno.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://montemagno.com/rss"); } } public string TwitterHandle => "JamesMontemagno"; public string GravatarHash => "5df4d86308e585c879c19e5f909d8bfe"; public string GitHubHandle => "jamesmontemagno"; public GeoPosition Position => new GeoPosition(47.6541770, -122.3500000); public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); } }
30.829268
103
0.677215
[ "MIT" ]
MSiccDev/planetxamarin
src/Firehose.Web/Authors/JamesMontemagno.cs
1,266
C#
using System; using System.Collections.Generic; using System.Text; namespace Data { public interface ISeedData { string URLImage(string urlImg); } }
14.25
39
0.690058
[ "MIT" ]
SeOcSa/PropertySales
Data/ISeedData.cs
173
C#
using UnityEngine; public class ConfirmDialog { private bool confirming = false, clickYes = false, clickNo = false; private Rect confirmRect; private float buttonWidth = 50, buttonHeight = 20, padding = 10; private Vector2 messageDimensions; private AudioClip clickSound; private AudioElement audioElement; public void StartConfirmation(AudioClip clickSound, AudioElement audioElement) { this.clickSound = clickSound; this.audioElement = audioElement; confirming = true; clickYes = false; clickNo = false; } public void EndConfirmation() { confirming = false; clickYes = false; clickNo = false; } public bool IsConfirming() { return confirming; } public bool MadeChoice() { return clickYes || clickNo; } public bool ClickedYes() { return clickYes; } public bool ClickedNo() { return clickNo; } public void Show(string message) { ShowDialog( message); } public void Show(string message, GUISkin skin) { GUI.skin = skin; ShowDialog(message); } private void ShowDialog(string message) { messageDimensions = GUI.skin.GetStyle("window").CalcSize(new GUIContent(message)); float width = messageDimensions.x + 2 * padding; float height = messageDimensions.y + buttonHeight + 2 * padding; float leftPos = Screen.width / 2 - width / 2; float topPos = Screen.height / 2 - height / 2; confirmRect = new Rect(leftPos, topPos, width, height); confirmRect = GUI.Window(0, confirmRect, Dialog, message); } private void Dialog(int windowID) { float buttonLeft = messageDimensions.x / 2 - buttonWidth - padding / 2; float buttonTop = messageDimensions.y + padding; if(GUI.Button(new Rect(buttonLeft, buttonTop, buttonWidth, buttonHeight), "Yes")) { PlayClick(); confirming = false; clickYes = true; } buttonLeft += buttonWidth + padding; if(GUI.Button(new Rect(buttonLeft,buttonTop,buttonWidth,buttonHeight),"No")) { PlayClick(); confirming = false; clickNo = true; } } private void PlayClick() { if(audioElement != null) audioElement.Play(clickSound); } }
30.5
91
0.602869
[ "MIT" ]
andreidanstanescu/RTS
BetarStarcraft/Assets/Menu/ConfirmDialog.cs
2,440
C#
using UnityEngine; using System.Collections; public class SitOnTheGround : MonoBehaviour { void Update () { Node closestNode = Grid.GridInstance.NodeFromWorldPoint (transform.position); transform.position = Vector3.MoveTowards (transform.position, closestNode.worldPosition - Vector3.up * 5, 1f); } }
29.090909
114
0.75
[ "MIT" ]
Portmanteur/Procedural-Landmass-Generation
Assets/Scripts/SitOnTheGround.cs
320
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BetsApi_Business.Interfaces { public interface IModelMapper<T, U> where T : class where U : class { /// <summary> /// Purpose: Return a converted Entity Framework Model to a View Model. /// </summary> /// <param name="ef"></param> /// <returns>ViewModel</returns> public U EFToView(T ef); /// <summary> /// Purpose: Return a View Model to an Entity Framework Model by searching the Database. /// </summary> /// <param name="view"></param> /// <returns>Entity Framework Model</returns> public Task<T> ViewToEF(U view); } }
32.782609
96
0.618037
[ "MIT" ]
Not-Fight-Club/not-fight-club-bets
BetsApi_Business/Interfaces/IModelMapper.cs
756
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Outlining; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name("Outlining Command Handler")] internal sealed class OutliningCommandHandler : ICommandHandler<StartAutomaticOutliningCommandArgs> { private readonly IOutliningManagerService _outliningManagerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OutliningCommandHandler(IOutliningManagerService outliningManagerService) => _outliningManagerService = outliningManagerService; public string DisplayName => EditorFeaturesResources.Outlining; public bool ExecuteCommand(StartAutomaticOutliningCommandArgs args, CommandExecutionContext context) { // The editor actually handles this command, we just have to make sure it is enabled. return false; } public CommandState GetCommandState(StartAutomaticOutliningCommandArgs args) { var outliningManager = _outliningManagerService.GetOutliningManager(args.TextView); var enabled = false; if (outliningManager != null) { enabled = outliningManager.Enabled; } return new CommandState(isAvailable: !enabled); } } }
38.2
108
0.734555
[ "MIT" ]
AlekseyTs/roslyn
src/EditorFeatures/Core.Wpf/Structure/OutliningCommandHandler.cs
1,912
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="VectorFieldVisual3D.cs" company="Helix 3D Toolkit"> // http://helixtoolkit.codeplex.com, license: MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf { using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// A visual element that shows a vector field. /// </summary> public class VectorFieldVisual3D : ModelVisual3D { /// <summary> /// The model. /// </summary> private readonly ModelVisual3D model; /// <summary> /// The body geometry. /// </summary> private MeshGeometry3D body; /// <summary> /// The head geometry. /// </summary> private MeshGeometry3D head; /// <summary> /// Initializes a new instance of the <see cref = "VectorFieldVisual3D" /> class. /// </summary> public VectorFieldVisual3D() { this.Positions = new Point3DCollection(); this.Directions = new Vector3DCollection(); this.Fill = Brushes.Blue; this.ThetaDiv = 37; this.Diameter = 1; this.HeadLength = 2; this.model = new ModelVisual3D(); this.Children.Add(this.model); } /// <summary> /// Gets or sets the diameter. /// </summary> /// <value>The diameter.</value> public double Diameter { get; set; } /// <summary> /// Gets or sets the directions. /// </summary> /// <value>The directions.</value> public Vector3DCollection Directions { get; set; } /// <summary> /// Gets or sets the fill. /// </summary> /// <value>The fill.</value> public Brush Fill { get; set; } /// <summary> /// Gets or sets the length of the head. /// </summary> /// <value>The length of the head.</value> public double HeadLength { get; set; } /// <summary> /// Gets or sets the positions. /// </summary> /// <value>The positions.</value> public Point3DCollection Positions { get; set; } /// <summary> /// Gets or sets the number of divisions of the arrows. /// </summary> /// <value>The theta div.</value> public int ThetaDiv { get; set; } /// <summary> /// Updates the model. /// </summary> public void UpdateModel() { this.CreateGeometry(); var c = new Model3DGroup(); var mat = MaterialHelper.CreateMaterial(this.Fill); double l = this.HeadLength * this.Diameter; for (int i = 0; i < this.Positions.Count; i++) { var p = this.Positions[i]; var d = this.Directions[i]; var headModel = new GeometryModel3D { Geometry = this.head, Material = mat, Transform = CreateHeadTransform(p + d, d) }; c.Children.Add(headModel); var u = d; u.Normalize(); var bodyModel = new GeometryModel3D { Geometry = this.body, Material = mat, Transform = CreateBodyTransform(p, u * (1.0 - l / d.Length)) }; c.Children.Add(bodyModel); } this.model.Content = c; } /// <summary> /// The create body transform. /// </summary> /// <param name="p"> /// The p. /// </param> /// <param name="z"> /// The z. /// </param> /// <returns> /// </returns> private static Transform3D CreateBodyTransform(Point3D p, Vector3D z) { double length = z.Length; z.Normalize(); var x = z.FindAnyPerpendicular(); x.Normalize(); var y = Vector3D.CrossProduct(z, x); var mat = new Matrix3D( x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X * length, z.Y * length, z.Z * length, 0, p.X, p.Y, p.Z, 1); return new MatrixTransform3D(mat); } /// <summary> /// The create head transform. /// </summary> /// <param name="p"> /// The p. /// </param> /// <param name="z"> /// The z. /// </param> /// <returns> /// </returns> private static Transform3D CreateHeadTransform(Point3D p, Vector3D z) { z.Normalize(); var x = z.FindAnyPerpendicular(); x.Normalize(); var y = Vector3D.CrossProduct(z, x); var mat = new Matrix3D(x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0, p.X, p.Y, p.Z, 1); return new MatrixTransform3D(mat); } /// <summary> /// The create geometry. /// </summary> private void CreateGeometry() { double r = this.Diameter / 2; double l = this.HeadLength * this.Diameter; // arrowhead var pc = new PointCollection { new Point(-l, r), new Point(-l, r * 2), new Point(0, 0) }; var headBuilder = new MeshBuilder(false, false); headBuilder.AddRevolvedGeometry(pc, null, new Point3D(0, 0, 0), new Vector3D(0, 0, 1), this.ThetaDiv); this.head = headBuilder.ToMesh(); this.head.Freeze(); // body pc = new PointCollection { new Point(0, 0), new Point(0, r), new Point(1, r) }; var bodyBuilder = new MeshBuilder(false, false); bodyBuilder.AddRevolvedGeometry(pc, null, new Point3D(0, 0, 0), new Vector3D(0, 0, 1), this.ThetaDiv); this.body = bodyBuilder.ToMesh(); this.body.Freeze(); } } }
33.139175
121
0.452636
[ "MIT" ]
smallholexu/helix-toolkit
Source/HelixToolkit.Wpf/Visual3Ds/Composite/VectorFieldVisual3D.cs
6,431
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class ATests { [TestMethod] public void TestMethod1() { const string input = @"2 11 4"; const string output = @"4"; Tester.InOutTest(() => Tasks.A.Solve(), input, output); } [TestMethod] public void TestMethod2() { const string input = @"3 9 5"; const string output = @"3"; Tester.InOutTest(() => Tasks.A.Solve(), input, output); } [TestMethod] public void TestMethod3() { const string input = @"100 1 10"; const string output = @"0"; Tester.InOutTest(() => Tasks.A.Solve(), input, output); } } }
24.515152
67
0.500618
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC120/Tests/ATests.cs
809
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add Extensions\MyQuantityExtensions.cs to decorate quantities with new behavior. // Add UnitDefinitions\MyQuantity.json and run GeneratUnits.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet // // 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. // ReSharper disable once CheckNamespace namespace UnitsNet.Units { // Disable missing XML comment warnings for the generated unit enums. #pragma warning disable 1591 public enum LuminousIntensityUnit { Undefined = 0, Candela, } #pragma warning restore 1591 }
44.660377
104
0.693283
[ "MIT" ]
AlexejLiebenthal/UnitsNet
UnitsNet/GeneratedCode/Units/LuminousIntensityUnit.g.cs
2,369
C#
using manager.web.api.model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace manager.web.api.manager { public interface IJobManager { void SaveJob(JobItem job); } }
17.571429
34
0.727642
[ "Apache-2.0" ]
eswk22/dark-ninja
manager.web.api/manager/IJobManager.cs
248
C#
/* * The MIT License * * Copyright 2019 Palmtree Software. * * 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.Collections.Generic; using System.Linq; using System.Numerics; namespace Palmtree.Math.CodeGen.TestData.Plugin.Sint { class TestDataRendererPlugin_OneComplement_UX : TestDataRendererPluginBase_1_1 { public TestDataRendererPlugin_OneComplement_UX() : base("sint", "test_data_onecomplement_ux.xml") { } protected override IEnumerable<TestDataItemContainer> TestDataItems { get { return (UBigIntDataSource .Select(p1 => new { p1 = (IDataItem)new UBigIntDataItem(p1), r1 = (IDataItem)new BigIntDataItem(~p1), }) .Zip(Enumerable.Range(0, int.MaxValue), (item, index) => new TestDataItemContainer { Index = index, Param1 = item.p1, Result1 = item.r1, })); } } } } /* * END OF FILE */
35.015152
80
0.605798
[ "MIT" ]
rougemeilland/Palmtree.Math
Palmtree.Math.CodeGen.TestData/Plugin/Sint/TestDataRendererPlugin_OneComplement_UX.cs
2,313
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.MWAA")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AmazonMWAA. (New Service) Amazon MWAA is a managed service for Apache Airflow that makes it easy for data engineers and data scientists to execute data processing workflows in the cloud.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AmazonMWAA. (New Service) Amazon MWAA is a managed service for Apache Airflow that makes it easy for data engineers and data scientists to execute data processing workflows in the cloud.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AmazonMWAA. (New Service) Amazon MWAA is a managed service for Apache Airflow that makes it easy for data engineers and data scientists to execute data processing workflows in the cloud.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AmazonMWAA. (New Service) Amazon MWAA is a managed service for Apache Airflow that makes it easy for data engineers and data scientists to execute data processing workflows in the cloud.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AmazonMWAA. (New Service) Amazon MWAA is a managed service for Apache Airflow that makes it easy for data engineers and data scientists to execute data processing workflows in the cloud.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.5.0.20")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
56.90566
279
0.76061
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/MWAA/Properties/AssemblyInfo.cs
3,016
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelectionManager : MonoBehaviour { [SerializeField] private Material highlightMaterial; [SerializeField] private string selectableTag = "Selectable"; [SerializeField] private Material standardMaterial; private Transform _selection; private Transform _start; private bool isScalable = false; public GameObject SferaFirma; public GameObject Cornice; private bool wasIn = false; private Transform selectionScale; private int scalingFramesLeft = 100; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if(_selection != null){ var selectionRender = _selection.GetComponent<Renderer>(); selectionRender.material = standardMaterial; // _selection.transform.localScale = new Vector3 (1.3f,1.3f,1.3f); scalingFramesLeft = 100; _selection = null; } var ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); RaycastHit hit; if(Physics.Raycast(ray,out hit)){ var selection = hit.transform; if(selection.CompareTag(selectableTag)){ wasIn = true; var selectionRender = selection.GetComponent<Renderer>(); selectionScale = selection.GetComponent<Transform>(); if(selectionRender != null) { selectionRender.material = highlightMaterial; if (scalingFramesLeft > 0) { hit.transform.localScale = new Vector3( Mathf.Lerp (selection.transform.localScale.x, 1.8f, Time.deltaTime *10),Mathf.Lerp (selection.transform.localScale.y, 1.8f, Time.deltaTime *10 ),Mathf.Lerp (selection.transform.localScale.z, 1.8f, Time.deltaTime * 10 )); scalingFramesLeft--; } } _selection = selection; } else if(wasIn == true){ selectionScale.localScale = new Vector3 (1.3f,1.3f,1.3f); wasIn = false; } } } }
30.131579
273
0.59083
[ "MIT" ]
davidmarro1234/forumArUnity
Assets/Scripts/SelectionManager.cs
2,292
C#
using CadEditor; using System; using System.Drawing; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x1df21, 22 , 11*16+64, 11, 16); } public bool getScreenVertical() { return true; } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return getVideoAddress; } public GetVideoChunkFunc getVideoChunkFunc() { return getVideoChunk; } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x195e1, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0x1dee1; } public GetBlocksFunc getBlocksFunc() { return getBlocks;} public SetBlocksFunc setBlocksFunc() { return setBlocks;} public GetPalFunc getPalFunc() { return getPallete;} public SetPalFunc setPalFunc() { return null;} //---------------------------------------------------------------------------- public static ObjRec[] getBlocks(int tileId) { int count = ConfigScript.getBlocksCount(tileId); var bb = Utils.readBlocksLinear(Globals.romdata, ConfigScript.getTilesAddr(tileId), 2, 2, count, false, false); var palAddr = ConfigScript.getPalBytesAddr(tileId); return bb; } public static void setBlocks(int tileId, ObjRec[] blocksData) { int addr = ConfigScript.getTilesAddr(tileId); int count = ConfigScript.getBlocksCount(tileId); var palAddr = ConfigScript.getPalBytesAddr(tileId); Utils.writeBlocksLinear(blocksData, Globals.romdata, addr, count, false, false); } public byte[] getPallete(int palId) { return Utils.readBinFile("pal1(boss).bin"); } public int getVideoAddress(int id) { return -1; } public byte[] getVideoChunk(int videoPageId) { return Utils.readVideoBankFromFile("chr1(boss).bin", videoPageId); } }
37.466667
117
0.661477
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/youkai_club/Settings_YoukaiClub-1(j).cs
2,248
C#
using System; using System.Collections.Generic; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Querying; namespace Umbraco.Core.Persistence.Repositories { public interface IContentTypeRepository : IContentTypeCompositionRepository<IContentType> { /// <summary> /// Given the path of a content item, this will return true if the content item exists underneath a list view content item /// </summary> /// <param name="contentPath"></param> /// <returns></returns> bool HasContainerInPath(string contentPath); /// <summary> /// Gets all entities of the specified <see cref="PropertyType"/> query /// </summary> /// <param name="query"></param> /// <returns>An enumerable list of <see cref="IContentType"/> objects</returns> IEnumerable<IContentType> GetByQuery(IQuery<PropertyType> query); /// <summary> /// Gets all property type aliases. /// </summary> /// <returns></returns> IEnumerable<string> GetAllPropertyTypeAliases(); IEnumerable<MoveEventInfo<IContentType>> Move(IContentType toMove, EntityContainer container); /// <summary> /// Gets all content type aliases /// </summary> /// <param name="objectTypes"> /// If this list is empty, it will return all content type aliases for media, members and content, otherwise /// it will only return content type aliases for the object types specified /// </param> /// <returns></returns> IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes); /// <summary> /// Derives a unique alias from an existing alias. /// </summary> /// <param name="alias">The original alias.</param> /// <returns>The original alias with a number appended to it, so that it is unique.</returns> /// /// <remarks>Unique accross all content, media and member types.</remarks> string GetUniqueAlias(string alias); IEnumerable<int> GetAllContentTypeIds(string[] aliases); } }
40.54717
130
0.64402
[ "MIT" ]
filipesousa20/Umbraco-CMS-V7
src/Umbraco.Core/Persistence/Repositories/Interfaces/IContentTypeRepository.cs
2,151
C#
namespace PromotionEngine { public class ProductModel { public string ProductName { get; set; } public int ProductPrice { get; set; } } }
16.8
47
0.613095
[ "MIT" ]
sohampal/Promotion_Engine
PromotionEngine/PromotionEngine/ProductModel.cs
170
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Mysoft.TaskScheduler.Models { /// <summary> /// 任务标识对象模型 /// </summary> [Serializable] internal class TaskIdentity { /// <summary> /// 执行任务Id /// </summary> [JsonProperty] public string DoId { get; internal set; } /// <summary> /// 回滚任务Id /// </summary> [JsonProperty] public string UndoId { get; internal set; } } }
19.555556
51
0.554924
[ "Apache-2.0" ]
MysoftEOP/Mysoft.TaskScheduler
src/Mysoft.TaskScheduler/Models/TaskIdentity.cs
562
C#
using Socean.Rpc.Core; using Socean.Rpc.Core.Client; using Socean.Rpc.Core.Message; using System; namespace Socean.Rpc.DynamicProxy { internal static class FastRpcClientExtention { internal static object QueryInternal(this FastRpcClient fastRpcClient, string title, ICustomTuple customTuple, Type returnType, IBinarySerializer serializer, string extention = null, bool throwIfErrorResponseCode = true) { if (serializer == null) throw new ArgumentNullException(nameof(serializer)); if (customTuple == null) throw new ArgumentNullException(nameof(customTuple)); var encoding = NetworkSettings.TitleExtentionEncoding; var response = fastRpcClient.Query( encoding.GetBytes(title), serializer.Serialize(customTuple), extention == null ? FrameFormat.EmptyBytes : encoding.GetBytes(extention), throwIfErrorResponseCode); if (returnType == typeof(void)) return null; if (response.ContentBytes == null) return null; return serializer.Deserialize(response.ContentBytes, returnType); } } }
34.305556
228
0.646154
[ "MIT" ]
ch00486259/Socean.Rpc
src/Socean.Rpc/DynamicProxy/FastRpcClientExtention.cs
1,237
C#
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; namespace Spine.Unity.Editor { public static class SpineInspectorUtility { public static string Pluralize (int n, string singular, string plural) { return n + " " + (n == 1 ? singular : plural); } public static string PluralThenS (int n) { return n == 1 ? "" : "s"; } public static string EmDash { get { return "\u2014"; } } static GUIContent tempContent; internal static GUIContent TempContent (string text, Texture2D image = null, string tooltip = null) { if (tempContent == null) tempContent = new GUIContent(); tempContent.text = text; tempContent.image = image; tempContent.tooltip = tooltip; return tempContent; } public static void PropertyFieldWideLabel (SerializedProperty property, GUIContent label = null, float minimumLabelWidth = 150) { EditorGUIUtility.labelWidth = minimumLabelWidth; EditorGUILayout.PropertyField(property, label ?? TempContent(property.displayName, null, property.tooltip)); EditorGUIUtility.labelWidth = 0; // Resets to default } public static void PropertyFieldFitLabel (SerializedProperty property, GUIContent label = null, float extraSpace = 5f) { label = label ?? TempContent(property.displayName, null, property.tooltip); float width = GUI.skin.label.CalcSize(TempContent(label.text)).x + extraSpace; if (label.image != null) width += EditorGUIUtility.singleLineHeight; PropertyFieldWideLabel(property, label, width); } public static bool UndoRedoPerformed (UnityEngine.Event current) { return current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed"; } public static Texture2D UnityIcon<T>() { return EditorGUIUtility.ObjectContent(null, typeof(T)).image as Texture2D; } public static Texture2D UnityIcon(System.Type type) { return EditorGUIUtility.ObjectContent(null, type).image as Texture2D; } #region SerializedProperty Helpers public static SerializedProperty FindBaseOrSiblingProperty (this SerializedProperty property, string propertyName) { if (string.IsNullOrEmpty(propertyName)) return null; SerializedProperty relativeProperty = property.serializedObject.FindProperty(propertyName); // baseProperty if (relativeProperty == null) { // If no baseProperty, find sibling property. int nameLength = property.name.Length; string propertyPath = property.propertyPath; propertyPath = propertyPath.Remove(propertyPath.Length - nameLength, nameLength) + propertyName; relativeProperty = property.serializedObject.FindProperty(propertyPath); } return relativeProperty; } #endregion #region Layout Scopes static GUIStyle grayMiniLabel; public static GUIStyle GrayMiniLabel { get { if (grayMiniLabel == null) { grayMiniLabel = new GUIStyle(EditorStyles.centeredGreyMiniLabel); grayMiniLabel.alignment = TextAnchor.UpperLeft; } return grayMiniLabel; } } public class LabelWidthScope : System.IDisposable { public LabelWidthScope (float minimumLabelWidth = 190f) { EditorGUIUtility.labelWidth = minimumLabelWidth; } public void Dispose () { EditorGUIUtility.labelWidth = 0f; } } public class IndentScope : System.IDisposable { public IndentScope () { EditorGUI.indentLevel++; } public void Dispose () { EditorGUI.indentLevel--; } } public class BoxScope : System.IDisposable { readonly bool indent; static GUIStyle boxScopeStyle; public static GUIStyle BoxScopeStyle { get { if (boxScopeStyle == null) { boxScopeStyle = new GUIStyle(EditorStyles.helpBox); var p = boxScopeStyle.padding; p.right += 6; p.top += 1; p.left += 3; } return boxScopeStyle; } } public BoxScope (bool indent = true) { this.indent = indent; EditorGUILayout.BeginVertical(BoxScopeStyle); if (indent) EditorGUI.indentLevel++; } public void Dispose () { if (indent) EditorGUI.indentLevel--; EditorGUILayout.EndVertical(); } } #endregion #region Button const float CenterButtonMaxWidth = 270f; const float CenterButtonHeight = 35f; static GUIStyle spineButtonStyle; static GUIStyle SpineButtonStyle { get { if (spineButtonStyle == null) { spineButtonStyle = new GUIStyle(GUI.skin.button); spineButtonStyle.name = "Spine Button"; spineButtonStyle.padding = new RectOffset(10, 10, 10, 10); } return spineButtonStyle; } } public static bool LargeCenteredButton (string label, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { if (sideSpace) { bool clicked; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.Space(); clicked = GUILayout.Button(label, SpineButtonStyle, GUILayout.MaxWidth(maxWidth), GUILayout.Height(CenterButtonHeight)); EditorGUILayout.Space(); } EditorGUILayout.Space(); return clicked; } else { return GUILayout.Button(label, GUILayout.MaxWidth(CenterButtonMaxWidth), GUILayout.Height(CenterButtonHeight)); } } public static bool LargeCenteredButton (GUIContent content, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { if (sideSpace) { bool clicked; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.Space(); clicked = GUILayout.Button(content, SpineButtonStyle, GUILayout.MaxWidth(maxWidth), GUILayout.Height(CenterButtonHeight)); EditorGUILayout.Space(); } EditorGUILayout.Space(); return clicked; } else { return GUILayout.Button(content, GUILayout.MaxWidth(CenterButtonMaxWidth), GUILayout.Height(CenterButtonHeight)); } } public static bool CenteredButton (GUIContent content, float height = 20f, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { if (sideSpace) { bool clicked; using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.Space(); clicked = GUILayout.Button(content, GUILayout.MaxWidth(maxWidth), GUILayout.Height(height)); EditorGUILayout.Space(); } EditorGUILayout.Space(); return clicked; } else { return GUILayout.Button(content, GUILayout.MaxWidth(maxWidth), GUILayout.Height(height)); } } #endregion #region Multi-Editing Helpers public static bool TargetsUseSameData (SerializedObject so) { if (so.isEditingMultipleObjects) { int n = so.targetObjects.Length; var first = so.targetObjects[0] as ISkeletonComponent; for (int i = 1; i < n; i++) { var sr = so.targetObjects[i] as ISkeletonComponent; if (sr != null && sr.SkeletonDataAsset != first.SkeletonDataAsset) return false; } } return true; } public static SerializedObject GetRenderersSerializedObject (SerializedObject serializedObject) { if (serializedObject.isEditingMultipleObjects) { var renderers = new List<Object>(); foreach (var o in serializedObject.targetObjects) { var component = o as Component; if (component != null) { var renderer = component.GetComponent<Renderer>(); if (renderer != null) renderers.Add(renderer); } } return new SerializedObject(renderers.ToArray()); } else { var component = serializedObject.targetObject as Component; if (component != null) { var renderer = component.GetComponent<Renderer>(); if (renderer != null) return new SerializedObject(renderer); } } return null; } #endregion #region Sorting Layer Field Helpers static readonly GUIContent SortingLayerLabel = new GUIContent("Sorting Layer", "MeshRenderer.sortingLayerID"); static readonly GUIContent OrderInLayerLabel = new GUIContent("Order in Layer", "MeshRenderer.sortingOrder"); static MethodInfo m_SortingLayerFieldMethod; static MethodInfo SortingLayerFieldMethod { get { if (m_SortingLayerFieldMethod == null) m_SortingLayerFieldMethod = typeof(EditorGUILayout).GetMethod("SortingLayerField", BindingFlags.Static | BindingFlags.NonPublic, null, new [] { typeof(GUIContent), typeof(SerializedProperty), typeof(GUIStyle) }, null); return m_SortingLayerFieldMethod; } } public struct SerializedSortingProperties { public SerializedObject renderer; public SerializedProperty sortingLayerID; public SerializedProperty sortingOrder; public SerializedSortingProperties (Renderer r) : this(new SerializedObject(r)) {} public SerializedSortingProperties (Object[] renderers) : this(new SerializedObject(renderers)) {} /// <summary> /// Initializes a new instance of the /// <see cref="Spine.Unity.Editor.SpineInspectorUtility.SerializedSortingProperties"/> struct. /// </summary> /// <param name="rendererSerializedObject">SerializedObject of the renderer. Use /// <see cref="Spine.Unity.Editor.SpineInspectorUtility.GetRenderersSerializedObject"/> to easily generate this.</param> public SerializedSortingProperties (SerializedObject rendererSerializedObject) { renderer = rendererSerializedObject; sortingLayerID = renderer.FindProperty("m_SortingLayerID"); sortingOrder = renderer.FindProperty("m_SortingOrder"); } public void ApplyModifiedProperties () { renderer.ApplyModifiedProperties(); // SetDirty if (renderer.isEditingMultipleObjects) foreach (var o in renderer.targetObjects) EditorUtility.SetDirty(o); else EditorUtility.SetDirty(renderer.targetObject); } } public static void SortingPropertyFields (SerializedSortingProperties prop, bool applyModifiedProperties) { if (applyModifiedProperties) EditorGUI.BeginChangeCheck(); if (SpineInspectorUtility.SortingLayerFieldMethod != null && prop.sortingLayerID != null) SpineInspectorUtility.SortingLayerFieldMethod.Invoke(null, new object[] { SortingLayerLabel, prop.sortingLayerID, EditorStyles.popup } ); else EditorGUILayout.PropertyField(prop.sortingLayerID); EditorGUILayout.PropertyField(prop.sortingOrder, OrderInLayerLabel); if (applyModifiedProperties && EditorGUI.EndChangeCheck()) prop.ApplyModifiedProperties(); } #endregion } }
38.386293
224
0.706379
[ "MIT" ]
sgaumin/Magic_Kitchen
Assets/MyLibrary/spine-unity/Assets/spine-unity/Editor/SpineInspectorUtility.cs
12,322
C#
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Lucene.Net.Util.Automaton { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using PrefixTermsEnum = Lucene.Net.Search.PrefixTermsEnum; using SingleTermsEnum = Lucene.Net.Index.SingleTermsEnum; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Immutable class holding compiled details for a given /// <see cref="Automaton"/>. The <see cref="Automaton"/> is deterministic, must not have /// dead states but is not necessarily minimal. /// <para/> /// @lucene.experimental /// </summary> public class CompiledAutomaton { /// <summary> /// Automata are compiled into different internal forms for the /// most efficient execution depending upon the language they accept. /// </summary> public enum AUTOMATON_TYPE { /// <summary> /// Automaton that accepts no strings. </summary> NONE, /// <summary> /// Automaton that accepts all possible strings. </summary> ALL, /// <summary> /// Automaton that accepts only a single fixed string. </summary> SINGLE, /// <summary> /// Automaton that matches all strings with a constant prefix. </summary> PREFIX, /// <summary> /// Catch-all for any other automata. </summary> NORMAL } public AUTOMATON_TYPE Type { get; private set; } /// <summary> /// For <see cref="AUTOMATON_TYPE.PREFIX"/>, this is the prefix term; /// for <see cref="AUTOMATON_TYPE.SINGLE"/> this is the singleton term. /// </summary> public BytesRef Term { get; private set; } /// <summary> /// Matcher for quickly determining if a <see cref="T:byte[]"/> is accepted. /// only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>. /// </summary> public ByteRunAutomaton RunAutomaton { get; private set; } // TODO: would be nice if these sortedTransitions had "int // to;" instead of "State to;" somehow: /// <summary> /// Two dimensional array of transitions, indexed by state /// number for traversal. The state numbering is consistent with /// <see cref="RunAutomaton"/>. /// <para/> /// Only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>. /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public Transition[][] SortedTransitions => sortedTransitions; private readonly Transition[][] sortedTransitions; /// <summary> /// Shared common suffix accepted by the automaton. Only valid /// for <see cref="AUTOMATON_TYPE.NORMAL"/>, and only when the /// automaton accepts an infinite language. /// </summary> public BytesRef CommonSuffixRef { get; private set; } /// <summary> /// Indicates if the automaton accepts a finite set of strings. /// Null if this was not computed. /// Only valid for <see cref="AUTOMATON_TYPE.NORMAL"/>. /// </summary> public bool? Finite { get; private set; } public CompiledAutomaton(Automaton automaton) : this(automaton, null, true) { } public CompiledAutomaton(Automaton automaton, bool? finite, bool simplify) { if (simplify) { // Test whether the automaton is a "simple" form and // if so, don't create a runAutomaton. Note that on a // large automaton these tests could be costly: if (BasicOperations.IsEmpty(automaton)) { // matches nothing Type = AUTOMATON_TYPE.NONE; Term = null; CommonSuffixRef = null; RunAutomaton = null; sortedTransitions = null; this.Finite = null; return; } else if (BasicOperations.IsTotal(automaton)) { // matches all possible strings Type = AUTOMATON_TYPE.ALL; Term = null; CommonSuffixRef = null; RunAutomaton = null; sortedTransitions = null; this.Finite = null; return; } else { string commonPrefix; string singleton; if (automaton.Singleton == null) { commonPrefix = SpecialOperations.GetCommonPrefix(automaton); if (commonPrefix.Length > 0 && BasicOperations.SameLanguage(automaton, BasicAutomata.MakeString(commonPrefix))) { singleton = commonPrefix; } else { singleton = null; } } else { commonPrefix = null; singleton = automaton.Singleton; } if (singleton != null) { // matches a fixed string in singleton or expanded // representation Type = AUTOMATON_TYPE.SINGLE; Term = new BytesRef(singleton); CommonSuffixRef = null; RunAutomaton = null; sortedTransitions = null; this.Finite = null; return; } else if (BasicOperations.SameLanguage(automaton, BasicOperations.Concatenate(BasicAutomata.MakeString(commonPrefix), BasicAutomata.MakeAnyString()))) { // matches a constant prefix Type = AUTOMATON_TYPE.PREFIX; Term = new BytesRef(commonPrefix); CommonSuffixRef = null; RunAutomaton = null; sortedTransitions = null; this.Finite = null; return; } } } Type = AUTOMATON_TYPE.NORMAL; Term = null; if (finite == null) { this.Finite = SpecialOperations.IsFinite(automaton); } else { this.Finite = finite; } Automaton utf8 = (new UTF32ToUTF8()).Convert(automaton); if (this.Finite == true) { CommonSuffixRef = null; } else { CommonSuffixRef = SpecialOperations.GetCommonSuffixBytesRef(utf8); } RunAutomaton = new ByteRunAutomaton(utf8, true); sortedTransitions = utf8.GetSortedTransitions(); } //private static final boolean DEBUG = BlockTreeTermsWriter.DEBUG; private BytesRef AddTail(int state, BytesRef term, int idx, int leadLabel) { // Find biggest transition that's < label // TODO: use binary search here Transition maxTransition = null; foreach (Transition transition in sortedTransitions[state]) { if (transition.min < leadLabel) { maxTransition = transition; } } Debug.Assert(maxTransition != null); // Append floorLabel int floorLabel; if (maxTransition.max > leadLabel - 1) { floorLabel = leadLabel - 1; } else { floorLabel = maxTransition.max; } if (idx >= term.Bytes.Length) { term.Grow(1 + idx); } //if (DEBUG) System.out.println(" add floorLabel=" + (char) floorLabel + " idx=" + idx); term.Bytes[idx] = (byte)floorLabel; state = maxTransition.to.Number; idx++; // Push down to last accept state while (true) { Transition[] transitions = sortedTransitions[state]; if (transitions.Length == 0) { Debug.Assert(RunAutomaton.IsAccept(state)); term.Length = idx; //if (DEBUG) System.out.println(" return " + term.utf8ToString()); return term; } else { // We are pushing "top" -- so get last label of // last transition: Debug.Assert(transitions.Length != 0); Transition lastTransition = transitions[transitions.Length - 1]; if (idx >= term.Bytes.Length) { term.Grow(1 + idx); } //if (DEBUG) System.out.println(" push maxLabel=" + (char) lastTransition.max + " idx=" + idx); term.Bytes[idx] = (byte)lastTransition.max; state = lastTransition.to.Number; idx++; } } } // TODO: should this take startTerm too? this way // Terms.intersect could forward to this method if type != // NORMAL: public virtual TermsEnum GetTermsEnum(Terms terms) { switch (Type) { case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.NONE: return TermsEnum.EMPTY; case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.ALL: return terms.GetIterator(null); case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.SINGLE: return new SingleTermsEnum(terms.GetIterator(null), Term); case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.PREFIX: // TODO: this is very likely faster than .intersect, // but we should test and maybe cutover return new PrefixTermsEnum(terms.GetIterator(null), Term); case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.NORMAL: return terms.Intersect(this, null); default: // unreachable throw new Exception("unhandled case"); } } /// <summary> /// Finds largest term accepted by this Automaton, that's /// &lt;= the provided input term. The result is placed in /// output; it's fine for output and input to point to /// the same <see cref="BytesRef"/>. The returned result is either the /// provided output, or <c>null</c> if there is no floor term /// (ie, the provided input term is before the first term /// accepted by this <see cref="Automaton"/>). /// </summary> public virtual BytesRef Floor(BytesRef input, BytesRef output) { output.Offset = 0; //if (DEBUG) System.out.println("CA.floor input=" + input.utf8ToString()); int state = RunAutomaton.InitialState; // Special case empty string: if (input.Length == 0) { if (RunAutomaton.IsAccept(state)) { output.Length = 0; return output; } else { return null; } } IList<int> stack = new List<int>(); int idx = 0; while (true) { int label = ((sbyte)input.Bytes[input.Offset + idx]) & 0xff; int nextState = RunAutomaton.Step(state, label); //if (DEBUG) System.out.println(" cycle label=" + (char) label + " nextState=" + nextState); if (idx == input.Length - 1) { if (nextState != -1 && RunAutomaton.IsAccept(nextState)) { // Input string is accepted if (idx >= output.Bytes.Length) { output.Grow(1 + idx); } output.Bytes[idx] = (byte)label; output.Length = input.Length; //if (DEBUG) System.out.println(" input is accepted; return term=" + output.utf8ToString()); return output; } else { nextState = -1; } } if (nextState == -1) { // Pop back to a state that has a transition // <= our label: while (true) { Transition[] transitions = sortedTransitions[state]; if (transitions.Length == 0) { Debug.Assert(RunAutomaton.IsAccept(state)); output.Length = idx; //if (DEBUG) System.out.println(" return " + output.utf8ToString()); return output; } else if (label - 1 < transitions[0].min) { if (RunAutomaton.IsAccept(state)) { output.Length = idx; //if (DEBUG) System.out.println(" return " + output.utf8ToString()); return output; } // pop if (stack.Count == 0) { //if (DEBUG) System.out.println(" pop ord=" + idx + " return null"); return null; } else { state = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); idx--; //if (DEBUG) System.out.println(" pop ord=" + (idx+1) + " label=" + (char) label + " first trans.min=" + (char) transitions[0].min); label = input.Bytes[input.Offset + idx] & 0xff; } } else { //if (DEBUG) System.out.println(" stop pop ord=" + idx + " first trans.min=" + (char) transitions[0].min); break; } } //if (DEBUG) System.out.println(" label=" + (char) label + " idx=" + idx); return AddTail(state, output, idx, label); } else { if (idx >= output.Bytes.Length) { output.Grow(1 + idx); } output.Bytes[idx] = (byte)label; stack.Add(state); state = nextState; idx++; } } } public virtual string ToDot() { StringBuilder b = new StringBuilder("digraph CompiledAutomaton {\n"); b.Append(" rankdir = LR;\n"); int initial = RunAutomaton.InitialState; for (int i = 0; i < sortedTransitions.Length; i++) { b.Append(" ").Append(i); if (RunAutomaton.IsAccept(i)) { b.Append(" [shape=doublecircle,label=\"\"];\n"); } else { b.Append(" [shape=circle,label=\"\"];\n"); } if (i == initial) { b.Append(" initial [shape=plaintext,label=\"\"];\n"); b.Append(" initial -> ").Append(i).Append("\n"); } for (int j = 0; j < sortedTransitions[i].Length; j++) { b.Append(" ").Append(i); sortedTransitions[i][j].AppendDot(b); } } return b.Append("}\n").ToString(); } public override int GetHashCode() { const int prime = 31; int result = 1; result = prime * result + ((RunAutomaton == null) ? 0 : RunAutomaton.GetHashCode()); result = prime * result + ((Term == null) ? 0 : Term.GetHashCode()); result = prime * result + Type.GetHashCode(); //((Type == null) ? 0 : Type.GetHashCode()); // LUCENENET NOTE: Enum cannot be null in .NET return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } CompiledAutomaton other = (CompiledAutomaton)obj; if (Type != other.Type) { return false; } if (Type == AUTOMATON_TYPE.SINGLE || Type == AUTOMATON_TYPE.PREFIX) { if (!Term.Equals(other.Term)) { return false; } } else if (Type == AUTOMATON_TYPE.NORMAL) { if (!RunAutomaton.Equals(other.RunAutomaton)) { return false; } } return true; } } }
38.37451
169
0.459864
[ "Apache-2.0" ]
Ref12/lucenenet
src/Lucene.Net/Util/Automaton/CompiledAutomaton.cs
19,571
C#
/* * Copyright 2020 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://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.IO; using Amazon.IonDotnet.Internals.Text; using Amazon.IonDotnet.Tests.Common; using Amazon.IonDotnet.Builders; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Globalization; using System.Collections.Generic; namespace Amazon.IonDotnet.Tests.Internals { [TestClass] public class TextReaderTimestampTest { [TestMethod] public void Date_2000_11_20_8_20_15_Unknown() { var data = DirStructure.OwnTestFileAsBytes("text/ts_2000_11_20_8_20_15_unknown.ion"); IIonReader reader = new UserTextReader(new MemoryStream(data)); ReaderTimestampCommon.Date_2000_11_20_8_20_15_Unknown(reader); } /// <summary> /// Test the date string with >14 offset. /// </summary> /// <param name="dateString"></param> /// <param name="expectedDateString"></param> [DataRow("1857-05-30T19:24:59.1+23:59", "1857-05-29T19:25:59.1Z")] [TestMethod] public void Date_LargeOffset(string dateString, string expectedDateString) { var date = Timestamp.Parse(dateString); var expectedDate = Timestamp.Parse(expectedDateString); Assert.IsTrue(date.LocalOffset >= -14 * 60 && date.LocalOffset <= 14 * 60); Assert.IsTrue(date.Equals(expectedDate)); } /// <summary> /// Verify that timestamp parsing is not affected by the runtime's configured locale. /// </summary> /// <param name="dateString"></param> [DataRow("2020-10-21T12:37:52.086Z"), DataRow("2020-10-21T12:37:52.186Z"), DataRow("2020-10-21T12:37:00.086Z"), DataRow("2020-10-21T13:18:46.911Z"), DataRow("2020-10-21T13:18:00.911Z")] [TestMethod] public void Date_IgnoreCultureInfo(string dateString) { // Take note of the system's default culture setting so we can restore it after this test is complete CultureInfo initialCulture = CultureInfo.CurrentCulture; // Parse the timestamp using the runtime's InvariantCulture. InvariantCulture is a stable, non-customizable locale // that can be used for formatting and parsing operations that require culture-independent results. CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; var invariantCultureTimestamp = Timestamp.Parse(dateString); // Parse the timestamp again for each of the following cultures, verifying that the result is the same as it was // when we parsed it using the InvariantCulture. List<string> cultureNames = new List<string>() {"af-ZA", "en-GB", "en-US", "es-CL", "es-MX", "es-US", "ko-KR", "nl-NL", "zh-CN"}; cultureNames.ForEach(cultureName => { CultureInfo.CurrentCulture = new CultureInfo(cultureName, false); var variantCultureTimestamp = Timestamp.Parse(dateString); Assert.AreEqual(invariantCultureTimestamp, variantCultureTimestamp); }); // Restore the original culture setting so the output of subsequent tests will be written using the expected // localization. CultureInfo.CurrentCulture = initialCulture; } /// <summary> /// Test local timezone offset /// </summary> /// <param name="dateString"></param> /// <param name="expectedLocalOffset"> Time zone offset in minutes</param> /// <param name="expectedTimeOffset"></param> [DataRow("2010-10-10T03:20+02:12", +(2 * 60 + 12), 3, 20)] [DataRow("2010-10-10T03:20-02:12", -(2 * 60 + 12), 3, 20)] [DataRow("2010-10-10T03:20+00:12", +(0 * 60 + 12), 3, 20)] [DataRow("2010-10-10T03:20+02:00", +(2 * 60 + 00), 3, 20)] [TestMethod] public void TimeZone_Hour_Minute(string dateString, int expectedOffset, int expectedHour, int expectedMinute) { var date = Timestamp.Parse(dateString); var dateTimeOffset = date.AsDateTimeOffset(); Assert.AreEqual(expectedOffset, date.LocalOffset); Assert.AreEqual(expectedHour, dateTimeOffset.Hour); Assert.AreEqual(expectedMinute, dateTimeOffset.Minute); } [DataRow("2010-10-10T03:20")] [DataRow("2010-10-10T03:20:40")] [DataRow("2010-10-10T03:20:40.5")] [TestMethod] [ExpectedException(typeof(FormatException))] public void Invalid_Timestamps_Missing_Offset(string dateString) { Timestamp.Parse(dateString); } } }
43.716667
141
0.641632
[ "Apache-2.0" ]
Armanbqt/ion-dotnet
Amazon.IonDotnet.Tests/Internals/TextReaderTimestampTest.cs
5,248
C#
using System; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Logging; namespace TimerTriggerDummy { // This is a dummy class. // The purpose of this class is to force the Net SDK to generate all the configuration files // needed for running under Net 5 framework. public static class TimerTriggerDummy { [Function("TimerTrigger1")] public static void Run([TimerTrigger("0 */5 * * * *")] string myTimer, FunctionContext context) { } } }
27.833333
103
0.696607
[ "Apache-2.0" ]
genexuslabs/DotNetClasses
dotnet/src/extensions/Azure/Handlers/Dummies/TimerTriggerDummy.cs
501
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace $safeprojectname$ { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); options.ValidateOnBuild = true; }); } }
30.857143
88
0.578704
[ "MIT" ]
47-studio-org/botframework-solutions
templates/csharp/VA/VA/Program.cs
866
C#
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using TestContext = NUnit.Framework.TestContext; using Assert = NUnit.Framework.Assert; namespace CMS.Tests { /// <summary> /// Provides methods for checking the test categories /// </summary> public class TestsCategoryCheck { const string APP_KEY_EXCLUDED_CATEGORIES = "CMSTestExcludedCategories"; const string APP_KEY_RESTRICTED_CATEGORIES = "CMSTestRestrictedCategories"; private static readonly Lazy<IEnumerable<string>> mExcludedCategories = new Lazy<IEnumerable<string>>(() => GetCategoriesFromConfig(APP_KEY_EXCLUDED_CATEGORIES)); private static readonly Lazy<IEnumerable<string>> mRestrictedCategories = new Lazy<IEnumerable<string>>(() => GetCategoriesFromConfig(APP_KEY_RESTRICTED_CATEGORIES)); private static IEnumerable<string> ExcludedCategories { get { return mExcludedCategories.Value; } } private static IEnumerable<string> RestrictedCategories { get { return mRestrictedCategories.Value; } } /// <summary> /// Throw <see cref="IgnoreException"/> if current test is assigned to not restricted or excluded categories. /// </summary> internal static void CheckCategories(Type testType) { // End check if MSTest if (AutomatedTests.IsMSTest(testType)) { return; } // End check if no categories in tests config if (!ExcludedCategories.Any() && !RestrictedCategories.Any()) { return; } // Get categories assigned to current test var test = TestContext.CurrentContext.Test; var cat = test.Properties["Category"]; var currentTestCategories = cat.Cast<string>().ToArray(); // Add categories assigned to current test class and assembly var classAndAssemblyCategories = GetClassAndAssemblyCategories(testType); currentTestCategories = currentTestCategories.Concat(classAndAssemblyCategories).ToArray(); // End check if current test assigned to no category if (currentTestCategories.Any()) { return; } // Ignore test if in excluded category if (currentTestCategories.Intersect(ExcludedCategories).Any()) { Assert.Ignore("Test is assigned to excluded category."); } // Ignore test if not in restricted category if (!currentTestCategories.Intersect(RestrictedCategories).Any() && RestrictedCategories.Any()) { Assert.Ignore("Test is not assigned to any restricted category."); } } /// <summary> /// Throw <see cref="IgnoreException"/> if no test in specified class passes category check. /// </summary> /// <param name="type">Test class type</param> internal static void CheckAllTestsCategories(Type type) { // End check if MSTest if (AutomatedTests.IsMSTest(type)) { return; } // End check if not a fixture, it is wrapped by another test in that case if (!type.IsDefined(typeof(TestFixtureAttribute), true)) { return; } var classAndAssemblyCategories = GetClassAndAssemblyCategories(type).ToArray(); if (classAndAssemblyCategories.Intersect(ExcludedCategories).Any()) { Assert.Ignore("Test fixture assigned to excluded category."); } var searchForTestMethodInRestrictedCategory = (RestrictedCategories.Any() && !classAndAssemblyCategories.Intersect(RestrictedCategories).Any()); var allTestMethods = type.GetMethods() .Where(t => !t.IsDefined(typeof(IgnoreAttribute), false) && (t.IsDefined(typeof(TestAttribute), false) || t.IsDefined(typeof(TestCaseAttribute), false) || t.IsDefined(typeof(TestCaseSourceAttribute), false))) .ToArray(); // Check categories for each test method foreach (var testMethod in allTestMethods) { var categoryAttrs = (CategoryAttribute[])testMethod.GetCustomAttributes(typeof(CategoryAttribute), true); var currentTestCategories = categoryAttrs.Select(x => x.Name).ToArray(); // Class and assembly are not in restricted category if (searchForTestMethodInRestrictedCategory) { // Method is in restricted category and is not in excluded category if (!currentTestCategories.Intersect(ExcludedCategories).Any() && currentTestCategories.Intersect(RestrictedCategories).Any()) { return; } } else { // Method is not in excluded category if (!currentTestCategories.Intersect(ExcludedCategories).Any() || !categoryAttrs.Any()) { return; } } } Assert.Ignore("All tests in fixture assigned to excluded category or not assigned to restricted category."); } /// <summary> /// Performs category check for assembly set up class. /// </summary> /// <param name="type">Type of class that performs assembly set up using <see cref="SetUpFixtureAttribute"/>.</param> /// <returns>True if assembly set up is required to run.</returns> internal static bool CheckAssemblySetUp(Type type) { var setUpAttrs = type.GetCustomAttributes(typeof(SetUpFixtureAttribute), true); if (setUpAttrs.Length == 0) { return false; } var categories = GetClassCategories(type).ToArray(); // Check if in excluded categories if (categories.Intersect(ExcludedCategories).Any()) { return false; } // Check if in restricted categories return !RestrictedCategories.Any() || categories.Intersect(RestrictedCategories).Any(); } /// <summary> /// Gets categories specified in Tests.config file under given app key. /// </summary> /// <param name="keyName">Name of app key in Tests.config</param> private static IEnumerable<string> GetCategoriesFromConfig(string keyName) { string[] categories = { }; char[] separator = { ';' }; var globalTestsConfig = TestsConfig.GlobalTestsConfig; if (globalTestsConfig.HasFile) { var globalAppSettings = globalTestsConfig.AppSettings; if (globalAppSettings.Settings[keyName] != null) { categories = globalAppSettings.Settings[keyName].Value.Split(separator, StringSplitOptions.RemoveEmptyEntries); } } return categories; } /// <summary> /// Gets categories assigned to current test class and assembly. /// </summary> /// <param name="type">Test type</param> /// <returns>Categories assigned to current test class and assembly.</returns> private static IEnumerable<string> GetClassAndAssemblyCategories(Type type) { return GetClassCategories(type).Concat(GetAssemblyCategories(type)); } /// <summary> /// Gets categories assigned to current test class. /// </summary> /// <param name="type">Test type</param> /// <returns>Categories assigned to current test class.</returns> private static IEnumerable<string> GetClassCategories(Type type) { var categories = Enumerable.Empty<string>(); var classCategoryAttrs = (CategoryAttribute[])type.GetCustomAttributes(typeof(CategoryAttribute), true); if (classCategoryAttrs.Length > 0) { categories = classCategoryAttrs.Select(x => x.Name); } return categories; } /// <summary> /// Gets categories assigned to current test assembly. /// </summary> /// <param name="type">Test type</param> /// <returns>Categories assigned to current test assembly.</returns> private static IEnumerable<string> GetAssemblyCategories(Type type) { var categories = Enumerable.Empty<string>(); var assemblyCategoryAttrs = (CategoryAttribute[])type.Assembly.GetCustomAttributes(typeof(CategoryAttribute), true); if (assemblyCategoryAttrs.Length > 0) { categories = assemblyCategoryAttrs.Select(x => x.Name); } return categories; } } }
37.845528
191
0.580559
[ "Apache-2.0" ]
UrbancokDavid/BSc-thesis
SLN_old/TestsProject/CMSTests/Helpers/TestCategoryCheck.cs
9,312
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: EnumType.cs.tt namespace Microsoft.Graph { using System.Text.Json.Serialization; /// <summary> /// The enum TeamworkConnectionStatus. /// </summary> [JsonConverter(typeof(JsonStringEnumConverter))] public enum TeamworkConnectionStatus { /// <summary> /// Unknown /// </summary> Unknown = 0, /// <summary> /// Connected /// </summary> Connected = 1, /// <summary> /// Disconnected /// </summary> Disconnected = 2, /// <summary> /// Unknown Future Value /// </summary> UnknownFutureValue = 3, } }
25.340909
153
0.49148
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/TeamworkConnectionStatus.cs
1,115
C#
// <auto-generated/> #pragma warning disable 1591 namespace Test { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; public partial class TestComponent : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 219 private void __RazorDirectiveTokenHelpers__() { } #pragma warning restore 219 #pragma warning disable 0414 private static System.Object __o = null; #pragma warning restore 0414 #pragma warning disable 1998 protected override void BuildRenderTree( Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder ) { { __Blazor.Test.TestComponent.TypeInference.CreateGrid_0_CaptureParameters( #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" Array.Empty<DateTime>() #line default #line hidden #nullable disable , out var __typeInferenceArg_0___arg0 ); __Blazor.Test.TestComponent.TypeInference.CreateGrid_0( __builder, -1, -1, __typeInferenceArg_0___arg0, -1, (__builder2) => { __Blazor.Test.TestComponent.TypeInference.CreateColumn_1( __builder2, -1, __typeInferenceArg_0___arg0 ); #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" __o = typeof(Column<>); #line default #line hidden #nullable disable __Blazor.Test.TestComponent.TypeInference.CreateColumn_2( __builder2, -1, __typeInferenceArg_0___arg0 ); #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" __o = typeof(Column<>); #line default #line hidden #nullable disable } ); } #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" __o = typeof(Grid<>); #line default #line hidden #nullable disable } #pragma warning restore 1998 } } namespace __Blazor.Test.TestComponent { #line hidden internal static class TypeInference { public static void CreateGrid_0<TItem>( global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, int __seq0, global::System.Collections.Generic.IEnumerable<TItem> __arg0, int __seq1, global::Microsoft.AspNetCore.Components.RenderFragment __arg1 ) { __builder.OpenComponent<global::Test.Grid<TItem>>(seq); __builder.AddAttribute(__seq0, "Items", __arg0); __builder.AddAttribute(__seq1, "ChildContent", __arg1); __builder.CloseComponent(); } public static void CreateGrid_0_CaptureParameters<TItem>( global::System.Collections.Generic.IEnumerable<TItem> __arg0, out global::System.Collections.Generic.IEnumerable<TItem> __arg0_out ) { __arg0_out = __arg0; } public static void CreateColumn_1<TItem>( global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, System.Collections.Generic.IEnumerable<TItem> __syntheticArg0 ) { __builder.OpenComponent<global::Test.Column<TItem>>(seq); __builder.CloseComponent(); } public static void CreateColumn_2<TItem>( global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder, int seq, System.Collections.Generic.IEnumerable<TItem> __syntheticArg0 ) { __builder.OpenComponent<global::Test.Column<TItem>>(seq); __builder.CloseComponent(); } } } #pragma warning restore 1591
33.717742
90
0.59579
[ "Apache-2.0" ]
belav/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentDesignTimeCodeGenerationTest/CascadingGenericInference_NotCascaded_Inferred/TestComponent.codegen.cs
4,181
C#
using Substitute.Business.DataStructs.Enum; namespace Substitute.Business.DataStructs.ImageResponse { public interface IImageResponseFilter { string Command { get; } ulong? GuildId { get; } ulong UserId { get; } EImageResponseSort SortBy { get; } } }
22.846154
55
0.659933
[ "Apache-2.0" ]
antalabot/substitute
Substitute.Business/DataStructs/ImageResponse/IImageResponseFilter.cs
299
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Powershell { using System; using System.Fabric; using System.Fabric.Result; using System.Management.Automation; using System.Numerics; [Cmdlet(VerbsCommon.Get, Constants.GetUpgradeOrchestrationServiceState)] public sealed class GetUpgradeOrchestrationServiceState : CommonCmdletBase { protected override void ProcessRecord() { var clusterConnection = this.GetClusterConnection(); try { string uosServiceState = clusterConnection.GetUpgradeOrchestrationServiceStateAsync( this.GetTimeout(), this.GetCancellationToken()).Result; this.WriteObject(uosServiceState); } catch (AggregateException aggregateException) { aggregateException.Handle((ae) => { this.ThrowTerminatingError( ae, Constants.GetUpgradeOrchestrationServiceStateErrorId, clusterConnection); return true; }); } } } }
36.547619
100
0.522476
[ "MIT" ]
AndreyTretyak/service-fabric
src/prod/src/managed/powershell/GetUpgradeOrchestrationServiceState.cs
1,535
C#
using Microsoft.CodeAnalysis.CSharp.Syntax; // lgtm[cs/similar-file] using Semmle.Extraction.Kinds; using System.IO; namespace Semmle.Extraction.CSharp.Entities.Expressions { class Checked : Expression<CheckedExpressionSyntax> { Checked(ExpressionNodeInfo info) : base(info.SetKind(ExprKind.CHECKED)) { } public static Expression Create(ExpressionNodeInfo info) => new Checked(info).TryPopulate(); protected override void PopulateExpression(TextWriter trapFile) { Create(cx, Syntax.Expression, this, 0); } } }
30.368421
100
0.708839
[ "MIT" ]
Abdullahki/codeql
csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Checked.cs
577
C#
using System.Web; using System.Web.Optimization; namespace SpraySite { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/signalr").Include( "~/Scripts/jquery.signalR-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/smjs").Include( "~/Scripts/smscripts/sm.browsercheck.js", "~/Scripts/smscripts/sm.fadecontrol.js", "~/Scripts/smscripts/sm.analytics.js")); bundles.Add(new ScriptBundle("~/bundles/staticBundle").Include( "~/Scripts/smscripts/sm.static.js")); bundles.Add(new ScriptBundle("~/bundles/fadingBundle").Include( "~/Scripts/smscripts/sm.fading.js")); bundles.Add(new ScriptBundle("~/bundles/projectwonderful").Include( "~/Scripts/smscripts/sm.ads.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-{version}.js")); bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css", "~/Content/themes/base/jquery.ui.selectable.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.autocomplete.css", "~/Content/themes/base/jquery.ui.button.css", "~/Content/themes/base/jquery.ui.dialog.css", "~/Content/themes/base/jquery.ui.slider.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); } } }
49.666667
112
0.553161
[ "Unlicense" ]
CodyJung/TF2SprayMaker
SpraySite/App_Start/BundleConfig.cs
2,833
C#
// // MainLoop.cs: IMainLoopDriver and MainLoop for Terminal.Gui // // Authors: // Miguel de Icaza (miguel@gnome.org) // using System; using System.Collections.Generic; namespace Terminal.Gui { /// <summary> /// Public interface to create your own platform specific main loop driver. /// </summary> public interface IMainLoopDriver { /// <summary> /// Initializes the main loop driver, gets the calling main loop for the initialization. /// </summary> /// <param name="mainLoop">Main loop.</param> void Setup (MainLoop mainLoop); /// <summary> /// Wakes up the mainloop that might be waiting on input, must be thread safe. /// </summary> void Wakeup (); /// <summary> /// Must report whether there are any events pending, or even block waiting for events. /// </summary> /// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns> /// <param name="wait">If set to <c>true</c> wait until an event is available, otherwise return immediately.</param> bool EventsPending (bool wait); /// <summary> /// The iteration function. /// </summary> void MainIteration (); } /// <summary> /// Simple main loop implementation that can be used to monitor /// file descriptor, run timers and idle handlers. /// </summary> /// <remarks> /// Monitoring of file descriptors is only available on Unix, there /// does not seem to be a way of supporting this on Windows. /// </remarks> public class MainLoop { /// <summary> /// Provides data for timers running manipulation. /// </summary> public sealed class Timeout { /// <summary> /// Time to wait before invoke the callback. /// </summary> public TimeSpan Span; /// <summary> /// The function that will be invoked. /// </summary> public Func<MainLoop, bool> Callback; } internal SortedList<long, Timeout> timeouts = new SortedList<long, Timeout> (); object timeoutsLockToken = new object (); internal List<Func<bool>> idleHandlers = new List<Func<bool>> (); /// <summary> /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks./>. /// A shorter limit time can be added at the end, but it will be called before an /// earlier addition that has a longer limit time. /// </summary> public SortedList<long, Timeout> Timeouts => timeouts; /// <summary> /// Gets the list of all idle handlers. /// </summary> public List<Func<bool>> IdleHandlers => idleHandlers; /// <summary> /// The current IMainLoopDriver in use. /// </summary> /// <value>The driver.</value> public IMainLoopDriver Driver { get; } /// <summary> /// Invoked when a new timeout is added to be used on the case /// if <see cref="Application.ExitRunLoopAfterFirstIteration"/> is true, /// </summary> public event Action<long> TimeoutAdded; /// <summary> /// Creates a new Mainloop. /// </summary> /// <param name="driver">Should match the <see cref="ConsoleDriver"/> (one of the implementations UnixMainLoop, NetMainLoop or WindowsMainLoop).</param> public MainLoop (IMainLoopDriver driver) { Driver = driver; driver.Setup (this); } /// <summary> /// Runs <c>action</c> on the thread that is processing events /// </summary> /// <param name="action">the action to be invoked on the main processing thread.</param> public void Invoke (Action action) { AddIdle (() => { action (); return false; }); } /// <summary> /// Adds specified idle handler function to mainloop processing. The handler function will be called once per iteration of the main loop after other events have been handled. /// </summary> /// <remarks> /// <para> /// Remove an idle hander by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns. /// </para> /// <para> /// If the <c>idleHandler</c> returns <c>false</c> it will be removed and not called subsequently. /// </para> /// </remarks> /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param> public Func<bool> AddIdle (Func<bool> idleHandler) { lock (idleHandlers) { idleHandlers.Add (idleHandler); } Driver.Wakeup (); return idleHandler; } /// <summary> /// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing. /// </summary> /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param> /// Returns <c>true</c>if the idle handler is successfully removed; otherwise, <c>false</c>. /// This method also returns <c>false</c> if the idle handler is not found. public bool RemoveIdle (Func<bool> token) { lock (token) return idleHandlers.Remove (token); } void AddTimeout (TimeSpan time, Timeout timeout) { lock (timeoutsLockToken) { var k = (DateTime.UtcNow + time).Ticks; timeouts.Add (NudgeToUniqueKey (k), timeout); TimeoutAdded?.Invoke (k); } } /// <summary> /// Adds a timeout to the mainloop. /// </summary> /// <remarks> /// When time specified passes, the callback will be invoked. /// If the callback returns true, the timeout will be reset, repeating /// the invocation. If it returns false, the timeout will stop and be removed. /// /// The returned value is a token that can be used to stop the timeout /// by calling <see cref="RemoveTimeout(object)"/>. /// </remarks> public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback) { if (callback == null) throw new ArgumentNullException (nameof (callback)); var timeout = new Timeout () { Span = time, Callback = callback }; AddTimeout (time, timeout); return timeout; } /// <summary> /// Removes a previously scheduled timeout /// </summary> /// <remarks> /// The token parameter is the value returned by AddTimeout. /// </remarks> /// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>. /// This method also returns <c>false</c> if the timeout is not found. public bool RemoveTimeout (object token) { lock (timeoutsLockToken) { var idx = timeouts.IndexOfValue (token as Timeout); if (idx == -1) return false; timeouts.RemoveAt (idx); } return true; } void RunTimers () { long now = DateTime.UtcNow.Ticks; SortedList<long, Timeout> copy; // lock prevents new timeouts being added // after we have taken the copy but before // we have allocated a new list (which would // result in lost timeouts or errors during enumeration) lock (timeoutsLockToken) { copy = timeouts; timeouts = new SortedList<long, Timeout> (); } foreach (var t in copy) { var k = t.Key; var timeout = t.Value; if (k < now) { if (timeout.Callback (this)) AddTimeout (timeout.Span, timeout); } else { lock (timeoutsLockToken) { timeouts.Add (NudgeToUniqueKey (k), timeout); } } } } /// <summary> /// Finds the closest number to <paramref name="k"/> that is not /// present in <see cref="timeouts"/> (incrementally). /// </summary> /// <param name="k"></param> /// <returns></returns> private long NudgeToUniqueKey (long k) { lock (timeoutsLockToken) { while (timeouts.ContainsKey (k)) { k++; } } return k; } void RunIdle () { List<Func<bool>> iterate; lock (idleHandlers) { iterate = idleHandlers; idleHandlers = new List<Func<bool>> (); } foreach (var idle in iterate) { if (idle ()) lock (idleHandlers) idleHandlers.Add (idle); } } bool running; /// <summary> /// Stops the mainloop. /// </summary> public void Stop () { running = false; Driver.Wakeup (); } /// <summary> /// Determines whether there are pending events to be processed. /// </summary> /// <remarks> /// You can use this method if you want to probe if events are pending. /// Typically used if you need to flush the input queue while still /// running some of your own code in your main thread. /// </remarks> public bool EventsPending (bool wait = false) { return Driver.EventsPending (wait); } /// <summary> /// Runs one iteration of timers and file watches /// </summary> /// <remarks> /// You use this to process all pending events (timers, idle handlers and file watches). /// /// You can use it like this: /// while (main.EvensPending ()) MainIteration (); /// </remarks> public void MainIteration () { if (timeouts.Count > 0) RunTimers (); Driver.MainIteration (); lock (idleHandlers) { if (idleHandlers.Count > 0) RunIdle (); } } /// <summary> /// Runs the mainloop. /// </summary> public void Run () { bool prev = running; running = true; while (running) { EventsPending (true); MainIteration (); } running = prev; } } }
28.245283
178
0.638499
[ "MIT" ]
dandycheung/gui.cs
Terminal.Gui/Core/MainLoop.cs
8,984
C#
using Assets.blackwhite_side_scroller; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControls : MonoBehaviour { private CharacterController2D _controller; private SlidingCharacterController2D _slidingController; private float _horizontalMove; public float RunSpeed; public float[] SpeedSteps; [Header("Debug info (read only)")] public float InputSpeed; public float StepSpeed; public bool _crouch; public bool _jumpPressed; public bool _jumpProcessed; void Start() { _controller = GetComponent<CharacterController2D>(); _slidingController = GetComponent<SlidingCharacterController2D>(); } void Update() { InputSpeed = Input.GetAxis("Horizontal"); StepSpeed = SpeedSteps.ClosestTo(Mathf.Abs(InputSpeed)) * (InputSpeed > 0 ? 1 : -1); _horizontalMove = StepSpeed * RunSpeed; if (!_jumpPressed || _jumpProcessed) { _jumpPressed = Input.GetButtonDown("Jump"); if (_jumpPressed) _jumpProcessed = false; } } void FixedUpdate() { _jumpProcessed = false; if (_controller.enabled) _controller.Move(_horizontalMove * Time.fixedDeltaTime, _crouch, _jumpPressed); else if (_slidingController.enabled && _jumpPressed) _slidingController.Jump(); if (_jumpPressed) { _jumpPressed = false; _jumpProcessed = true; } } }
28.052632
93
0.625391
[ "MIT" ]
schouffy/unity-skyline-rider
Assets/blackwhite-side-scroller/Scripts/Player/PlayerControls.cs
1,601
C#
using System.Collections.Generic; using System.Text; namespace OsuSkinMixer { public class SkinIniSection : Dictionary<string, string> { public SkinIniSection(string name) { Name = name; } public string Name { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append('[').Append(Name).AppendLine("]"); foreach (var pair in this) sb.Append(pair.Key).Append(": ").AppendLine(pair.Value); return sb.ToString(); } } }
23.68
72
0.548986
[ "MIT" ]
rednir/OsuSkinMixer
src/Models/SkinIni/SkinIniSection.cs
592
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.WAFRegional")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS WAF Regional. AWS WAF (Web Application Firewall) Regional protects web applications from attack via ALB load balancer and provides API to associate it with a WAF WebACL.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.5.0.59")]
47.4375
253
0.751647
[ "Apache-2.0" ]
rczwojdrak/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/WAFRegional/Properties/AssemblyInfo.cs
1,518
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="OAuthRequestHandler.cs"> // Copyright (c) 2019 Aspose.Ocr for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Ocr.Cloud.Sdk.Internal.Invoker.RequestHandlers { using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; internal class JwtRequestHandler : IRequestHandler { private readonly Configuration configuration; private readonly ApiInvoker apiInvoker; private string accessToken; public JwtRequestHandler(Configuration configuration) { this.configuration = configuration; var requestHandlers = new List<IRequestHandler>(); requestHandlers.Add(new DebugLogRequestHandler(this.configuration)); requestHandlers.Add(new ApiExceptionRequestHandler()); this.apiInvoker = new ApiInvoker(requestHandlers); } public string ProcessUrl(string url) { if (string.IsNullOrEmpty(this.accessToken)) RequestToken(); return url; } public void BeforeSend(WebRequest request, Stream streamToSend) { request.Headers.Add("Authorization", "Bearer " + this.accessToken); } public void ProcessResponse(HttpWebResponse response, Stream resultStream) { } private void RequestToken() { var requestUrl = this.configuration.IdentityServerBaseUrl + "/connect/token"; var postData = "grant_type=client_credentials"; postData += "&client_id=" + this.configuration.AppSid; postData += "&client_secret=" + this.configuration.AppKey; var result = this.apiInvoker.InvokeApi<GetAccessTokenResult>( requestUrl, "POST", postData, contentType: "application/x-www-form-urlencoded"); this.accessToken = result.AccessToken; } private class GetAccessTokenResult { [JsonProperty(PropertyName = "access_token")] public string AccessToken { get; set; } } } }
38.791209
120
0.618414
[ "MIT" ]
aspose-ocr-cloud/aspose-ocr-cloud-dotnet
Aspose.Ocr.Cloud.Sdk/Internal/Invoker/RequestHandlers/JwtRequestHandler.cs
3,532
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapDCETModelETCancellationTokenSourceAwakeSystemWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.DCETModelETCancellationTokenSourceAwakeSystemWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.DCETModelETCancellationTokenSourceAwakeSystemWrap gen_ret = new XLua.CSObjectWrap.DCETModelETCancellationTokenSourceAwakeSystemWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.DCETModelETCancellationTokenSourceAwakeSystemWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.DCETModelETCancellationTokenSourceAwakeSystemWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
24.990909
157
0.581302
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapDCETModelETCancellationTokenSourceAwakeSystemWrapWrap.cs
2,751
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.ServiceFabric.Models { public enum PSServiceKind { /// <summary> /// Does not use Service Fabric to make its state highly available or /// reliable. The value is 0. /// </summary> Stateless, /// <summary> /// Uses Service Fabric to make its state or part of its state highly /// available and reliable. The value is 1. /// </summary> Stateful } }
40.677419
87
0.570975
[ "MIT" ]
Agazoth/azure-powershell
src/ServiceFabric/ServiceFabric/Models/ManagedClusters/PSServiceKind.cs
1,233
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nest.Tests.MockData; using NUnit.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Nest; using Newtonsoft.Json.Converters; using Nest.Resolvers.Converters; using Nest.Tests.MockData.Domain; using FluentAssertions; namespace Nest.Tests.Integration.Core.Get { [TestFixture] public class GetMultiTests : IntegrationTests { [Test] public void GetMultiSimple() { var result = this._client.MultiGet(a => a .Get<ElasticsearchProject>(g=>g.Id(NestTestData.Data[1].Id)) .Get<Person>(g => g.Id(NestTestData.People[1].Id)) ); var objects = result.Documents; objects.Should().NotBeNull().And.HaveCount(2); var person = result.Source<Person>(NestTestData.People[1].Id); person.Should().NotBeNull(); person.FirstName.Should().NotBeNullOrEmpty(); } [Test] public void GetMultiSimpleWithMissingItem() { var project = -200; var frank = -204; var lewisId = NestTestData.People[5].Id; var result = this._client.MultiGet(a => a .Get<Person>(g => g.Id(project)) .Get<Person>(g => g.Id(frank)) .Get<Person>(g => g.Id(lewisId)) ); var objects = result.Documents; objects.Should().NotBeNull() .And.HaveCount(3); var missingPerson = result.Get<Person>(project); missingPerson.Should().NotBeNull(); missingPerson.Found.Should().BeFalse(); var missingPersonDirect = result.Source<Person>(frank); missingPersonDirect.Should().BeNull(); var lewis = result.Source<Person>(lewisId); lewis.Should().NotBeNull(); lewis.FirstName.Should().NotBeNullOrEmpty(); } [Test] public void GetMultiWithMetaData() { var projectId = NestTestData.Data[14].Id; var authorId = NestTestData.People[11].Id; var result = this._client.MultiGet(a => a .Get<ElasticsearchProject>(g => g.Id(projectId).Fields(p=>p.Id, p=>p.Followers.First().FirstName)) .Get<Person>(g => g.Id(authorId).Type("person").Index(ElasticsearchConfiguration.DefaultIndex).Fields(p => p.Id, p => p.FirstName)) ); var objects = result.Documents; objects.Should().NotBeNull() .And.HaveCount(2); var people = objects.OfType<MultiGetHit<Person>>(); people.Should().HaveCount(1); var personHit = people.FirstOrDefault(p => p.Id == authorId.ToString()); personHit.Should().NotBeNull(); personHit.Found.Should().BeTrue(); personHit.Version.Should().NotBeNullOrEmpty().And.Match("1"); var fieldSelection = personHit.FieldSelection; fieldSelection.Should().NotBeNull(); fieldSelection.FieldValue<Person, int>(p=>p.Id).Should().BeEquivalentTo(new []{authorId}); fieldSelection.FieldValue<Person, string>(p => p.FirstName) .Should().NotBeEmpty(); } [Test] public void GetMultiWithMetaDataUsingCleanApi() { var projectId = NestTestData.Data[8].Id; var authorId = NestTestData.People[5].Id; var result = this._client.MultiGet(a => a .Get<ElasticsearchProject>(g => g.Id(projectId).Fields(p => p.Id, p => p.Followers.First().FirstName)) .Get<Person>(g => g .Id(authorId) .Type("person") .Index(ElasticsearchConfiguration.DefaultIndex) .Fields(p => p.Id, p => p.FirstName) ) ); var personHit = result.Get<Person>(authorId); personHit.Should().NotBeNull(); personHit.Found.Should().BeTrue(); personHit.Version.Should().NotBeNullOrEmpty().And.Match("1"); //personHit.FieldSelection would work too var personFieldSelection = result.GetFieldSelection<Person>(authorId); personFieldSelection.Should().NotBeNull(); personFieldSelection.FieldValue<Person, int>(p => p.Id).Should().BeEquivalentTo(new []{authorId}); personFieldSelection.FieldValue<Person, string>(p => p.FirstName) .Should().NotBeEmpty(); var projectFieldSelection = result.GetFieldSelection<ElasticsearchProject>(projectId); projectFieldSelection.Should().NotBeNull(); projectFieldSelection.FieldValue<ElasticsearchProject, int>(p => p.Id) .Should().BeEquivalentTo(new []{projectId}); projectFieldSelection.FieldValue<ElasticsearchProject, string>(p => p.Followers.First().FirstName) .Should().NotBeEmpty(); } } }
30.028571
135
0.700048
[ "Apache-2.0" ]
NickCraver/NEST
src/Tests/Nest.Tests.Integration/Core/Get/GetMultiTests.cs
4,206
C#
using System; using System.Drawing; using System.Windows; using System.Windows.Controls; using System.Runtime.InteropServices; using System.Threading; using HalconDotNet; namespace CompactNavigationMenu.Views { /// <summary> /// Interaction logic for HomeView.xaml /// </summary> enum enumStatus { pclSuccess = 0, //Base pclParameterSetupFailed, //Device pclNoDevice, pclDeviceOpenErr, pclImageSizeErr, pclImageLoadErr, pclProjectorSizeErr, pclpreviousSetupFailed, pclImageBuffersEmpty, pclGrabTimeout, pclDeviceAlreadyConnected, //Core pclCoreProcessErr, //Calibration pclCalloadErr, pclCalProcessErr, pclUnknownErr, }; //base [StructLayout(LayoutKind.Sequential)] unsafe public struct basePara { public bool SoftwareSimulation; //use h/w //screen public int screenSizeX; //px public int screenSizeY; public float screenPixelSizeX; //mm public float screenPixelSizeY; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string dir_imagesave; //이미지 저장 경로 public CoreCoordinate coordinate_system; bool saveImage; bool useItyTable; } //sync [StructLayout(LayoutKind.Sequential)] unsafe public struct syncPara { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string local_ip; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string remote_ip; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string port; //camera public int maxcamera; public int ImageSizeX; public int ImageSizeY; //projector public int projSizeX; public int projSizeY; //command public float exposure_time; public float high_time; public int capture_count; } //core //enum public enum DetectionAlgorithm { Structuredlight = 1, ActiveStereo = 2, } public enum ScanType { Inspection = 0, Calibration = 1, Continuous = 2, Intensity_Calibration = 3, } public enum CoreCoordinate { Camera = 0, World = 1, }; [StructLayout(LayoutKind.Sequential)] unsafe public struct corePara { int bucket; int threshold; int max_distance; int amplitudethreshold; public DetectionAlgorithm detectionAlgo; public ScanType scanType; } //calibration [StructLayout(LayoutKind.Sequential)] unsafe public struct calPara { bool fit_plane; } //point cloud [StructLayout(LayoutKind.Sequential)] unsafe public struct pointcloud { public IntPtr x; public IntPtr y; public IntPtr z; public long dataSize; } public partial class HomeView : UserControl { [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclUploadParameter(basePara para1, syncPara para2, corePara para3, calPara para4); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclDownloadParameter(ref basePara para1, ref syncPara para2, ref corePara para3, ref calPara para4); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclSetup(); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclCapture(); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclManualRun(string dir, pointcloud* data); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclRun(byte** pImages, pointcloud* data); [DllImport("Library.PointCloudOptics.dll")] public unsafe static extern int pclScan(pointcloud* data); basePara para1 = new basePara(); syncPara para2 = new syncPara(); corePara para3 = new corePara(); calPara para4 = new calPara(); Rectangle rectHalcon; HWindow hWindow; public HomeView() { InitializeComponent(); } private void HomeView_SizeChanged(object sender, SizeChangedEventArgs e) { throw new NotImplementedException(); } private void Button_Click(object sender, System.Windows.RoutedEventArgs e) { double width = HalconWPFWindow.Width; rectHalcon.Width = (int)width; double height = HalconWPFWindow.Height; rectHalcon.Height = (int)height; hWindow = HalconWPFWindow.HalconWindow; if (hWindow == null) { return; } Thread thread = new Thread(new ThreadStart(ThreadRun)); thread.Start(); unsafe { enumStatus status = (enumStatus)pclSetup(); status = (enumStatus)pclDownloadParameter(ref para1, ref para2, ref para3, ref para4); txtBoxResult.Text = status.ToString(); } } void ThreadRun() { HDevelopExport HD = new HDevelopExport(rectHalcon, hWindow); } private void Grid_SizeChanged(object sender, SizeChangedEventArgs e) { HalconWPFWindow.Width = e.NewSize.Width-100-10; HalconWPFWindow.Height = e.NewSize.Height-60-10; } } }
25.536036
140
0.607162
[ "MIT" ]
poincarelim/CompactNavigationMenu
Views/HomeView.xaml.cs
5,685
C#
using UnityEngine; using UnityEngine.SceneManagement; namespace Cindy.Logic.VariableObjects { /// <summary> /// 场景名 /// </summary> [AddComponentMenu("Cindy/Logic/VariableObject/Util/SceneName (String)")] public class SceneName : StringObject { [Header("Scene Name")] public SceneType sceneType = SceneType.ActiveScene; protected override void Start() { base.Start(); GetValue(); } public override void SetValue(string value) { } public override string GetValue() { switch (sceneType) { default: case SceneType.ActiveScene: value = SceneManager.GetActiveScene().name; break; case SceneType.ObjectScene: value = gameObject.scene.name; break; } return value; } public enum SceneType { ActiveScene, ObjectScene } } }
23.297872
76
0.499543
[ "MIT" ]
Hansin1997/Cindy
src/Cindy/Cindy.Logic/VariableObjects/SceneName.cs
1,103
C#
using strange.extensions.mediation.impl; using Services; using UnityEngine; namespace Views.UI { public class HealthBarView : EventView { /// <summary> /// Health prefab /// </summary> [SerializeField] private GameObject _healthPrefab; /// <summary> /// Player starts service /// </summary> [Inject] public PlayerStartsService PlayerStartsService { get; set; } private int _currentHealth; protected override void Start() { _currentHealth = PlayerStartsService.Health; ShowHealth(); } private void Update() { if (PlayerStartsService.Health >= _currentHealth) return; _currentHealth = PlayerStartsService.Health; Destroy(transform.GetChild(transform.childCount - 1).gameObject); } /// <summary> /// Show health /// </summary> private void ShowHealth() { for (var i = 0; i < _currentHealth; i++) { Instantiate(_healthPrefab, transform.position, Quaternion.identity, transform); } } } }
25.104167
95
0.551867
[ "MIT" ]
gellios3/My-Bomber-Man
Assets/Scripts/Views/UI/HealthBarView.cs
1,205
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using DLaB.Common; using DLaB.Xrm.LocalCrm.Entities; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; #if NET using DataverseUnitTest.Exceptions; using DLaB.Xrm; namespace DataverseUnitTest.Builders #else using DLaB.Xrm.Test.Exceptions; namespace DLaB.Xrm.Test.Builders #endif { /// <summary> /// Manages what the default builder is for the Entity Type, and the specific builder by id /// </summary> internal class EntityBuilderManager { #region Properties /// <summary> /// The builder for each specific entity /// </summary> /// <value> /// The builders. /// </value> private Dictionary<Guid, BuilderInfo> Builders { get; } /// <summary> /// Manages the same list of Builders as the Builders Property, but by logical name /// </summary> /// <value> /// The type of the builders by entity. /// </value> private Dictionary<string, List<BuilderInfo>> BuildersByEntityType { get; } // ReSharper disable once StaticMemberInGenericType private static readonly object BuilderConstructorForEntityLock = new object(); /// <summary> /// Contains constructors for the default builders of each entity type. Whenever a new Builder is needed, this contains the constructor that will be invoked. /// </summary> /// <value> /// The builder for entity. /// </value> // ReSharper disable once StaticMemberInGenericType private static Dictionary<string, ConstructorInfo> DefaultBuilderConstructors { get; } /// <summary> /// Manages Custom Builder Fluent Actions. Key is entity Logical Name. Value is fluent actions to apply to Builder /// </summary> /// <value> /// The custom builder actions. /// </value> private Dictionary<string, Action<object>> CustomBuilderFluentActions { get; } private Dictionary<Guid, Id> Ids { get; } #endregion Properties #region Constructors static EntityBuilderManager() { var builderInterface = typeof (IEntityBuilder); var genericInterface = typeof (IEntityBuilder<>); // Load all types that have EntityBuilder<> as a base class var entityBuilders = from t in TestSettings.EntityBuilder.Assembly.GetTypes() where builderInterface.IsAssignableFrom(t) && t.IsPublic && !t.IsAbstract select new { Entity = EntityHelper.GetEntityLogicalName(t.GetInterfaces().First(i => i.IsGenericType && i.GetGenericTypeDefinition() == genericInterface).GenericTypeArguments[0]), Builder = t, Ass = t.Assembly.GetName().Name }; var groupedBuilder = entityBuilders.GroupBy(b => b.Entity).ToList(); var dup = groupedBuilder.Where(g => g.Count() > 1).Select(g => new { g.Key, Names = g.Select(b => b.Builder.FullName)}).ToList(); if (dup.Any()) { throw new Exception($"Duplicate EntityBuilders {string.Join(", ", dup.First().Names)} found for Entity {dup.First().Key}."); } DefaultBuilderConstructors = groupedBuilder.ToDictionary(g => g.Key, g => g.First().Builder.GetConstructor(new[] { typeof(Id) })); foreach (var builder in DefaultBuilderConstructors) { if (builder.Key == "entity" || builder.Value != null) { continue; } throw new Exception("Entity Builder " + builder.Key + " does not contain a Constructor of type (Id)!"); } } /// <summary> /// Initializes a new instance of the <see cref="EntityBuilderManager" /> class. /// </summary> public EntityBuilderManager() { BuildersByEntityType = new Dictionary<string, List<BuilderInfo>>(); Builders = new Dictionary<Guid, BuilderInfo>(); CustomBuilderFluentActions = new Dictionary<string, Action<object>>(); Ids = new Dictionary<Guid, Id>(); } #endregion Constructors /// <summary> /// Adds the custom fluent action if one doesn't already exist, and combines if one does already exist. /// </summary> /// <param name="logicalName">Name of the logical.</param> /// <param name="action">The action.</param> private void AddCustomAction(string logicalName, Action<object> action) { if (CustomBuilderFluentActions.TryGetValue(logicalName, out var customAction)) { // Builder already has custom Action. Create new custom Action that first calls old, then calls new CustomBuilderFluentActions[logicalName] = b => { customAction(b); action(b); }; } else { CustomBuilderFluentActions[logicalName] = action; } } /// <summary> /// Applies the custom action to all Builders for the given type. /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <param name="logicalName">Name of the logical.</param> /// <param name="action">The action.</param> /// <exception cref="System.Exception"></exception> private void ApplyCustomAction<TBuilder>(string logicalName, Action<TBuilder> action) where TBuilder : class, IEntityBuilder { if (!BuildersByEntityType.TryGetValue(logicalName, out List<BuilderInfo> builders)) { return; } foreach (var result in builders.Select(b => b.Builder)) { if (!(result is TBuilder builder)) { throw new Exception($"Unexpected type of builder! Builder for {logicalName}, was not of type {typeof(TBuilder).FullName}, but type {result.GetType().FullName}."); } action(builder); } } /// <summary> /// Applies all custom fluent actions to the builder /// </summary> /// <param name="logicalName">Name of the logical.</param> /// <param name="builder">The builder.</param> private void ApplyCustomActions(string logicalName, object builder) { if (CustomBuilderFluentActions.TryGetValue(logicalName, out Action<object> customAction)) { customAction(builder); } } /// <summary> /// Creates the specified entities in the correct Dependent Order, returning the entities created. /// </summary> /// <param name="service">The service.</param> /// <returns></returns> public Dictionary<Guid, Entity> Create(IOrganizationService service) { var results = new Dictionary<Guid, Entity>(); var builders = new List<Tuple<Guid, BuilderInfo>>(); var postCreateUpdates = new List<Entity>(); foreach (var info in EntityDependency.Mapper.EntityCreationOrder) { if (!BuildersByEntityType.TryGetValue(info.LogicalName, out List<BuilderInfo> values)) { // The Entity Creation Order is a Singleton. // If this continue occurs, most likely another instance of a Crm Environment Builder used a type that wasn't utilized by this instance continue; } foreach (var value in values) { try { var entity = CreateEntity(service, value, info.CyclicAttributes, postCreateUpdates); RecordBuiltEntity(entity, value, results, builders); } catch (Exception ex) { var entityName = value.Id.Entity == null ? info.LogicalName : $"Entity {value.Id.LogicalName}{Environment.NewLine}{value.Id.Entity.ToStringAttributes()}"; if (string.IsNullOrWhiteSpace(entityName)) { entityName = info.LogicalName; } throw new CreationFailureException($"An error occured attempting to create {entityName}.{Environment.NewLine}{ex.Message}", ex); } } } foreach (var entity in postCreateUpdates) { try { service.Update(entity); AddPostCreateAttributesToIdEntity(results, entity); } catch (Exception ex) { var entityName = $"Entity {entity.LogicalName}{Environment.NewLine}{entity.ToStringAttributes()}"; throw new CreationFailureException($"An error occured attempting to update an EntityDependency post create for Entity {entityName}.{Environment.NewLine}{ex.Message}", ex); } } // Process Post Updates foreach (var builder in builders) { builder.Item2.Builder.PostCreate(service, results[builder.Item1]); } return results; } private void RecordBuiltEntity(Entity entity, BuilderInfo builder, Dictionary<Guid, Entity> results, List<Tuple<Guid, BuilderInfo>> builders) { results.Add(entity.Id, entity); builders.Add(new Tuple<Guid, BuilderInfo>(entity.Id, builder)); if (Ids.TryGetValue(entity.Id, out Id id)) { id.Entity = entity; } } private void AddPostCreateAttributesToIdEntity(Dictionary<Guid, Entity> results, Entity postCreateEntity) { if (results.TryGetValue(postCreateEntity.Id, out Entity entity)) { foreach (var att in postCreateEntity.Attributes) { entity[att.Key] = att.Value; } } if (Ids.TryGetValue(postCreateEntity.Id, out Id id)) { foreach (var att in postCreateEntity.Attributes) { id.Entity[att.Key] = att.Value; } } } /// <summary> /// Updates the Builder with any attributes set in the Id's Entity. /// </summary> /// <param name="service">The service.</param> /// <param name="info">The builder.</param> /// <param name="cyclicAttributes">The cyclic attributes.</param> /// <param name="postCreateUpdates">The post create updates.</param> /// <returns></returns> private static Entity CreateEntity(IOrganizationService service, BuilderInfo info, IEnumerable<string> cyclicAttributes, List<Entity> postCreateUpdates) { var entity = info.Id.Entity; var builder = info.Builder; if (entity != null) { foreach (var att in entity.Attributes) { builder.WithAttributeValue(att.Key, att.Value); } } var attributes = cyclicAttributes as string[] ?? cyclicAttributes.ToArray(); var postCreateEntity = new Entity(info.Id); if (attributes.Length > 0) { var tmp = builder.Build(); foreach (var att in attributes) { var parentEntity = tmp.GetAttributeValue<EntityReference>(att); if (parentEntity == null || service.GetEntityOrDefault(parentEntity.LogicalName, parentEntity.Id, new ColumnSet(false)) != null) { continue; } // parent hasn't been created yet, Add attribute to be updated, and remove attribute for creation postCreateEntity[att] = parentEntity; builder.WithAttributeValue(att, null); } } var createdEntity = builder.Create(service, false); if (postCreateEntity.Attributes.Any()) { postCreateEntity.Id = createdEntity.Id; postCreateUpdates.Add(postCreateEntity); } return createdEntity; } /// <summary> /// Gets the builder for the given Id, casting it to the given type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">The identifier.</param> /// <returns></returns> // ReSharper disable once UnusedMember.Local public T Get<T>(Id id) { return (T) Get(id); } /// <summary> /// Gets the builder for the given Id /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public IEntityBuilder Get(Id id) { if (id != Guid.Empty && !Ids.ContainsKey(id)) { Ids.Add(id, id); } if (Builders.TryGetValue(id, out BuilderInfo builder)) { return builder.Builder; } if (!DefaultBuilderConstructors.TryGetValue(id, out ConstructorInfo constructor)) { constructor = GetGenericConstructor(id); } builder = CreateBuilder(id, constructor); return builder.Builder; } private BuilderInfo CreateBuilder(Id id, ConstructorInfo constructor) { // Add the Entity to the mapper to make sure it can be created in the correct order EntityDependency.Mapper.Add(id); var builder = new BuilderInfo(id, (IEntityBuilder) constructor.Invoke(new object[] {id})); ApplyCustomActions(id, builder.Builder); Builders.Add(id, builder); BuildersByEntityType.AddOrAppend(id, builder); return builder; } /// <summary> /// Adds the builder as the default builder for the given entity type /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <param name="logicalName">Name of the logical.</param> /// <exception cref="System.Exception"> /// </exception> private void SetBuilderType<TBuilder>(string logicalName) where TBuilder : IEntityBuilder { var constructor = GetIdConstructor<TBuilder>(); if (DefaultBuilderConstructors.TryGetValue(logicalName, out ConstructorInfo existingConstructor)) { // Should only have one type. Check to make sure type is the same if (existingConstructor.DeclaringType != constructor.DeclaringType) { // ReSharper disable PossibleNullReferenceException throw new Exception($"Only one type of Builder can be used per entity. Attempt was made to define builder {constructor.DeclaringType.FullName}, when builder {existingConstructor.DeclaringType.FullName} already is defined!"); // ReSharper restore PossibleNullReferenceException } } else { DefaultBuilderConstructors.Add(logicalName, constructor); } } /// <summary> /// Removes the Builder specified by the Id /// </summary> /// <param name="id">The identifier.</param> public void Remove(Id id) { if (Ids.ContainsKey(id)) { Ids.Remove(id); } if (BuildersByEntityType.TryGetValue(id, out List<BuilderInfo> builders) && Builders.TryGetValue(id, out BuilderInfo builder)) { Builders.Remove(id); builders.Remove(builder); } } /// <summary> /// Creates a GenericEntityBuilder of the type of logical name being passed in. Employs locking since BuilderForEntity is static /// </summary> /// <param name="logicalName">Name of the Entity to create a GenericEntityBuilder Constructor For.</param> /// <returns></returns> private ConstructorInfo GetGenericConstructor(string logicalName) { if (DefaultBuilderConstructors.TryGetValue(logicalName, out ConstructorInfo constructor)) { return constructor; } lock (BuilderConstructorForEntityLock) { if (DefaultBuilderConstructors.TryGetValue(logicalName, out constructor)) { return constructor; } var builderType = logicalName == ConnectionRoleAssociation.EntityLogicalName ? typeof(N2NBuilder<>) : typeof(GenericEntityBuilder<>); var builder = builderType.MakeGenericType(TestBase.GetType(logicalName)); constructor = builder.GetConstructor(new[] { typeof(Id) }); DefaultBuilderConstructors.Add(logicalName, constructor); return constructor; } } /// <summary> /// Allows for the specification of any fluent methods to (all existing/future) builders for the given entity type /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> public void WithBuilderForEntityType<TBuilder>(Action<TBuilder> action) where TBuilder : class, IEntityBuilder { var entityType = GetEntityTypeOfBuilder<TBuilder>(); var logicalName = EntityHelper.GetEntityLogicalName(entityType); SetBuilderType<TBuilder>(logicalName); // Handle all existing Builders ApplyCustomAction(logicalName, action); // Handle all future Builders AddCustomAction(logicalName, b => action((TBuilder) b)); // Convert Action<TBuilder> to Action<Object> } private static Type GetEntityTypeOfBuilder<TBuilder>() { var types = (from iType in typeof(TBuilder).GetInterfaces() where iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IEntityBuilder<>) select iType.GetGenericArguments()[0]).ToList(); var type = types.FirstOrDefault(); if (type == null) { throw new Exception($"Builder type \"{typeof(TBuilder).FullName}\" does not implement IEntityBuilder<>!"); } if(types.Count == 1) { return type; } if (types.Skip(1).Any(t => t != type)) { throw new Exception($"Builder type \"{typeof(TBuilder).FullName}\" implements multiple IEntityBuilder<> types!"); } return type; } /// <summary> /// Allows for the specification of a particular entity to use a specific entity builder /// </summary> /// <typeparam name="TBuilder">The type of the builder.</typeparam> /// <param name="id">The identifier.</param> /// <param name="action">The action.</param> /// <exception cref="System.Exception"></exception> public void WithBuilderForEntity<TBuilder>(Id id, Action<TBuilder> action) where TBuilder : class, IEntityBuilder { GetEntityTypeOfBuilder<TBuilder>(); var constructor = GetIdConstructor<TBuilder>(); var builder = CreateBuilder(id, constructor); action((TBuilder)builder.Builder); } private static ConstructorInfo GetIdConstructor<TBuilder>() where TBuilder : IEntityBuilder { var constructor = typeof (TBuilder).GetConstructor(new[] {typeof (Id)}); if (constructor == null) { throw new Exception($"{typeof (TBuilder).FullName} does not contain a constructor with a single parameter of type {typeof (Id).FullName}"); } return constructor; } private class BuilderInfo { public Id Id { get; } public IEntityBuilder Builder { get; } public BuilderInfo(Id id, IEntityBuilder builder) { Id = id; Builder = builder; } } } }
40.71869
245
0.5587
[ "MIT" ]
bobbyangers/XrmUnitTest
DLaB.Xrm.Test.Base/Builders/EntityBuilderManager.cs
21,135
C#
/* © Cutter Systems spol. s r.o., 2018 Author: Petr Kalandra (kalandra@cutter.cz) 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 Newtonsoft.Json; using System.Collections.Generic; using RosSharp.RosBridgeClient.Messages.Standard; namespace RosSharp.RosBridgeClient.Messages.Actionlib { public class TwoIntsResult { [JsonIgnore] public const string RosMessageName = "actionlib/TwoIntsResult"; // ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ====== public long sum; public TwoIntsResult() { } } }
28.277778
73
0.766208
[ "Apache-2.0" ]
kaldap/ros-sharp
Libraries/RosBridgeClient/Messages/Actionlib/TwoIntsResult.cs
1,019
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.cloudesl.Model.V20200201; namespace Aliyun.Acs.cloudesl.Transform.V20200201 { public class GetUserResponseUnmarshaller { public static GetUserResponse Unmarshall(UnmarshallerContext context) { GetUserResponse getUserResponse = new GetUserResponse(); getUserResponse.HttpResponse = context.HttpResponse; getUserResponse.ErrorMessage = context.StringValue("GetUser.ErrorMessage"); getUserResponse.ErrorCode = context.StringValue("GetUser.ErrorCode"); getUserResponse.Message = context.StringValue("GetUser.Message"); getUserResponse.DynamicCode = context.StringValue("GetUser.DynamicCode"); getUserResponse.Code = context.StringValue("GetUser.Code"); getUserResponse.DynamicMessage = context.StringValue("GetUser.DynamicMessage"); getUserResponse.RequestId = context.StringValue("GetUser.RequestId"); getUserResponse.Success = context.BooleanValue("GetUser.Success"); GetUserResponse.GetUser_User user = new GetUserResponse.GetUser_User(); user.Stores = context.StringValue("GetUser.User.Stores"); user.UserName = context.StringValue("GetUser.User.UserName"); user.UserId = context.StringValue("GetUser.User.UserId"); user.UserType = context.StringValue("GetUser.User.UserType"); user.OwnerId = context.StringValue("GetUser.User.OwnerId"); user.Bid = context.StringValue("GetUser.User.Bid"); List<GetUserResponse.GetUser_User.GetUser_DingTalkInfo> user_dingTalkInfos = new List<GetUserResponse.GetUser_User.GetUser_DingTalkInfo>(); for (int i = 0; i < context.Length("GetUser.User.DingTalkInfos.Length"); i++) { GetUserResponse.GetUser_User.GetUser_DingTalkInfo dingTalkInfo = new GetUserResponse.GetUser_User.GetUser_DingTalkInfo(); dingTalkInfo.DingTalkCompanyId = context.StringValue("GetUser.User.DingTalkInfos["+ i +"].DingTalkCompanyId"); dingTalkInfo.DingTalkUserId = context.StringValue("GetUser.User.DingTalkInfos["+ i +"].DingTalkUserId"); user_dingTalkInfos.Add(dingTalkInfo); } user.DingTalkInfos = user_dingTalkInfos; getUserResponse.User = user; return getUserResponse; } } }
46.393939
143
0.757675
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudesl/Cloudesl/Transform/V20200201/GetUserResponseUnmarshaller.cs
3,062
C#
using System; using System.Linq; using System.Reflection; using System.Collections; using System.Collections.Generic; using Xunit; using DotNetCoreKoans.Engine; namespace DotNetCoreKoans.Koans { public class AboutArrays : Koan { [Step(1)] public void CreatingArrays() { var empty_array = new object[] { }; Assert.Equal(typeof(object[]), empty_array.GetType()); //Note that you have to explicitly check for subclasses Assert.True(typeof(Array).IsAssignableFrom(empty_array.GetType())); Assert.Equal(0, empty_array.Length); } [Step(2)] public void ArrayLiterals() { //You don't have to specify a type if the arguments can be inferred var array = new[] { 42 }; Assert.Equal(typeof(int[]), array.GetType()); Assert.Equal(new int[] { 42 }, array); //Are arrays 0-based or 1-based? Assert.Equal(42, array[0]); //This is important because... Assert.True(array.IsFixedSize); //...it means we can't do this: array[1] = 13; Assert.Throws(typeof(System.IndexOutOfRangeException), delegate () { array[1] = 13; }); //This is because the array is fixed at length 1. You could write a function //which created a new array bigger than the last, copied the elements over, and //returned the new array. Or you could do this: List<int> dynamicArray = new List<int>(); dynamicArray.Add(42); Assert.Equal(array, dynamicArray.ToArray()); dynamicArray.Add(13); Assert.Equal((new int[] { 42, 13 }), dynamicArray.ToArray()); } [Step(3)] public void AccessingArrayElements() { var array = new[] { "peanut", "butter", "and", "jelly" }; Assert.Equal("peanut", array[0]); Assert.Equal("jelly", array[3]); //This doesn't work: Assert.Equal(FILL_ME_IN, array[-1]); } [Step(4)] public void SlicingArrays() { var array = new[] { "peanut", "butter", "and", "jelly" }; Assert.Equal(new string[] { "peanut","butter" }, array.Take(2).ToArray()); Assert.Equal(new string[] { "butter","and" }, array.Skip(1).Take(2).ToArray()); } [Step(5)] public void PushingAndPopping() { var array = new[] { 1, 2 }; var stack = new Stack(array); stack.Push("last"); Assert.Equal(stack.ToArray(), stack.ToArray()); var poppedValue = stack.Pop(); Assert.Equal("last", poppedValue); Assert.Equal(stack.ToArray(), stack.ToArray()); } [Step(6)] public void Shifting() { //Shift == Remove First Element //Unshift == Insert Element at Beginning //C# doesn't provide this natively. You have a couple //of options, but we'll use the LinkedList<T> to implement var array = new[] { "Hello", "World" }; var list = new LinkedList<string>(array); list.AddFirst("Say"); Assert.Equal(list.ToArray(), list.ToArray()); list.RemoveLast(); Assert.Equal(list.ToArray(), list.ToArray()); list.RemoveFirst(); Assert.Equal(list.ToArray(), list.ToArray()); list.AddAfter(list.Find("Hello"), "World"); Assert.Equal(list.ToArray(), list.ToArray()); } } }
32.836364
99
0.543743
[ "MIT" ]
ekaphopl04/DotNetCoreKoans
Koans/AboutArrays.cs
3,612
C#
using static Marketplace.EventSourcing.TypeMapper; using static Marketplace.Users.Messages.UserProfile.Events; namespace Marketplace.Users { public static class EventMappings { public static void MapEventTypes() { Map<V1.UserRegistered>("UserRegistered"); Map<V1.UserFullNameUpdated>("UserFullNameUpdated"); } } }
26.714286
63
0.687166
[ "MIT" ]
ChrisDev3110/Hands-On-Domain-Driven-Design-with-.NET-Core
Chapter13/src/Marketplace.Users/EventMappings.cs
374
C#
/* * Square Connect API * * Client library for accessing the Square Connect APIs * * OpenAPI spec version: 2.0 * Contact: developers@squareup.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Square.Connect.Api; using Square.Connect.Model; using Square.Connect.Client; using System.Reflection; namespace Square.Connect.Test { /// <summary> /// Class for testing CatalogItemProductType /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class CatalogItemProductTypeTests { // TODO uncomment below to declare an instance variable for CatalogItemProductType //private CatalogItemProductType instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of CatalogItemProductType //instance = new CatalogItemProductType(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of CatalogItemProductType /// </summary> [Test] public void CatalogItemProductTypeInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" CatalogItemProductType //Assert.IsInstanceOfType<CatalogItemProductType> (instance, "variable 'instance' is a CatalogItemProductType"); } } }
25.183099
124
0.633669
[ "Apache-2.0" ]
NimmoJustin/connect-csharp-sdk
src/Square.Connect.Test/Model/CatalogItemProductTypeTests.cs
1,788
C#
using Bright.Net.Codecs; using System.Collections.Generic; namespace Luban.Common.Protos { public static class ProtocolStub { public static Dictionary<int, ProtocolCreator> Factories { get; } = new Dictionary<int, ProtocolCreator> { [GetInputFile.ID] = () => new GetInputFile(), [GetOutputFile.ID] = () => new GetOutputFile(), [PushLog.ID] = () => new PushLog(), [PushException.ID] = () => new PushException(), [GenJob.ID] = () => new GenJob(), [GetImportFileOrDirectory.ID] = () => new GetImportFileOrDirectory(), [QueryFilesExists.ID] = () => new QueryFilesExists(), }; } }
34.85
112
0.579627
[ "MIT" ]
CN-Zxcv/luban
src/Luban.Common/Source/Protos/ProtocolStub.cs
697
C#
using System.Collections.Generic; using UnityEngine; namespace Com.LuisPedroFonseca.ProCamera2D { public enum EaseType { EaseInOut, EaseOut, EaseIn, Linear } public static class Utils { public static float EaseFromTo(float start, float end, float value, EaseType type = EaseType.EaseInOut) { value = Mathf.Clamp01(value); switch (type) { case EaseType.EaseInOut: return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); case EaseType.EaseOut: return Mathf.Lerp(start, end, Mathf.Sin(value * Mathf.PI * 0.5f)); case EaseType.EaseIn: return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f)); default: return Mathf.Lerp(start, end, value); } } public static float SmoothApproach(float pastPosition, float pastTargetPosition, float targetPosition, float speed, float deltaTime) { float t = deltaTime * speed; float v = (targetPosition - pastTargetPosition) / t; float f = pastPosition - pastTargetPosition + v; return targetPosition - v + f * Mathf.Exp(-t); } public static float Remap(this float value, float from1, float to1, float from2, float to2) { return Mathf.Clamp((value - from1) / (to1 - from1) * (to2 - from2) + from2, from2, to2); } public static void DrawArrowForGizmo(Vector3 pos, Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Gizmos.DrawRay(pos, direction); DrawArrowEnd(true, pos, direction, Gizmos.color, arrowHeadLength, arrowHeadAngle); } public static void DrawArrowForGizmo(Vector3 pos, Vector3 direction, Color color, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Gizmos.DrawRay(pos, direction); DrawArrowEnd(true, pos, direction, color, arrowHeadLength, arrowHeadAngle); } public static void DrawArrowForDebug(Vector3 pos, Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Debug.DrawRay(pos, direction); DrawArrowEnd(false, pos, direction, Gizmos.color, arrowHeadLength, arrowHeadAngle); } public static void DrawArrowForDebug(Vector3 pos, Vector3 direction, Color color, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Debug.DrawRay(pos, direction, color); DrawArrowEnd(false, pos, direction, color, arrowHeadLength, arrowHeadAngle); } static void DrawArrowEnd(bool gizmos, Vector3 pos, Vector3 direction, Color color, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { if (direction == Vector3.zero) return; Vector3 right = Quaternion.LookRotation(direction) * Quaternion.Euler(arrowHeadAngle, 0, 0) * Vector3.back; Vector3 left = Quaternion.LookRotation(direction) * Quaternion.Euler(-arrowHeadAngle, 0, 0) * Vector3.back; Vector3 up = Quaternion.LookRotation(direction) * Quaternion.Euler(0, arrowHeadAngle, 0) * Vector3.back; Vector3 down = Quaternion.LookRotation(direction) * Quaternion.Euler(0, -arrowHeadAngle, 0) * Vector3.back; if (gizmos) { Gizmos.color = color; Gizmos.DrawRay(pos + direction, right * arrowHeadLength); Gizmos.DrawRay(pos + direction, left * arrowHeadLength); Gizmos.DrawRay(pos + direction, up * arrowHeadLength); Gizmos.DrawRay(pos + direction, down * arrowHeadLength); } else { Debug.DrawRay(pos + direction, right * arrowHeadLength, color); Debug.DrawRay(pos + direction, left * arrowHeadLength, color); Debug.DrawRay(pos + direction, up * arrowHeadLength, color); Debug.DrawRay(pos + direction, down * arrowHeadLength, color); } } public static bool AreNearlyEqual(float a, float b, float tolerance = .02f) { return Mathf.Abs(a - b) < tolerance; } public static Vector2 GetScreenSizeInWorldCoords(Camera gameCamera, float distance = 10f) { float width = 0f; float height = 0f; if (gameCamera.orthographic) { if (gameCamera.orthographicSize <= .001f) return Vector2.zero; var p1 = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, gameCamera.nearClipPlane)); var p2 = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, gameCamera.nearClipPlane)); var p3 = gameCamera.ViewportToWorldPoint(new Vector3(1, 1, gameCamera.nearClipPlane)); width = (p2 - p1).magnitude; height = (p3 - p2).magnitude; } else { height = 2.0f * Mathf.Abs(distance) * Mathf.Tan(gameCamera.fieldOfView * 0.5f * Mathf.Deg2Rad); width = height * gameCamera.aspect; } return new Vector2(width, height); } public static Vector3 GetVectorsSum(IList<Vector3> input) { Vector3 output = Vector3.zero; for (int i = 0; i < input.Count; i++) { output += input[i]; } return output; } public static float AlignToGrid(float input, float gridSize) { return Mathf.Round((Mathf.Round(input / gridSize) * gridSize) / gridSize) * gridSize; } public static bool IsInsideRectangle(float x, float y, float width, float height, float pointX, float pointY) { if (pointX >= x - width * .5f && pointX <= x + width * .5f && pointY >= y - height * .5f && pointY <= y + height * .5f) return true; return false; } public static bool IsInsideCircle(float x, float y, float radius, float pointX, float pointY) { return (pointX - x) * (pointX - x) + (pointY - y) * (pointY - y) < radius * radius; } } }
40.055901
151
0.574198
[ "MIT" ]
05Robot/05_Robot
Assets/Plugin/ProCamera2D/Code/Core/Utils/Utils.cs
6,451
C#
using System.ComponentModel; namespace Ckode.Dapper.Repository.Delegates { public delegate void PreOperationDelegate<T>(T inputEntity, CancelEventArgs e); }
22.714286
80
0.823899
[ "MIT" ]
NQbbe/Ckode.Dapper.Repository
Source/Ckode.Dapper.Repository/Delegates/PreOperationDelegate.cs
159
C#
using System; using Smobiler.Core; namespace Smobiler.Tutorials.Components { partial class demoPageView : Smobiler.Core.Controls.MobileForm { #region "SmobilerForm generated code " //SmobilerForm overrides dispose to clean up the component list. protected override void Dispose(bool disposing) { base.Dispose(disposing); } //NOTE: The following procedure is required by the SmobilerForm //It can be modified using the SmobilerForm. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.title1 = new Smobiler.Core.Controls.Title(); this.panel10 = new Smobiler.Core.Controls.Panel(); this.panel1 = new Smobiler.Core.Controls.Panel(); this.labContent = new Smobiler.Core.Controls.Label(); this.labTitle = new Smobiler.Core.Controls.Label(); this.button1 = new Smobiler.Core.Controls.Button(); this.pageView1 = new Smobiler.Core.Controls.PageView(); this.popList1 = new Smobiler.Core.Controls.PopList(); // // title1 // this.title1.ImageType = Smobiler.Core.Controls.ImageEx.ImageStyle.FontIcon; this.title1.Name = "title1"; this.title1.ResourceID = "angle-left"; this.title1.Size = new System.Drawing.Size(300, 30); this.title1.Text = "PageView"; this.title1.ImagePress += new System.EventHandler(this.title1_ImagePress); // // panel10 // this.panel10.Controls.AddRange(new Smobiler.Core.Controls.MobileControl[] { this.panel1, this.pageView1}); this.panel10.Dock = System.Windows.Forms.DockStyle.Fill; this.panel10.Location = new System.Drawing.Point(0, 30); this.panel10.Name = "panel10"; this.panel10.Scrollable = true; this.panel10.Size = new System.Drawing.Size(300, 970); // // panel1 // this.panel1.BackColor = System.Drawing.Color.White; this.panel1.Border = new Smobiler.Core.Controls.Border(1F); this.panel1.BorderColor = System.Drawing.Color.Silver; this.panel1.BorderRadius = 5; this.panel1.Controls.AddRange(new Smobiler.Core.Controls.MobileControl[] { this.labContent, this.labTitle, this.button1}); this.panel1.Location = new System.Drawing.Point(5, 9); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(290, 123); // // labContent // this.labContent.BackColor = System.Drawing.Color.WhiteSmoke; this.labContent.Location = new System.Drawing.Point(0, 26); this.labContent.Name = "labContent"; this.labContent.Padding = new Smobiler.Core.Controls.Padding(5F); this.labContent.Size = new System.Drawing.Size(290, 54); this.labContent.Text = "可进行数据绑定,添加行,删除行,清空,根据数据源添加,index事件\r\n"; // // labTitle // this.labTitle.BackColor = System.Drawing.Color.WhiteSmoke; this.labTitle.Border = new Smobiler.Core.Controls.Border(0F, 0F, 0F, 1F); this.labTitle.BorderColor = System.Drawing.Color.DarkSeaGreen; this.labTitle.FontSize = 16F; this.labTitle.Name = "labTitle"; this.labTitle.Padding = new Smobiler.Core.Controls.Padding(5F); this.labTitle.Size = new System.Drawing.Size(290, 26); this.labTitle.Text = "分页显示控件"; // // button1 // this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.button1.Location = new System.Drawing.Point(39, 87); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(212, 30); this.button1.Text = "控件介绍"; this.button1.Press += new System.EventHandler(this.button1_Press); // // pageView1 // this.pageView1.Location = new System.Drawing.Point(0, 138); this.pageView1.Name = "pageView1"; this.pageView1.Size = new System.Drawing.Size(300, 220); this.pageView1.TemplateControlName = "demoPageViewTemplate"; this.pageView1.PageIndexChanged += new System.EventHandler(this.pageView1_PageIndexChanged); // // popList1 // this.popList1.Name = "popList1"; this.popList1.Selected += new System.EventHandler(this.popList1_Selected); // // demoPageView // this.Components.AddRange(new Smobiler.Core.Controls.MobileComponent[] { this.popList1}); this.Controls.AddRange(new Smobiler.Core.Controls.MobileControl[] { this.title1, this.panel10}); this.Load += new System.EventHandler(this.demoPageView_Load); this.Name = "demoPageView"; } #endregion private Core.Controls.Title title1; private Core.Controls.Panel panel10; private Core.Controls.Panel panel1; private Core.Controls.Label labContent; private Core.Controls.Label labTitle; private Core.Controls.Button button1; private Core.Controls.PageView pageView1; private Core.Controls.PopList popList1; } }
44.310078
139
0.588174
[ "MIT" ]
lichao8872/SmobilerTutorials
Source/Components/demoPageView.Designer.cs
5,796
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SC.DAL.EF { internal class SupportCenterDbConfiguration : DbConfiguration { public SupportCenterDbConfiguration() { this.SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory()); // SQL Server instantie op machine this.SetProviderServices("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance); this.SetDatabaseInitializer<SupportCenterDbContext>(new SupportCenterDbInitializer()); } } }
29.454545
136
0.777778
[ "MIT" ]
anerach/SupportCenter-Dapper
DAL/EF/SupportCenterDbConfiguration.cs
650
C#
using FluentValidation.Results; namespace AllOverIt.Validation { public interface IValidationInvoker { ValidationResult Validate<TType>(TType instance); ValidationResult Validate<TType, TContext>(TType instance, TContext context); void AssertValidation<TType>(TType instance); void AssertValidation<TType, TContext>(TType instance, TContext context); } }
30.846154
85
0.735661
[ "MIT" ]
TimeTravelPenguin/AllOverIt
Source/AllOverIt.Validation/IValidationInvoker.cs
403
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. namespace Tvl.DebugCommandLine { using System.Runtime.InteropServices; /// <summary> /// This enumeration defines the commands that are provided by this extension. The GUID of this enumeration is the /// command group which these commands are assigned to. /// </summary> [Guid("B9B17AA7-66FB-4BEB-AE17-876222AE8390")] internal enum DebugCommandLineCommand { DebugCommandLineCombo = 0, DebugCommandLineComboGetList = 1, } }
34.789474
118
0.717095
[ "Apache-2.0" ]
sharwell/DebugCommandLine
Tvl.DebugCommandLine/DebugCommandLineCommand.cs
663
C#
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace DataStructures { /// <summary> /// This object represents a parameter with units. This object should be used in most of the places where /// a user specifies a number and its units / unit multiplier. (ie to set the timestep lengths, to set the interpolation /// values for waveforms, etc). /// </summary> [Serializable, TypeConverter(typeof(ExpandableObjectConverter))] public class DimensionedParameter { public static bool Equivalent(DimensionedParameter a, DimensionedParameter b) { if (!Parameter.Equivalent(a.myParameter, b.myParameter)) return false; if (a.ParameterString != b.ParameterString) return false; if (!Units.Equivalent(a.ParameterUnits, b.ParameterUnits)) return false; if (a.ParameterValue != b.ParameterValue) return false; return true; } public Parameter parameter; [Description("The parameter object underlying this dimensioned parameter.")] public Parameter myParameter { get { return parameter; } set { parameter = value; } } /// <summary> /// Forces this dimensioned parameter to take on a manual value with specified units. This will stop use of /// any previously used variable. /// </summary> /// <param name="value"></param> /// <param name="units"></param> public void forceToManualValue(double value, Units units) { this.units = units; this.parameter.forceToManualValue(value); } public Units units; [Description("The units associated with this dimensioned parameter.")] public Units ParameterUnits { get { return units; } set { units = value; } } [Description("Text depiction of the value and units of this dimensioned parameter.")] public string ParameterString { get { return this.ToString(); } } public void setBaseValue(double value) { double orderOfMag = Math.Log10(Math.Abs(value)); Units.Multiplier multToUse = new Units.Multiplier(); if (value != 0) { if (orderOfMag >= 7.5) { multToUse = Units.Multiplier.G; } else if (orderOfMag > 4.5) { multToUse = Units.Multiplier.M; } else if (orderOfMag > 1.5) { multToUse = Units.Multiplier.k; } else if (orderOfMag > -1.5) { multToUse = Units.Multiplier.unity; } else if (orderOfMag > -4.5) { multToUse = Units.Multiplier.m; } else if (orderOfMag > -7.5) { multToUse = Units.Multiplier.u; } else multToUse = Units.Multiplier.n; } else { multToUse = Units.Multiplier.unity; } double unMultipliedValue = value / multToUse.getMultiplierFactor(); this.units.multiplier = multToUse; this.parameter.ManualValue = unMultipliedValue; } [Description("The numerical value of this dimensioned parameter, taking into account unit multipliers.")] public double ParameterValue { get { return this.getBaseValue(); } } public DimensionedParameter(Units units, double manualValue) { this.units = units; this.parameter.forceToManualValue(manualValue); } public DimensionedParameter(Units.Dimension dim) { this.parameter.ManualValue = 1; this.parameter.variable = null; this.units.dimension = dim; this.units.multiplier = Units.Multiplier.unity; } public DimensionedParameter(DimensionedParameter parameter) { this.parameter = parameter.parameter; this.units = parameter.units; } /* /// <summary> /// This returns the manual value of the parameter in "base units", taking into account the unit multiplier. /// IE, if the parameter is 1, and the units are ms, then this returns .001. /// </summary> /// <returns></returns> public double getManualBaseValue() { return units.multiplier * parameter.getManualValue(); } */ /// <summary> /// This returns the value (taking into account variables) of the parameter in base units. /// </summary> /// <param name="variableValues"></param> /// <returns></returns> public double getBaseValue() { return units.multiplier * parameter.getValue(); } /* /// <summary> /// Returns an array of manual base values corresponding to the manual values of /// the DimensionedParameters in the list. /// </summary> /// <param name="?"></param> /// <returns></returns> public static double [] getManualBaseValues(List<DimensionedParameter> list) { if (list == null) return null; double[] ans = new double[list.Count]; for (int i = 0; i < list.Count; i++) { ans[i] = list[i].getManualBaseValue(); } return ans; }*/ /// <summary> /// Returns an array of base values corresponding to the values of the /// DimensionedParameters in the list. /// </summary> /// <param name="list"></param> /// <param name="variableValues"></param> /// <returns></returns> public static double[] getBaseValues(List<DimensionedParameter> list) { if (list == null) return null; double[] ans = new double[list.Count]; for (int i = 0; i < list.Count; i++) { ans[i] = list[i].getBaseValue(); } return ans; } public override string ToString() { return this.parameter.Value.ToString() + " " + this.units.ToString(); } /// <summary> /// Same as ToString, but without the space character /// </summary> /// <returns></returns> public string ToShortString() { return this.parameter.Value.ToString() + this.units.ToString(); } } }
34.126168
125
0.502533
[ "MIT" ]
biswaroopmukherjee/breadboard-cicero
DataStructures/SequenceData/DimensionedParameter.cs
7,303
C#
using GizmoFort.Connector.ERPNext.PublicTypes; using GizmoFort.Connector.ERPNext.WrapperTypes; using System.ComponentModel; namespace GizmoFort.Connector.ERPNext.ERPTypes.Cash_flow_mapping_template { public class ERPCash_flow_mapping_template : ERPNextObjectBase { public ERPCash_flow_mapping_template() : this(new ERPObject(DocType.Cash_flow_mapping_template)) { } public ERPCash_flow_mapping_template(ERPObject obj) : base(obj) { } public static ERPCash_flow_mapping_template Create(string templatename, string mapping) { ERPCash_flow_mapping_template obj = new ERPCash_flow_mapping_template(); obj.template_name = templatename; obj.mapping = mapping; return obj; } public string template_name { get { return data.template_name; } set { data.template_name = value; data.name = value; } } public string mapping { get { return data.mapping; } set { data.mapping = value; } } } //Enums go here }
27.595238
108
0.625539
[ "MIT" ]
dmequus/gizmofort.connector.erpnext
Libs/GizmoFort.Connector.ERPNext/ERPTypes/Cash_flow_mapping_template/ERPCash_flow_mapping_template.cs
1,159
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Query.InternalTrees { /// <summary> /// Base class for set operations - union, intersect, except /// </summary> internal abstract class SetOp : RelOp { #region private state private readonly VarMap[] m_varMap; private readonly VarVec m_outputVars; #endregion #region constructors internal SetOp(OpType opType, VarVec outputs, VarMap left, VarMap right) : this(opType) { m_varMap = new VarMap[2]; m_varMap[0] = left; m_varMap[1] = right; m_outputVars = outputs; } protected SetOp(OpType opType) : base(opType) { } #endregion #region public methods /// <summary> /// 2 children - left, right /// </summary> internal override int Arity { get { return 2; } } /// <summary> /// Map of result vars to the vars of each branch of the setOp /// </summary> internal VarMap[] VarMap { get { return m_varMap; } } /// <summary> /// Get the set of output vars produced /// </summary> internal VarVec Outputs { get { return m_outputVars; } } #endregion } }
24.8125
133
0.505668
[ "Apache-2.0" ]
TerraVenil/entityframework
src/EntityFramework/Core/Query/InternalTrees/SetOp.cs
1,588
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Hazelnut using UnityEngine; using DaggerfallConnect.Utility; using DaggerfallWorkshop.Utility; using DaggerfallWorkshop.Game.UserInterface; using DaggerfallWorkshop.Game.Items; using DaggerfallWorkshop.Game.Banking; namespace DaggerfallWorkshop.Game.UserInterfaceWindows { public class DaggerfallTransportWindow : DaggerfallPopupWindow { #region UI Rects Rect footButtonRect = new Rect(5, 5, 120, 7); Rect horseButtonRect = new Rect(5, 14, 120, 7); Rect cartButtonRect = new Rect(5, 23, 120, 7); Rect shipButtonRect = new Rect(5, 32, 120, 7); Rect exitButtonRect = new Rect(44, 42, 43, 15); // Rect footDisabledRect = new Rect(1, 1, 120, 7); // Can foot option ever be disabled? Rect horseDisabledRect = new Rect(1, 10, 120, 7); Rect cartDisabledRect = new Rect(1, 19, 120, 7); Rect shipDisabledRect = new Rect(1, 28, 120, 7); #endregion #region UI Controls Panel mainPanel = new Panel(); Button footButton; Button horseButton; Button cartButton; Button shipButton; Button exitButton; #endregion #region UI Textures Texture2D baseTexture; Texture2D disabledTexture; #endregion #region Fields const string baseTextureName = "MOVE00I0.IMG"; const string disabledTextureName = "MOVE01I0.IMG"; Vector2 baseSize; KeyCode toggleClosedBinding; #endregion #region Constructors public DaggerfallTransportWindow(IUserInterfaceManager uiManager) : base(uiManager) { // Clear background ParentPanel.BackgroundColor = Color.clear; } #endregion #region Setup Methods protected override void Setup() { // What transport options does the player have? ItemCollection inventory = GameManager.Instance.PlayerEntity.Items; bool hasHorse = GameManager.Instance.TransportManager.HasHorse(); bool hasCart = GameManager.Instance.TransportManager.HasCart(); bool hasShip = GameManager.Instance.TransportManager.ShipAvailiable(); // Load all textures LoadTextures(); // Create interface panel mainPanel.HorizontalAlignment = HorizontalAlignment.Center; mainPanel.VerticalAlignment = VerticalAlignment.Middle; mainPanel.BackgroundTexture = baseTexture; mainPanel.Position = new Vector2(0, 50); mainPanel.Size = baseSize; DFSize disabledTextureSize = new DFSize(122, 36); // Foot button footButton = DaggerfallUI.AddButton(footButtonRect, mainPanel); footButton.OnMouseClick += FootButton_OnMouseClick; // Horse button horseButton = DaggerfallUI.AddButton(horseButtonRect, mainPanel); if (hasHorse) { horseButton.OnMouseClick += HorseButton_OnMouseClick; } else { horseButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, horseDisabledRect, disabledTextureSize); } // Cart button cartButton = DaggerfallUI.AddButton(cartButtonRect, mainPanel); if (hasCart) { cartButton.OnMouseClick += CartButton_OnMouseClick; } else { cartButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, cartDisabledRect, disabledTextureSize); } // Ship button shipButton = DaggerfallUI.AddButton(shipButtonRect, mainPanel); if (hasShip) { shipButton.OnMouseClick += ShipButton_OnMouseClick; } else { shipButton.BackgroundTexture = ImageReader.GetSubTexture(disabledTexture, shipDisabledRect, disabledTextureSize); } // Exit button exitButton = DaggerfallUI.AddButton(exitButtonRect, mainPanel); exitButton.OnMouseClick += ExitButton_OnMouseClick; NativePanel.Components.Add(mainPanel); // Store toggle closed binding for this window toggleClosedBinding = InputManager.Instance.GetBinding(InputManager.Actions.Transport); } #endregion #region Overrides public override void Update() { base.Update(); // Toggle window closed with same hotkey used to open it if (Input.GetKeyUp(toggleClosedBinding)) CloseWindow(); } #endregion #region Private Methods void LoadTextures() { ImageData baseData = ImageReader.GetImageData(baseTextureName); baseTexture = baseData.texture; baseSize = new Vector2(baseData.width, baseData.height); disabledTexture = ImageReader.GetTexture(disabledTextureName); } #endregion #region Event Handlers private void ExitButton_OnMouseClick(BaseScreenComponent sender, Vector2 position) { CloseWindow(); } private void FootButton_OnMouseClick(BaseScreenComponent sender, Vector2 position) { // Reset to normal on foot walking. GameManager.Instance.TransportManager.TransportMode = TransportModes.Foot; CloseWindow(); } private void HorseButton_OnMouseClick(BaseScreenComponent sender, Vector2 position) { // Change to riding a horse. GameManager.Instance.TransportManager.TransportMode = TransportModes.Horse; CloseWindow(); } private void CartButton_OnMouseClick(BaseScreenComponent sender, Vector2 position) { // Change to riding a cart. GameManager.Instance.TransportManager.TransportMode = TransportModes.Cart; CloseWindow(); } private void ShipButton_OnMouseClick(BaseScreenComponent sender, Vector2 position) { // Teleport to your ship, or back. GameManager.Instance.TransportManager.TransportMode = TransportModes.Ship; CloseWindow(); } #endregion } }
34.165803
131
0.632545
[ "MIT" ]
JasonBreen/daggerfall-unity
Assets/Scripts/Game/UserInterfaceWindows/DaggerfallTransportWindow.cs
6,594
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps.ControlPoints; using osu.Game.IO.Serialization; namespace osu.Game.Rulesets.Timing { /// <summary> /// A control point which adds an aggregated multiplier based on the provided <see cref="TimingPoint"/>'s BeatLength and <see cref="DifficultyPoint"/>'s SpeedMultiplier. /// </summary> public class MultiplierControlPoint : IJsonSerializable, IComparable<MultiplierControlPoint> { /// <summary> /// The time in milliseconds at which this <see cref="MultiplierControlPoint"/> starts. /// </summary> public double StartTime; /// <summary> /// The aggregate multiplier which this <see cref="MultiplierControlPoint"/> provides. /// </summary> public double Multiplier => Velocity * DifficultyPoint.SpeedMultiplier * 1000 / TimingPoint.BeatLength; /// <summary> /// The velocity multiplier. /// </summary> public double Velocity = 1; /// <summary> /// The <see cref="TimingControlPoint"/> that provides the timing information for this <see cref="MultiplierControlPoint"/>. /// </summary> public TimingControlPoint TimingPoint = new TimingControlPoint(); /// <summary> /// The <see cref="DifficultyControlPoint"/> that provides additional difficulty information for this <see cref="MultiplierControlPoint"/>. /// </summary> public DifficultyControlPoint DifficultyPoint = new DifficultyControlPoint(); /// <summary> /// Creates a <see cref="MultiplierControlPoint"/>. This is required for JSON serialization /// </summary> public MultiplierControlPoint() { } /// <summary> /// Creates a <see cref="MultiplierControlPoint"/>. /// </summary> /// <param name="startTime">The start time of this <see cref="MultiplierControlPoint"/>.</param> public MultiplierControlPoint(double startTime) { StartTime = startTime; } // ReSharper disable once ImpureMethodCallOnReadonlyValueField public int CompareTo(MultiplierControlPoint other) => StartTime.CompareTo(other?.StartTime); } }
40.6
174
0.637931
[ "MIT" ]
Dragicafit/osu
osu.Game/Rulesets/Timing/MultiplierControlPoint.cs
2,377
C#
using UnityEngine; using UnityEditor; namespace Playground.Editor { public class EditorTest : EditorWindow { [HideInInspector] [SerializeField] private GameObject selectedObj = null; [SerializeField] private EditorData data; private bool DisplayVertices { get { return data.DisplayVertices; } set { if (value != data.DisplayVertices) { data.DisplayVertices = value; SceneView.RepaintAll(); } } } [SerializeField] private Color VerticesColor { get { return data.VerticesColor; } set { if (value != data.VerticesColor) { data.VerticesColor = value; SceneView.RepaintAll(); } } } private bool DepthCull { get { return data.DepthCull; } set { if (value != data.DepthCull) { data.DepthCull = value; SceneView.RepaintAll(); } } } private bool VertexCount { get { return data.VertexCount; } set { if (value != data.VertexCount) { data.VertexCount = value; SceneView.RepaintAll(); } } } private SerializedObject winObj; [MenuItem("Window/EditorTest")] public static void ShowWindow() { GetWindow<EditorTest>(); } public void OnEnable() { //data = CreateInstance<EditorData>(); Undo.undoRedoPerformed += OnUndoRedo; SceneView.onSceneGUIDelegate += OnSceneGUI; // Value init selectedObj = Selection.activeGameObject; // Properties init winObj = new SerializedObject(this); } public void OnGUI() { if (selectedObj == null) { GUILayout.Label("Nothing Selected"); return; } GUILayout.Label("Selected: " + selectedObj.name); DisplayVertices = GUILayout.Toggle(DisplayVertices, "Display Vertices"); if (DisplayVertices) { VerticesColor = EditorGUILayout.ColorField("Vertices Color", VerticesColor); GUILayout.BeginHorizontal(); DepthCull = GUILayout.Toggle(DepthCull, "Depth Cull"); VertexCount = GUILayout.Toggle(VertexCount, "Vertex Count"); GUILayout.EndHorizontal(); } if (GUILayout.Button("Reset Transform (Local)")) { Undo.RecordObject(selectedObj.transform, "Reset transform (Local)"); selectedObj.transform.localPosition = Vector3.zero; selectedObj.transform.localRotation = Quaternion.identity; selectedObj.transform.localScale = Vector3.one; } if (GUILayout.Button("Reset Transform (World)")) { Undo.RecordObject(selectedObj.transform, "Reset transform (World)"); selectedObj.transform.position = Vector3.zero; selectedObj.transform.rotation = Quaternion.identity; selectedObj.transform.localScale = Vector3.one; } if (GUILayout.Button("Mesh Test")) { MeshTest(); } winObj.ApplyModifiedProperties(); CheckRepaint(); } private void CheckRepaint() { SceneView.RepaintAll(); } private void OnSceneGUI(SceneView view) { if (selectedObj == null || !selectedObj.activeInHierarchy) return; EditorGUI.BeginChangeCheck(); data.VerticesColor.a = Handles.RadiusHandle(Quaternion.identity, selectedObj.transform.position, data.VerticesColor.a * 2) / 2; if (EditorGUI.EndChangeCheck()) { Repaint(); } if (Event.current.type != EventType.Repaint) return; MeshFilter filter = selectedObj.GetComponent<MeshFilter>(); if (filter == null) return; Mesh mesh = filter.sharedMesh; if (mesh == null) return; if (DisplayVertices) { if (DepthCull) { Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual; } Handles.color = VerticesColor; Vector3[] verts = mesh.vertices; for (int i = 0; i < verts.Length; i++) { Vector3 worldPos = selectedObj.transform.position + verts[i]; //Handles.SphereHandleCap(0, worldPos, Quaternion.identity, HandleUtility.GetHandleSize(worldPos) * .1f, EventType.Repaint); //Handles.CircleHandleCap(0, worldPos, Quaternion.LookRotation(norms[i]), HandleUtility.GetHandleSize(worldPos) * .1f, EventType.Repaint); //Handles.DotHandleCap(0, worldPos, Quaternion.identity, HandleUtility.GetHandleSize(worldPos) * .025f, EventType.Repaint); Handles.CubeHandleCap(0, worldPos, Quaternion.identity, HandleUtility.GetHandleSize(worldPos) * .075f, EventType.Repaint); //verts[i].x = Handles.ScaleValueHandle(verts[i].x, worldPos, Quaternion.identity, HandleUtility.GetHandleSize(worldPos) * 1.5f, Handles.ConeHandleCap, 0.1f); //verts[i] = Handles.FreeMoveHandle(worldPos, Quaternion.identity, HandleUtility.GetHandleSize(worldPos) * 1f, Vector3.one, Handles.ArrowHandleCap) - selectedObj.transform.position; } if (VertexCount) { Handles.Label(selectedObj.transform.position + Vector3.Cross((SceneView.GetAllSceneCameras()[0].transform.position - selectedObj.transform.position), Vector3.up).normalized * 1f, "vertices: " + verts.Length); } //data.VerticesColor.a = Handles.ScaleValueHandle(data.VerticesColor.a, selectedObj.transform.position, Quaternion.identity, 10f, Handles.ArrowHandleCap, 0.01f); Handles.color = Color.red; //data.VerticesColor.a = Handles.RadiusHandle(Quaternion.identity, selectedObj.transform.position, data.VerticesColor.a * 2) / 2; //mesh.vertices = verts; } } public void MeshTest() { MeshFilter filter = selectedObj.GetComponent<MeshFilter>(); if (filter == null) return; Mesh mesh = filter.sharedMesh; if (mesh == null) return; Vector3[] verts = mesh.vertices; for (int i = 0; i < verts.Length; i++) { verts[i].y -= 1f; } Undo.RecordObject(mesh, "Mesh Test"); mesh.vertices = verts; } private void OnSelectionChange() { selectedObj = Selection.activeGameObject; Repaint(); } private void OnUndoRedo() { if (selectedObj == null) return; MeshFilter filter = selectedObj.GetComponent<MeshFilter>(); if (filter == null) return; Mesh mesh = filter.sharedMesh; if (mesh == null) return; mesh.vertices = mesh.vertices; SceneView.RepaintAll(); } private void OnDisable() { selectedObj = null; SceneView.RepaintAll(); SceneView.onSceneGUIDelegate -= OnSceneGUI; } } }
31.378238
213
0.694518
[ "Apache-2.0" ]
Xenation/Playground
Assets/Projects/Editor/Scripts/EditorTest.cs
6,058
C#