content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime.Settings; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace CoreWithLanguage_1.Controllers { // This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot // implementation at runtime. Multiple different IBot implementations running at different endpoints can be // achieved by specifying a more specific type for the bot constructor argument. [ApiController] public class BotController : ControllerBase { private readonly Dictionary<string, IBotFrameworkHttpAdapter> _adapters = new Dictionary<string, IBotFrameworkHttpAdapter>(); private readonly IBot _bot; private readonly ILogger<BotController> _logger; public BotController( IConfiguration configuration, IEnumerable<IBotFrameworkHttpAdapter> adapters, IBot bot, ILogger<BotController> logger) { _bot = bot ?? throw new ArgumentNullException(nameof(bot)); _logger = logger; var adapterSettings = configuration.GetSection(AdapterSettings.AdapterSettingsKey).Get<List<AdapterSettings>>() ?? new List<AdapterSettings>(); adapterSettings.Add(AdapterSettings.CoreBotAdapterSettings); foreach (var adapter in adapters ?? throw new ArgumentNullException(nameof(adapters))) { var settings = adapterSettings.FirstOrDefault(s => s.Enabled && s.Type == adapter.GetType().FullName); if (settings != null) { _adapters.Add(settings.Route, adapter); } } } [HttpPost] [HttpGet] [Route("api/{route}")] public async Task PostAsync(string route) { if (string.IsNullOrEmpty(route)) { _logger.LogError($"PostAsync: No route provided."); throw new ArgumentNullException(nameof(route)); } if (_adapters.TryGetValue(route, out IBotFrameworkHttpAdapter adapter)) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogInformation($"PostAsync: routed '{route}' to {adapter.GetType().Name}"); } // Delegate the processing of the HTTP POST to the appropriate adapter. // The adapter will invoke the bot. await adapter.ProcessAsync(Request, Response, _bot).ConfigureAwait(false); } else { _logger.LogError($"PostAsync: No adapter registered and enabled for route {route}."); throw new KeyNotFoundException($"No adapter registered and enabled for route {route}."); } } } }
41.038961
156
0.618671
[ "MIT" ]
zlu89/FeelingWell
Feeling Well Bot/CoreWithLanguage_1/Controllers/BotController.cs
3,160
C#
using System; using System.Runtime.Serialization; using MyJetWallet.Domain.Orders; namespace Service.Liquidity.TradingPortfolio.Domain.Models { [DataContract] public class PortfolioTrade { public const string TopicName = "jetwallet-liquidity-tradingportfolio-trades"; [DataMember(Order = 1)] public string TradeId { get; set; } // TradeMessage.Name & SwapMessage.Name [DataMember(Order = 2)] public string AssociateBrokerId { get; set; } // TradeMessage.Name & SwapMessage.BrokerId [DataMember(Order = 3)] public string BaseWalletName { get; set; } // PortfolioWalletId [DataMember(Order = 4)] public string QuoteWalletName { get; set; } // PortfolioWalletId [DataMember(Order = 5)] public string AssociateSymbol { get; set; } //TradeMessage.AssociateSymbol SwapMessage.AssetId1|AssetId2 = swap.AssetId1 + "|" + swap.AssetId2, [DataMember(Order = 6)] public string BaseAsset { get; set; } //TradeMessage.BaseAsset SwapMessage.AssetId1 [DataMember(Order = 7)] public string QuoteAsset { get; set; } //TradeMessage.BaseAsset SwapMessage.AssetId2 [DataMember(Order = 8)] public OrderSide Side { get; set; } //TradeMessage.BaseAsset SwapMessage.Buy проверить сторону [DataMember(Order = 9)] public decimal Price { get; set; } //TradeMessage.BaseAsset [DataMember(Order = 10)] public decimal BaseVolume { get; set; } [DataMember(Order = 11)] public decimal QuoteVolume { get; set; } [DataMember(Order = 12)] public decimal BaseVolumeInUsd { get; set; } // из Portfolio [DataMember(Order = 13)] public decimal QuoteVolumeInUsd { get; set; }// из Portfolio [DataMember(Order = 14)] public decimal BaseAssetPriceInUsd { get; set; }// из Portfolio [DataMember(Order = 15)] public decimal QuoteAssetPriceInUsd { get; set; }// из Portfolio [DataMember(Order = 16)] public DateTime DateTime { get; set; } //Now [DataMember(Order = 17)] public string Source { get; set; } //TradeMessage.Source SwapMessage."Converter" [DataMember(Order = 18)] public string Comment { get; set; }//TradeMessage.Comment SwapMessage."Swap with client" [DataMember(Order = 19)] public string User { get; set; } // User SwapMessage."Converter" [DataMember(Order = 20)] public string FeeAsset { get; set; } //TradeMessage.FeeAsset SwapMessage.AssetId2 [DataMember(Order = 21)] public decimal FeeVolume { get; set; }//TradeMessage.FeeVolume SwapMessage.0 [DataMember(Order = 22)] public decimal FeeVolumeInUsd { get; set; } [DataMember(Order = 23)] public decimal FeeAssetPriceInUsd { get; set; } [DataMember(Order = 24)] public PortfolioTradeType Type { get; set; } = PortfolioTradeType.None; [DataMember(Order = 100)] public long Id { get; set; } } }
75.657895
179
0.682435
[ "MIT" ]
MyJetWallet/Service.Liquidity.TradingPortfolio
src/Service.Liquidity.TradingPortfolio.Domain.Models/PortfolioTrade.cs
2,901
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("13.DivisionWithoutResidue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("13.DivisionWithoutResidue")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9b2647df-385b-427d-ad1c-7b7a16edadef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.748419
[ "MIT" ]
V-Uzunov/Soft-Uni-Education
01.ProgrammingBasicsC#/04.SimpleLoops/13.DivisionWithoutResidue/Properties/AssemblyInfo.cs
1,426
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ namespace GameFramework.Sound { /// <summary> /// 声音辅助器接口。 /// </summary> public interface ISoundHelper { /// <summary> /// 释放声音资源。 /// </summary> /// <param name="soundAsset">要释放的声音资源。</param> void ReleaseSoundAsset(object soundAsset); } }
26.818182
63
0.476271
[ "MIT" ]
823040692/Frame
GameFramework/Sound/ISoundHelper.cs
641
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.MachineLearningServices.V20210701.Inputs { /// <summary> /// Settings for a personal compute instance. /// </summary> public sealed class PersonalComputeInstanceSettingsArgs : Pulumi.ResourceArgs { /// <summary> /// A user explicitly assigned to a personal compute instance. /// </summary> [Input("assignedUser")] public Input<Inputs.AssignedUserArgs>? AssignedUser { get; set; } public PersonalComputeInstanceSettingsArgs() { } } }
29.344828
81
0.681551
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/MachineLearningServices/V20210701/Inputs/PersonalComputeInstanceSettingsArgs.cs
851
C#
#region Usings using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Eshva.Poezd.Core.Pipeline; #endregion namespace Eshva.Poezd.Core.IntegrationTests.Tools { /// <summary> /// An empty handler registry. /// </summary> [ExcludeFromCodeCoverage] internal class EmptyHandlerRegistry : IHandlerRegistry { /// <summary> /// Creates a new instance of handler registry. /// </summary> public EmptyHandlerRegistry() { HandlersGroupedByMessageType = new Dictionary<Type, Type[]> { {typeof(string), new[] {typeof(string)}} }; } /// <inheritdoc /> public IReadOnlyDictionary<Type, Type[]> HandlersGroupedByMessageType { get; } } }
22.30303
82
0.679348
[ "MIT" ]
Eshva/Eshva.Poezd
tests/Eshva.Poezd.Core.IntegrationTests/Tools/EmptyHandlerRegistry.cs
736
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.ElasticPool.Services; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Azure.Commands.Sql.Common; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Commands.Sql.Database.Services { /// <summary> /// Adapter for database operations /// </summary> public class AzureSqlDatabaseAdapter { /// <summary> /// Gets or sets the AzureSqlDatabaseCommunicator which has all the needed management clients /// </summary> private AzureSqlDatabaseCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the AzureSqlElasticPoolCommunicator which has all the needed management clients /// </summary> private AzureSqlElasticPoolCommunicator ElasticPoolCommunicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="context">The current context</param> public AzureSqlDatabaseAdapter(IAzureContext context) { Context = context; _subscription = context?.Subscription; Communicator = new AzureSqlDatabaseCommunicator(Context); ElasticPoolCommunicator = new AzureSqlElasticPoolCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database</param> /// <returns>The Azure Sql Database object</returns> internal AzureSqlDatabaseModel GetDatabase(string resourceGroupName, string serverName, string databaseName) { var resp = Communicator.Get(resourceGroupName, serverName, databaseName); return CreateDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets an Azure Sql Database by name with additional information. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database</param> /// <returns>The Azure Sql Database object</returns> internal AzureSqlDatabaseModelExpanded GetDatabaseExpanded(string resourceGroupName, string serverName, string databaseName) { var resp = Communicator.GetExpanded(resourceGroupName, serverName, databaseName); return CreateExpandedDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListDatabases(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((db) => { return CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Gets a list of Azure Sql Databases with additional information. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModelExpanded> ListDatabasesExpanded(string resourceGroupName, string serverName) { var resp = Communicator.ListExpanded(resourceGroupName, serverName); return resp.Select((db) => { return CreateExpandedDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database with new AutoRest SDK. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database from AutoRest SDK</returns> internal AzureSqlDatabaseModel UpsertDatabaseWithNewSdk(string resourceGroup, string serverName, AzureSqlDatabaseCreateOrUpdateModel model) { // Construct the ARM resource Id of the pool string elasticPoolId = string.IsNullOrWhiteSpace(model.Database.ElasticPoolName) ? null : AzureSqlDatabaseModel.PoolIdTemplate.FormatInvariant( _subscription.Id, resourceGroup, serverName, model.Database.ElasticPoolName); // Use AutoRest SDK var resp = Communicator.CreateOrUpdate(resourceGroup, serverName, model.Database.DatabaseName, new Management.Sql.Models.Database { Location = model.Database.Location, Tags = model.Database.Tags, Collation = model.Database.CollationName, Sku = string.IsNullOrWhiteSpace(model.Database.SkuName) ? null : new Sku() { Name = model.Database.SkuName, Tier = model.Database.Edition, Family = model.Database.Family, Capacity = model.Database.Capacity }, MaxSizeBytes = model.Database.MaxSizeBytes, ReadScale = model.Database.ReadScale.ToString(), SampleName = model.SampleName, ZoneRedundant = model.Database.ZoneRedundant, ElasticPoolId = elasticPoolId, LicenseType = model.Database.LicenseType, AutoPauseDelay = model.Database.AutoPauseDelayInMinutes, MinCapacity = model.Database.MinimumCapacity, HighAvailabilityReplicaCount = model.Database.HighAvailabilityReplicaCount, RequestedBackupStorageRedundancy = model.Database.RequestedBackupStorageRedundancy, SecondaryType = model.Database.SecondaryType, MaintenanceConfigurationId = MaintenanceConfigurationHelper.ConvertMaintenanceConfigurationIdArgument(model.Database.MaintenanceConfigurationId, _subscription.Id), IsLedgerOn = model.Database.EnableLedger, }); return CreateDatabaseModelFromResponse(resourceGroup, serverName, resp); } /// <summary> /// Deletes a database /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database to delete</param> public void RemoveDatabase(string resourceGroupName, string serverName, string databaseName) { Communicator.Remove(resourceGroupName, serverName, databaseName); } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModel CreateDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.Models.Database database) { return new AzureSqlDatabaseModel(resourceGroup, serverName, database); } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModel CreateDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.Database database) { return new AzureSqlDatabaseModel(resourceGroup, serverName, database); } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModelExpanded CreateExpandedDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.Database database) { return new AzureSqlDatabaseModelExpanded(resourceGroup, serverName, database); } /// <summary> /// Failovers a database /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database to failover</param> /// <param name="replicaType">Whether to failover primary replica or readable secondary replica</param> public void FailoverDatabase(string resourceGroupName, string serverName, string databaseName, string replicaType) { Communicator.Failover(resourceGroupName, serverName, databaseName, replicaType); } internal IEnumerable<AzureSqlDatabaseActivityModel> ListDatabaseActivity(string resourceGroupName, string serverName, string elasticPoolName, string databaseName, Guid? operationId) { if (!string.IsNullOrEmpty(elasticPoolName)) { var response = ElasticPoolCommunicator.ListDatabaseActivity(resourceGroupName, serverName, elasticPoolName); IEnumerable<AzureSqlDatabaseActivityModel> list = response.Select((r) => { return new AzureSqlDatabaseActivityModel() { DatabaseName = r.DatabaseName, EndTime = r.EndTime, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorMessage, ErrorSeverity = r.ErrorSeverity, Operation = r.Operation, OperationId = r.OperationId, PercentComplete = r.PercentComplete, ServerName = r.ServerName, StartTime = r.StartTime, State = r.State, Properties = new AzureSqlDatabaseActivityModel.DatabaseState() { Current = new Dictionary<string, string>() { {"CurrentElasticPoolName", r.CurrentElasticPoolName}, {"CurrentServiceObjectiveName", r.CurrentServiceObjective}, }, Requested = new Dictionary<string, string>() { {"RequestedElasticPoolName", r.RequestedElasticPoolName}, {"RequestedServiceObjectiveName", r.RequestedServiceObjective}, } } }; }); // Check if we have a database name constraint if (!string.IsNullOrEmpty(databaseName)) { list = list.Where(pl => string.Equals(pl.DatabaseName, databaseName, StringComparison.OrdinalIgnoreCase)); } return list.ToList(); } else { var response = Communicator.ListOperations(resourceGroupName, serverName, databaseName); IEnumerable<AzureSqlDatabaseActivityModel> list = response.Select((r) => { return new AzureSqlDatabaseActivityModel() { DatabaseName = r.DatabaseName, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorDescription, ErrorSeverity = r.ErrorSeverity, Operation = r.Operation, OperationId = Guid.Parse(r.Name), PercentComplete = r.PercentComplete, ServerName = r.ServerName, StartTime = r.StartTime, State = r.State, Properties = new AzureSqlDatabaseActivityModel.DatabaseState() { Current = new Dictionary<string, string>(), Requested = new Dictionary<string, string>() }, EstimatedCompletionTime = r.EstimatedCompletionTime, Description = r.Description, IsCancellable = r.IsCancellable }; }); // Check if we have a operation id constraint if (operationId.HasValue) { list = list.Where(pl => Guid.Equals(pl.OperationId, operationId)); } return list.ToList(); } } internal IEnumerable<AzureSqlDatabaseActivityModel> CancelDatabaseActivity(string resourceGroupName, string serverName, string elasticPoolName, string databaseName, Guid? operationId) { if (!string.IsNullOrEmpty(elasticPoolName)) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Microsoft.Azure.Commands.Sql.Properties.Resources.ElasticPoolDatabaseActivityCancelNotSupported)); } if (!operationId.HasValue) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Microsoft.Azure.Commands.Sql.Properties.Resources.OperationIdRequired)); } Communicator.CancelOperation(resourceGroupName, serverName, databaseName, operationId.Value); // After Cancel event is fired, state will be in 'CancelInProgress' for a while but should expect to finish in a minute return ListDatabaseActivity(resourceGroupName, serverName, elasticPoolName, databaseName, operationId); } public void RenameDatabase(string resourceGroupName, string serverName, string databaseName, string newName) { Communicator.Rename(resourceGroupName, serverName, databaseName, newName); } /// <summary> /// Get database sku name based on edition /// Edition | SkuName /// GeneralPurpose | GP /// BusinessCritical | BC /// Hyperscale | HS /// Standard | Standard /// Basic | Basic /// Premium | Premium /// /// Also adds _S in the end of SkuName in case if it is Serverless /// </summary> /// <param name="tier">Azure Sql database edition</param> /// <param name="isServerless">If sku should be serverless type</param> /// <returns>The sku name</returns> public static string GetDatabaseSkuName(string tier, bool isServerless = false) { if (string.IsNullOrWhiteSpace(tier)) { return null; } return (SqlSkuUtils.GetVcoreSkuPrefix(tier) ?? tier) + (isServerless ? "_S" : ""); } /// <summary> /// Gets the Sku for the Dtu database. /// </summary> /// <param name="requestedServiceObjectiveName">Requested service objective name of the Azure Sql database</param> /// <param name="edition">Edition of the Azure Sql database</param> /// <returns></returns> public static Sku GetDtuDatabaseSku(string requestedServiceObjectiveName, string edition) { Sku sku = null; if (!string.IsNullOrWhiteSpace(requestedServiceObjectiveName) || !string.IsNullOrWhiteSpace(edition)) { sku = new Sku() { Name = string.IsNullOrWhiteSpace(requestedServiceObjectiveName) ? GetDatabaseSkuName(edition) : requestedServiceObjectiveName, Tier = edition }; } return sku; } /// <summary> /// Map external BackupStorageRedundancy value (Geo/Local/Zone) to internal (GRS/LRS/ZRS) /// </summary> /// <param name="backupStorageRedundancy">Backup storage redundancy</param> /// <returns>internal backupStorageRedundancy</returns> private static string MapExternalBackupStorageRedundancyToInternal(string backupStorageRedundancy) { if (string.IsNullOrWhiteSpace(backupStorageRedundancy)) { return null; } switch (backupStorageRedundancy.ToLower()) { case "geo": return "GRS"; case "local": return "LRS"; case "zone": return "ZRS"; default: return null; } } } }
49.271226
192
0.587478
[ "MIT" ]
Agazoth/azure-powershell
src/Sql/Sql/Database/Services/AzureSqlDatabaseAdapter.cs
20,468
C#
using System; using System.Reflection; namespace HITUOISR.Toolkit.Settings { /// <summary> /// 指定获取设置默认值的成员。 /// </summary> [AttributeUsage(AttributeTargets.Property)] public class SettingsDefaultValueMemberAttribute : Attribute { /// <summary> /// 用于获取默认值的成员名称。 /// </summary> public string MemberName { get; } /// <summary> /// 成员所在的类型。 /// </summary> public Type? MemberDeclaringType { get; set; } /// <summary> /// 初始化。 /// </summary> /// <param name="memberName">用于获取默认值的成员名称。</param> public SettingsDefaultValueMemberAttribute(string memberName) => MemberName = memberName; /// <summary> /// 获取默认值。 /// </summary> /// <param name="fallbackType">当成员所在类型未指定时,使用的类型。</param> /// <returns>得到的默认值。</returns> public object? GetDefaultValue(Type fallbackType) { Type type = MemberDeclaringType ?? fallbackType; var accessor = GetPropertyAccessor(type) ?? GetFieldAccessor(type) ?? GetMethodAccessor(type); if (accessor is null) { throw new ArgumentException($"Could not find public static member (property, field, or method) named '{MemberName}' on {type.FullName}."); } return accessor(); } private Func<object?>? GetFieldAccessor(Type? type) { FieldInfo? fieldInfo = null; for (var reflectionType = type; reflectionType != null; reflectionType = reflectionType.BaseType) { fieldInfo = reflectionType.GetRuntimeField(MemberName); if (fieldInfo != null) break; } if (fieldInfo == null || !fieldInfo.IsStatic) return null; return () => fieldInfo.GetValue(null); } private Func<object?>? GetPropertyAccessor(Type? type) { PropertyInfo? propInfo = null; for (var reflectionType = type; reflectionType != null; reflectionType = reflectionType.BaseType) { propInfo = reflectionType.GetRuntimeProperty(MemberName); if (propInfo != null) break; } if (propInfo == null || propInfo.GetMethod == null || !propInfo.GetMethod.IsStatic) return null; return () => propInfo.GetValue(null); } private Func<object?>? GetMethodAccessor(Type? type) { MethodInfo? methodInfo = null; for (var reflectionType = type; reflectionType != null; reflectionType = reflectionType.BaseType) { methodInfo = reflectionType.GetRuntimeMethod(MemberName, Array.Empty<Type>()); if (methodInfo != null) break; } if (methodInfo == null || !methodInfo.IsStatic) return null; return () => methodInfo.Invoke(null, null); } } }
33.064516
154
0.547967
[ "MIT" ]
HIT-UOI-SR/HITUOISR.Toolkit
HITUOISR.Toolkit.Settings.Model/src/SettingsDefaultValueMemberAttribute.cs
3,241
C#
using System.Collections.Generic; using System.Threading.Tasks; using ExamKing.Application.Consts; using ExamKing.Application.Mappers; using ExamKing.Application.Services; using Furion.DatabaseAccessor; using Mapster; using Microsoft.AspNetCore.Mvc; namespace ExamKing.WebApp.Teacher { /// <summary> /// 试卷接口 /// </summary> public class ExamController : ApiControllerBase { private readonly IExamService _examService; private readonly IQuestionService _questionService; /// <summary> /// 依赖注入 /// </summary> public ExamController( IExamService examService, IQuestionService questionService) { _examService = examService; _questionService = questionService; } /// <summary> /// 手动组卷 /// </summary> /// <param name="addExamInput"></param> /// <returns></returns> [UnitOfWork] public async Task<ExamOutput> InsertAddExam(AddExamInput addExamInput) { var teacher = await GetTeacher(); var addExamDto = addExamInput.Adapt<ExamDto>(); addExamDto.TeacherId = teacher.Id; var questions = new List<ExamquestionDto>(); foreach (var item in addExamInput.Selects) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Select; questions.Add(q); } foreach (var item in addExamInput.Singles) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Single; questions.Add(q); } foreach (var item in addExamInput.Judges) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Judge; questions.Add(q); } addExamDto.Examquestions = questions; var exam = await _examService.CreateExam(addExamDto); return exam.Adapt<ExamOutput>(); } /// <summary> /// 更新试卷 /// </summary> /// <param name="addExamInput"></param> /// <returns></returns> [UnitOfWork] public async Task<ExamOutput> UpdateEditExam(EditExamInput editExamInput) { var teacher = await GetTeacher(); var addExamDto = editExamInput.Adapt<ExamDto>(); addExamDto.TeacherId = teacher.Id; var questions = new List<ExamquestionDto>(); foreach (var item in editExamInput.Selects) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Select; questions.Add(q); } foreach (var item in editExamInput.Singles) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Single; questions.Add(q); } foreach (var item in editExamInput.Judges) { var q = item.Adapt<ExamquestionDto>(); q.QuestionType = QuestionTypeConst.Judge; questions.Add(q); } addExamDto.Examquestions = questions; var exam = await _examService.UpdateExam(addExamDto); return exam.Adapt<ExamOutput>(); } /// <summary> /// 删除试卷 /// </summary> /// <param name="id"></param> /// <returns></returns> [UnitOfWork] public async Task<string> DeleteRemoveExam(int id) { await _examService.DeleteExam(id); return "success"; } /// <summary> /// 查询考试列表 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public async Task<PagedList<ExamCourseOutput>> GetExamList( [FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 10) { var teacher = await GetTeacher(); var teacherId = teacher.Id; var exams = await _examService.FindExamAllByTeacherAndPage(teacherId, pageIndex, pageSize); return exams.Adapt<PagedList<ExamCourseOutput>>(); } /// <summary> /// 查询考试信息 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<ExamCourseOutput> GetExamInfo(int id) { var exams = await _examService.FindExamById(id); return exams.Adapt<ExamCourseOutput>(); } /// <summary> /// 查询考试是非题列表 /// </summary> /// <param name="id">考试id</param> /// <returns></returns> public async Task<List<ExamquestionOutput>> GetJudges(int id) { var judges = await _questionService.FindJudgeByExam(id); return judges.Adapt<List<ExamquestionOutput>>(); } /// <summary> /// 查询考试多选题列表 /// </summary> /// <param name="id">考试id</param> /// <returns></returns> public async Task<List<ExamquestionOutput>> GetSelects(int id) { var judges = await _questionService.FindSelectByExam(id); return judges.Adapt<List<ExamquestionOutput>>(); } /// <summary> /// 查询考试单选题列表 /// </summary> /// <param name="id">考试id</param> /// <returns></returns> public async Task<List<ExamquestionOutput>> GetSingles(int id) { var judges = await _questionService.FindSingleByExam(id); return judges.Adapt<List<ExamquestionOutput>>(); } } }
31.75
103
0.540055
[ "MIT" ]
pig0224/ExamKing
ExamKing.WebApp.Teacher/Controllers/ExamController.cs
5,972
C#
using GalaSoft.MvvmLight; using PowerApps_Theme_Editor.Model; namespace PowerApps_Theme_Editor.ViewModel { /// <summary> /// This class contains properties that a View can data bind to. /// </summary> public class PaletteViewModel : ViewModelBase { public Palette Palette { get; set; } private string _name; private string _value; private string _type; private string _phoneValue; public string name { get { return this._name; } set { Set(ref this._name, value); this.Palette.name = value; } } public string value { get { return this._value; } set { Set(ref this._value, value); this.Palette.value = value; } } public string type { get { return this._type; } set { Set(ref this._type, value); this.Palette.type = value; } } public string phoneValue { get { return this._phoneValue; } set { Set(ref this._phoneValue, value); this.Palette.phoneValue = value; } } /// <summary> /// Initializes a new instance of the PaletteViewModel class. /// </summary> public PaletteViewModel(Palette palette) { this.Palette = palette; this._name = palette.name; this._phoneValue = palette.phoneValue; this._value = palette.value; this._type = palette.type; } } }
23.195122
69
0.446372
[ "MIT" ]
AzureMentor/powerapps-tools
Tools/Apps/Microsoft.PowerApps.ThemeEditor/ViewModel/PaletteViewModel.cs
1,904
C#
// Copyright © 2010 onwards, Andrew Whewell // All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using VirtualRadar.Interface.BaseStation; using VirtualRadar.Interface; using VirtualRadar.Interface.WebServer; using VirtualRadar.Interface.WebSite; using VirtualRadar.Interface.Listener; namespace Test.VirtualRadar.Interface { [TestClass] public class PluginStartupParametersTests { [TestMethod] public void PluginStartupParameters_Constructor_Initialises_To_Known_State_And_Properties_Work() { var fsxAircraftList = new Mock<ISimpleAircraftList>(MockBehavior.Strict).Object; var uPnpManager = new Mock<IUniversalPlugAndPlayManager>(MockBehavior.Strict).Object; var webSite = new Mock<IWebSite>(MockBehavior.Strict).Object; var folder = "Abc"; var startupParameters = new PluginStartupParameters(fsxAircraftList, uPnpManager, webSite, folder); Assert.AreSame(fsxAircraftList, startupParameters.FlightSimulatorAircraftList); Assert.AreSame(uPnpManager, startupParameters.UPnpManager); Assert.AreSame(webSite, startupParameters.WebSite); Assert.AreEqual(folder, startupParameters.PluginFolder); } } }
64.044444
750
0.762665
[ "BSD-3-Clause" ]
AlexAX135/vrs
Test/Test.VirtualRadar.Interface/PluginStartupParametersTests.cs
2,885
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Web.Http.Dependencies; using Ninject; using Ninject.Syntax; namespace JabbR.Infrastructure { public class NinjectDependencyScope : IDependencyScope { private IResolutionRoot resolver; internal NinjectDependencyScope(IResolutionRoot resolver) { Contract.Assert(resolver != null); this.resolver = resolver; } public void Dispose() { IDisposable disposable = resolver as IDisposable; if (disposable != null) disposable.Dispose(); resolver = null; } public object GetService(Type serviceType) { if (resolver == null) throw new ObjectDisposedException("this", "This scope has already been disposed"); return resolver.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { if (resolver == null) throw new ObjectDisposedException("this", "This scope has already been disposed"); return resolver.GetAll(serviceType); } } public class NinjectWebApiDependencyResolver : NinjectDependencyScope, IDependencyResolver { private IKernel kernel; public NinjectWebApiDependencyResolver(IKernel kernel) : base(kernel) { this.kernel = kernel; } public IDependencyScope BeginScope() { return new NinjectDependencyScope(kernel.BeginBlock()); } } }
26.031746
98
0.614024
[ "MIT" ]
AAPT/jean0226case1322
JabbR/Infrastructure/NinjectWebApiDependencyResolver.cs
1,642
C#
using Solnet.Wallet; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Solnet.Raydium { /// <summary> /// Collection of Raydium specific consts /// </summary> public class Consts { public const string STAKE_PROGRAM_ID = "EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"; public const string STAKE_PROGRAM_ID_V4 = "CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T"; public const string STAKE_PROGRAM_ID_V5 = "9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z"; public const string LIQUIDITY_POOL_PROGRAM_ID_V4 = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"; public const string RAYDIUM_SINGLE_SIDED_STAKING_POOL = "EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q"; /// <summary> /// The public key of the sysvar clock account. /// </summary> public static readonly PublicKey SYSVAR_CLOCK_PUBKEY = new("SysvarC1ock11111111111111111111111111111111"); } }
25.04878
114
0.740019
[ "MIT" ]
bmresearch/Solnet.Raydium
Solnet.Raydium/Consts.cs
1,029
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace UsersApi.Tests.EndToEnd.Helpers { public static class TestHttpClientFactory { public static HttpClient Create() { var webhostBuilder = new WebHostBuilder(); webhostBuilder.UseStartup<Startup>(); webhostBuilder.ConfigureAppConfiguration((context, config) => { config.AddJsonFile("appsettings.json"); }); var testServer = new TestServer(webhostBuilder); return testServer.CreateClient(); } } }
27.62963
73
0.660858
[ "MIT" ]
BlackOpts/RestAPIASP.NET
Part 8 Testing RESTFul API/UsersApi.Tests.EndToEnd/Helpers/TestHttpClientFactory.cs
748
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Itsu")] [assembly: AssemblyDescription("Simple datetime helper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Itsu")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("aed04e87-1239-4184-9572-0e6a860e23a0")] // 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.*")]
37.571429
84
0.75057
[ "Unlicense" ]
asakura89/Deto
Properties/AssemblyInfo.cs
1,318
C#
namespace AngleSharp.Core.Tests.Css { using AngleSharp.Core.Tests.Mocks; using AngleSharp.Dom; using NUnit.Framework; [TestFixture] public class SlickspeedTests { IDocument document; [TestFixtureSetUp] public void Setup() { var config = Configuration.Default.SetCulture("en-US").With(new EnableScripting()); document = Assets.w3c_selectors.ToHtmlDocument(config); } [Test] public void SlickspeedFindBodyElement() { var result = document.QuerySelectorAll("body"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindDivElement() { var result = document.QuerySelectorAll("div"); Assert.AreEqual(51, result.Length); } [Test] public void SlickspeedFindBodyDivElement() { var result = document.QuerySelectorAll("body div"); Assert.AreEqual(51, result.Length); } [Test] public void SlickspeedFindDivPElement() { var result = document.QuerySelectorAll("div p"); Assert.AreEqual(140, result.Length); } [Test] public void SlickspeedFindDivPChildElement() { var result = document.QuerySelectorAll("div > p"); Assert.AreEqual(134, result.Length); } [Test] public void SlickspeedFindDivPSiblingElement() { var result = document.QuerySelectorAll("div + p"); Assert.AreEqual(22, result.Length); } [Test] public void SlickspeedFindDivPFollowingElement() { var result = document.QuerySelectorAll("div ~ p"); Assert.AreEqual(183, result.Length); } [Test] public void SlickspeedFindDivClassExaClassMpleElement() { var result = document.QuerySelectorAll("div[class^=exa][class$=mple]"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindDivPAElement() { var result = document.QuerySelectorAll("div p a"); Assert.AreEqual(12, result.Length); } [Test] public void SlickspeedFindDivOrPOrAElement() { var result = document.QuerySelectorAll("div, p, a"); Assert.AreEqual(671, result.Length); } [Test] public void SlickspeedFindNoteElement() { var result = document.QuerySelectorAll(".note"); Assert.AreEqual(14, result.Length); } [Test] public void SlickspeedFindDivExampleElement() { var result = document.QuerySelectorAll("div.example"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindUlTocline2Element() { var result = document.QuerySelectorAll("ul .tocline2"); Assert.AreEqual(12, result.Length); } [Test] public void SlickspeedFindDivExampleDivNoteElement() { var result = document.QuerySelectorAll("div.example, div.note"); Assert.AreEqual(44, result.Length); } [Test] public void SlickspeedFindTitleElement() { var result = document.QuerySelectorAll("#title"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindH1TitleElement() { var result = document.QuerySelectorAll("h1#title"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindDivTitleElement() { var result = document.QuerySelectorAll("div #title"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindUlTocLiTocline2Element() { var result = document.QuerySelectorAll("ul.toc li.tocline2"); Assert.AreEqual(12, result.Length); } [Test] public void SlickspeedFindUlTocLiTocline2ChildElement() { var result = document.QuerySelectorAll("ul.toc > li.tocline2"); Assert.AreEqual(12, result.Length); } [Test] public void SlickspeedFindH1TitleDivPElement() { var result = document.QuerySelectorAll("h1#title + div > p"); Assert.AreEqual(0, result.Length); } [Test] public void SlickspeedFindH1IdContainsSelectorsElement() { var result = document.QuerySelectorAll("h1[id]:contains(Selectors)"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindAHrefLangClassElement() { var result = document.QuerySelectorAll("a[href][lang][class]"); Assert.AreEqual(1, result.Length); } [Test] public void SlickspeedFindDivClassElement() { var result = document.QuerySelectorAll("div[class]"); Assert.AreEqual(51, result.Length); } [Test] public void SlickspeedFindDivClassExampleElement() { var result = document.QuerySelectorAll("div[class=example]"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindDivClassExaElement() { var result = document.QuerySelectorAll("div[class^=exa]"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindDivClassMpleElement() { var result = document.QuerySelectorAll("div[class$=mple]"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindDivClassEElement() { var result = document.QuerySelectorAll("div[class*=e]"); Assert.AreEqual(50, result.Length); } [Test] public void SlickspeedFindDivClassDialogElement() { var result = document.QuerySelectorAll("div[class|=dialog]"); Assert.AreEqual(0, result.Length); } [Test] public void SlickspeedFindDivClassMade_UpElement() { var result = document.QuerySelectorAll("div[class!=made_up]"); Assert.AreEqual(51, result.Length); } [Test] public void SlickspeedFindDivClassContainsExampleElement() { var result = document.QuerySelectorAll("div[class~=example]"); Assert.AreEqual(43, result.Length); } [Test] public void SlickspeedFindDivNotExampleElement() { var result = document.QuerySelectorAll("div:not(.example)"); Assert.AreEqual(8, result.Length); } [Test] public void SlickspeedFindPContainsSelectorsElement() { var result = document.QuerySelectorAll("p:contains(selectors)"); Assert.AreEqual(54, result.Length); } [Test] public void SlickspeedFindPNthChildEvenElement() { var result = document.QuerySelectorAll("p:nth-child(even)"); Assert.AreEqual(158, result.Length); } [Test] public void SlickspeedFindPNthChild2NElement() { var result = document.QuerySelectorAll("p:nth-child(2n)"); Assert.AreEqual(158, result.Length); } [Test] public void SlickspeedFindPNthChildOddElement() { var result = document.QuerySelectorAll("p:nth-child(odd)"); Assert.AreEqual(166, result.Length); } [Test] public void SlickspeedFindPNthChild2N1Element() { var result = document.QuerySelectorAll("p:nth-child(2n+1)"); Assert.AreEqual(166, result.Length); } [Test] public void SlickspeedFindPNthChildNElement() { var result = document.QuerySelectorAll("p:nth-child(n)"); Assert.AreEqual(324, result.Length); } [Test] public void SlickspeedFindPOnlyChildElement() { var result = document.QuerySelectorAll("p:only-child"); Assert.AreEqual(3, result.Length); } [Test] public void SlickspeedFindPLastChildElement() { var result = document.QuerySelectorAll("p:last-child"); Assert.AreEqual(19, result.Length); } [Test] public void SlickspeedFindPFirstChildElement() { var result = document.QuerySelectorAll("p:first-child"); Assert.AreEqual(54, result.Length); } } }
29.4
95
0.567234
[ "MIT" ]
Livven/AngleSharp
AngleSharp.Core.Tests/Css/Slickspeed.cs
8,822
C#
using CarouselView.FormsPlugin.Abstractions; using CarouselView.FormsPlugin.UWP; using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Xamarin.Forms.Platform.UWP; using System.ComponentModel; using System.Collections.Generic; using Windows.UI.Xaml.Media; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.UI.Xaml.Shapes; using System.Collections.Specialized; using Xamarin.Forms; using System.Diagnostics; [assembly: ExportRenderer(typeof(CarouselViewControl), typeof(CarouselViewRenderer))] namespace CarouselView.FormsPlugin.UWP { /// <summary> /// CarouselView Renderer /// </summary> public class CarouselViewRenderer : ViewRenderer<CarouselViewControl, UserControl> { bool orientationChanged; FlipViewControl nativeView; FlipView flipView; StackPanel indicators; ColorConverter converter; SolidColorBrush selectedColor; SolidColorBrush fillColor; double ElementWidth; double ElementHeight; // To hold all the rendered views ObservableCollection<FrameworkElement> Source; // To hold the indicators dots ObservableCollection<Shape> Dots; // To manage SizeChanged Timer timer; bool _disposed; // To avoid triggering Position changed more than once bool isChangingPosition; ScrollViewer ScrollingHost; Windows.UI.Xaml.Controls.Button prevBtn; Windows.UI.Xaml.Controls.Button nextBtn; protected override void OnElementChanged(ElementChangedEventArgs<CarouselViewControl> e) { base.OnElementChanged(e); if (Control == null) { // Instantiate the native control and assign it to the Control property with // the SetNativeControl method orientationChanged = true; } if (e.OldElement != null) { // Unsubscribe from event handlers and cleanup any resources /*if (flipView != null) { flipView.Loaded -= FlipView_Loaded; flipView.SelectionChanged -= FlipView_SelectionChanged; flipView.SizeChanged -= FlipView_SizeChanged; }*/ if (Element == null) return; if (Element.ItemsSource != null && Element.ItemsSource is INotifyCollectionChanged) ((INotifyCollectionChanged)Element.ItemsSource).CollectionChanged -= ItemsSource_CollectionChanged; } if (e.NewElement != null) { Element.SizeChanged += Element_SizeChanged; // Configure the control and subscribe to event handlers if (Element.ItemsSource != null && Element.ItemsSource is INotifyCollectionChanged) ((INotifyCollectionChanged)Element.ItemsSource).CollectionChanged += ItemsSource_CollectionChanged; } } async void ItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // NewItems contains the item that was added. // If NewStartingIndex is not -1, then it contains the index where the new item was added. if (e.Action == NotifyCollectionChangedAction.Add) { InsertPage(Element?.ItemsSource.GetItem(e.NewStartingIndex), e.NewStartingIndex); } // OldItems contains the item that was removed. // If OldStartingIndex is not -1, then it contains the index where the old item was removed. if (e.Action == NotifyCollectionChangedAction.Remove) { await RemovePage(e.OldStartingIndex); } // OldItems contains the moved item. // OldStartingIndex contains the index where the item was moved from. // NewStartingIndex contains the index where the item was moved to. if (e.Action == NotifyCollectionChangedAction.Move) { if (Element == null || flipView == null || Source == null) return; var obj = Source[e.OldStartingIndex]; Source.RemoveAt(e.OldStartingIndex); Source.Insert(e.NewStartingIndex, obj); SetCurrentPage(Element.Position); } // NewItems contains the replacement item. // NewStartingIndex and OldStartingIndex are equal, and if they are not -1, // then they contain the index where the item was replaced. if (e.Action == NotifyCollectionChangedAction.Replace) { if (Element == null || flipView == null || Source == null) return; Source[e.OldStartingIndex] = CreateView(e.NewItems[e.NewStartingIndex]); } // No other properties are valid. if (e.Action == NotifyCollectionChangedAction.Reset) { if (Element == null) return; SetPosition(); SetNativeView(); SetArrowsVisibility(); Element.SendPositionSelected(); } } // Arrows visibility private void FlipView_Loaded(object sender, RoutedEventArgs e) { ButtonHide(flipView, "PreviousButtonHorizontal"); ButtonHide(flipView, "NextButtonHorizontal"); ButtonHide(flipView, "PreviousButtonVertical"); ButtonHide(flipView, "NextButtonVertical"); //var controls = AllChildren(flipView); if (ScrollingHost == null) { ScrollingHost = FindVisualChild<Windows.UI.Xaml.Controls.ScrollViewer>(flipView, "ScrollingHost"); ScrollingHost.ViewChanging += ScrollingHost_ViewChanging; ScrollingHost.ViewChanged += ScrollingHost_ViewChanged; } SetArrows(); } private void Element_SizeChanged(object sender, EventArgs e) { if (Element == null) return; var rect = Element.Bounds; if (nativeView == null) { ElementWidth = ((Xamarin.Forms.Rectangle)rect).Width; ElementHeight = ((Xamarin.Forms.Rectangle)rect).Height; SetNativeView(); Element.SendPositionSelected(); Element.PositionSelectedCommand?.Execute(null); } } // Reset timer as this is called multiple times private void FlipView_SizeChanged(object sender, SizeChangedEventArgs e) { if (Math.Round(e.NewSize.Width) != Math.Round(ElementWidth) || Math.Round(e.NewSize.Height) != Math.Round(ElementHeight)) { if (timer != null) timer.Dispose(); timer = null; timer = new Timer(OnTick, e.NewSize, 100, 100); } } private void OnTick(object args) { timer.Dispose(); timer = null; // Save new dimensions when resize completes var size = (Windows.Foundation.Size)args; ElementWidth = size.Width; ElementHeight = size.Height; // Refresh UI Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { if (Element != null) { SetNativeView(); Element.SendPositionSelected(); } }); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (Element == null || flipView == null) return; var rect = this.Element?.Bounds; switch (e.PropertyName) { case "Orientation": orientationChanged = true; SetNativeView(); Element.SendPositionSelected(); Element.PositionSelectedCommand?.Execute(null); break; case "BackgroundColor": flipView.Background = (SolidColorBrush)converter.Convert(Element.BackgroundColor, null, null, null); break; case "IsSwipeEnabled": nativeView.IsSwipeEnabled = Element.IsSwipeEnabled; break; case "IndicatorsTintColor": fillColor = (SolidColorBrush)converter.Convert(Element.IndicatorsTintColor, null, null, null); UpdateIndicatorsTint(); break; case "CurrentPageIndicatorTintColor": selectedColor = (SolidColorBrush)converter.Convert(Element.CurrentPageIndicatorTintColor, null, null, null); UpdateIndicatorsTint(); break; case "IndicatorsShape": SetIndicators(); break; case "ShowIndicators": SetIndicators(); break; case "ItemsSource": SetPosition(); SetNativeView(); SetArrowsVisibility(); Element.SendPositionSelected(); if (Element.ItemsSource != null && Element.ItemsSource is INotifyCollectionChanged) { Element.PositionSelectedCommand?.Execute(null); ((INotifyCollectionChanged)Element.ItemsSource).CollectionChanged += ItemsSource_CollectionChanged; } break; case "ItemTemplate": SetNativeView(); Element.SendPositionSelected(); Element.PositionSelectedCommand?.Execute(null); break; case "Position": if (!isChangingPosition) { SetCurrentPage(Element.Position); } break; case "ShowArrows": FlipView_Loaded(flipView, null); break; case "ArrowsBackgroundColor": break; case "ArrowsTintColor": break; case "ArrowsTransparency": break; } } #region adapter callbacks private void FlipView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (Element != null && !isChangingPosition) { Element.Position = flipView.SelectedIndex; UpdateIndicatorsTint(); Element.SendPositionSelected(); Element.PositionSelectedCommand?.Execute(null); } } double lastOffset; private void ScrollingHost_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e) { var scrollView = (ScrollViewer)sender; double percentCompleted; ScrollDirection direction; // Get Horizontal or Vertical Offset depending on carousel orientation var currentOffset = Element.Orientation == CarouselViewOrientation.Horizontal ? scrollView.HorizontalOffset : scrollView.VerticalOffset; // Scrolling to the right if (currentOffset > lastOffset) { percentCompleted = Math.Floor((currentOffset - (int)currentOffset)*100); direction = Element.Orientation == CarouselViewOrientation.Horizontal ? ScrollDirection.Right : ScrollDirection.Down; } else { percentCompleted = Math.Floor((lastOffset - currentOffset) * 100); direction = Element.Orientation == CarouselViewOrientation.Horizontal ? ScrollDirection.Left : ScrollDirection.Up; } if (percentCompleted <= 100) Element.SendScrolled(percentCompleted, direction); } private void ScrollingHost_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { if (!e.IsIntermediate) { var scrollView = (ScrollViewer)sender; lastOffset = Element.Orientation == CarouselViewOrientation.Horizontal ? scrollView.HorizontalOffset : scrollView.VerticalOffset; } } #endregion public void SetNativeView() { var position = Element.Position; if (nativeView == null) { nativeView = new FlipViewControl(Element.IsSwipeEnabled); flipView = nativeView.FindName("flipView") as FlipView; } if (orientationChanged) { // Orientation BP if (Element.Orientation == CarouselViewOrientation.Horizontal) flipView.ItemsPanel = nativeView.Resources["HPanel"] as ItemsPanelTemplate; else flipView.ItemsPanel = nativeView.Resources["VPanel"] as ItemsPanelTemplate; orientationChanged = false; } var source = new List<FrameworkElement>(); if (Element.ItemsSource != null && Element.ItemsSource?.GetCount() > 0) { for (int j = 0; j <= Element.ItemsSource.GetCount() - 1; j++) { source.Add(CreateView(Element.ItemsSource.GetItem(j))); } } Source = new ObservableCollection<FrameworkElement>(source); flipView.ItemsSource = Source; //flipView.ItemsSource = Element.ItemsSource; //flipView.ItemTemplateSelector = new MyTemplateSelector(Element); (the way it should be) converter = new ColorConverter(); // BackgroundColor BP flipView.Background = (SolidColorBrush)converter.Convert(Element.BackgroundColor, null, null, null); // IndicatorsTintColor BP fillColor = (SolidColorBrush)converter.Convert(Element.IndicatorsTintColor, null, null, null); // CurrentPageIndicatorTintColor BP selectedColor = (SolidColorBrush)converter.Convert(Element.CurrentPageIndicatorTintColor, null, null, null); flipView.Loaded += FlipView_Loaded; flipView.SelectionChanged += FlipView_SelectionChanged; flipView.SizeChanged += FlipView_SizeChanged; if (Source.Count > 0) { flipView.SelectedIndex = position; } SetNativeControl(nativeView); //SetArrows(); // INDICATORS indicators = nativeView.FindName("indicators") as StackPanel; SetIndicators(); } void SetPosition() { isChangingPosition = true; if (Element.ItemsSource != null) { if (Element.Position > Element.ItemsSource.GetCount() - 1) Element.Position = Element.ItemsSource.GetCount() - 1; if (Element.Position == -1) Element.Position = 0; } else { Element.Position = 0; } isChangingPosition = false; } void SetArrows() { if (Element.Orientation == CarouselViewOrientation.Horizontal) { prevBtn = FindVisualChild<Windows.UI.Xaml.Controls.Button>(flipView, "PreviousButtonHorizontal"); nextBtn = FindVisualChild<Windows.UI.Xaml.Controls.Button>(flipView, "NextButtonHorizontal"); } else { prevBtn = FindVisualChild<Windows.UI.Xaml.Controls.Button>(flipView, "PreviousButtonVertical"); nextBtn = FindVisualChild<Windows.UI.Xaml.Controls.Button>(flipView, "NextButtonVertical"); } // TODO: Set BackgroundColor, TintColor and Transparency } void SetArrowsVisibility() { if (prevBtn == null || nextBtn == null) return; prevBtn.Visibility = Element.Position == 0 || Element.ItemsSource.GetCount() == 0 ? Visibility.Collapsed : Visibility.Visible; nextBtn.Visibility = Element.Position == Element.ItemsSource.GetCount() - 1 || Element.ItemsSource.GetCount() == 0 ? Visibility.Collapsed : Visibility.Visible; } void SetIndicators() { var dotsPanel = nativeView.FindName("dotsPanel") as ItemsControl; if (Element.ShowIndicators) { if (Element.Orientation == CarouselViewOrientation.Horizontal) { indicators.HorizontalAlignment = HorizontalAlignment.Stretch; indicators.VerticalAlignment = VerticalAlignment.Bottom; indicators.Width = Double.NaN; indicators.Height = 32; dotsPanel.HorizontalAlignment = HorizontalAlignment.Center; dotsPanel.VerticalAlignment = VerticalAlignment.Bottom; dotsPanel.ItemsPanel = nativeView.Resources["dotsHPanel"] as ItemsPanelTemplate; } else { indicators.HorizontalAlignment = HorizontalAlignment.Right; indicators.VerticalAlignment = VerticalAlignment.Center; indicators.Width = 32; indicators.Height = Double.NaN; dotsPanel.HorizontalAlignment = HorizontalAlignment.Center; dotsPanel.VerticalAlignment = VerticalAlignment.Center; dotsPanel.ItemsPanel = nativeView.Resources["dotsVPanel"] as ItemsPanelTemplate; } var dots = new List<Shape>(); if (Element.ItemsSource != null && Element.ItemsSource?.GetCount() > 0) { int i = 0; foreach (var item in Element.ItemsSource) { dots.Add(CreateDot(i, Element.Position)); i++; } } Dots = new ObservableCollection<Shape>(dots); dotsPanel.ItemsSource = Dots; } else { dotsPanel.ItemsSource = new List<Shape>(); } // ShowIndicators BP indicators.Visibility = Element.ShowIndicators ? Visibility.Visible : Visibility.Collapsed; } void UpdateIndicatorsTint() { var dotsPanel = nativeView.FindName("dotsPanel") as ItemsControl; int i = 0; foreach (var item in dotsPanel.Items) { ((Shape)item).Fill = i == Element.Position ? selectedColor : fillColor; i++; } } void InsertPage(object item, int position) { if (Element == null || flipView == null || Source == null) return; if (position <= Element.Position) { isChangingPosition = true; Element.Position++; isChangingPosition = false; } Source.Insert(position, CreateView(item)); Dots?.Insert(position, CreateDot(position, Element.Position)); flipView.SelectedIndex = Element.Position; //if (position <= Element.Position) Element.SendPositionSelected(); Element.PositionSelectedCommand?.Execute(null); } public async Task RemovePage(int position) { if (Element == null || flipView == null || Source == null) return; if (Source?.Count > 0) { // To remove latest page, rebuild flipview or the page wont disappear if (Source.Count == 1) { SetNativeView(); } else { isChangingPosition = true; // To remove current page if (position == Element.Position) { // Swipe animation at position 0 doesn't work :( /*if (position == 0) { flipView.SelectedIndex = 1; } else {*/ if (position > 0) { var newPos = position - 1; if (newPos == -1) newPos = 0; flipView.SelectedIndex = newPos; } // With a swipe transition if (Element.AnimateTransition) await Task.Delay(100); } Source.RemoveAt(position); Element.Position = flipView.SelectedIndex; Dots?.RemoveAt(position); UpdateIndicatorsTint(); isChangingPosition = false; Element.SendPositionSelected(); } } } void SetCurrentPage(int position) { if (position < 0 || position > Element.ItemsSource?.GetCount() - 1) return; if (Element == null || flipView == null || Element?.ItemsSource == null) return; if (Element.ItemsSource?.GetCount() > 0) { flipView.SelectedIndex = position; } } FrameworkElement CreateView(object item) { Xamarin.Forms.View formsView = null; var bindingContext = item; var dt = bindingContext as Xamarin.Forms.DataTemplate; var view = bindingContext as View; // Support for List<DataTemplate> as ItemsSource if (dt != null) { formsView = (Xamarin.Forms.View)dt.CreateContent(); } else { if (view != null) { formsView = view; } else { var selector = Element.ItemTemplate as Xamarin.Forms.DataTemplateSelector; if (selector != null) formsView = (Xamarin.Forms.View)selector.SelectTemplate(bindingContext, Element).CreateContent(); else formsView = (Xamarin.Forms.View)Element.ItemTemplate.CreateContent(); formsView.BindingContext = bindingContext; } } formsView.Parent = this.Element; var element = formsView.ToWindows(new Xamarin.Forms.Rectangle(0, 0, ElementWidth, ElementHeight)); //if (dt == null && view == null) //formsView.Parent = null; return element; } Shape CreateDot(int i, int position) { if (Element.IndicatorsShape == IndicatorsShape.Circle) { return new Ellipse() { Fill = i == position ? selectedColor : fillColor, Height = 7, Width = 7, Margin = new Windows.UI.Xaml.Thickness(4, 12, 4, 12) }; } else { return new Windows.UI.Xaml.Shapes.Rectangle() { Fill = i == position ? selectedColor : fillColor, Height = 6, Width = 6, Margin = new Windows.UI.Xaml.Thickness(4, 12, 4, 12) }; } } private void ButtonHide(FlipView f, string name) { var b = FindVisualChild<Windows.UI.Xaml.Controls.Button>(f, name); if (b != null) { b.Opacity = Element.ShowArrows ? 1.0 : 0.0; b.IsHitTestVisible = Element.ShowArrows; } } private childItemType FindVisualChild<childItemType>(DependencyObject obj, string name) where childItemType : FrameworkElement { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child is childItemType && ((FrameworkElement)child).Name == name) return (childItemType)child; else { childItemType childOfChild = FindVisualChild<childItemType>(child, name); if (childOfChild != null) return childOfChild; } } return null; } public List<Control> AllChildren(DependencyObject parent) { var _list = new List<Control>(); for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var _child = VisualTreeHelper.GetChild(parent, i); if (_child is Control) _list.Add(_child as Control); _list.AddRange(AllChildren(_child)); } return _list; } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { prevBtn = null; nextBtn = null; indicators = null; if (flipView != null) { flipView.SelectionChanged -= FlipView_SelectionChanged; flipView = null; } if (Element != null) { if (Element.ItemsSource != null && Element.ItemsSource is INotifyCollectionChanged) ((INotifyCollectionChanged)Element.ItemsSource).CollectionChanged -= ItemsSource_CollectionChanged; } nativeView = null; _disposed = true; } try { base.Dispose(disposing); } catch (Exception ex) { return; } } /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { var temp = DateTime.Now; } } // UWP DataTemplate doesn't support loadTemplate function as parameter // Having that, rendering all the views ahead of time is not needed /*public class MyTemplateSelector : DataTemplateSelector { CarouselViewControl Element; public MyTemplateSelector(CarouselViewControl element) { Element = element; } protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { Xamarin.Forms.View formsView = null; var bindingContext = item; var dt = bindingContext as Xamarin.Forms.DataTemplate; // Support for List<DataTemplate> as ItemsSource if (dt != null) { formsView = (Xamarin.Forms.View)dt.CreateContent(); } else { var selector = Element.ItemTemplate as Xamarin.Forms.DataTemplateSelector; if (selector != null) formsView = (Xamarin.Forms.View)selector.SelectTemplate(bindingContext, Element).CreateContent(); else formsView = (Xamarin.Forms.View)Element.ItemTemplate.CreateContent(); formsView.BindingContext = bindingContext; } formsView.Parent = this.Element; var element = FormsViewToNativeUWP.ConvertFormsToNative(formsView, new Xamarin.Forms.Rectangle(0, 0, ElementWidth, ElementHeight)); var template = new DataTemplate(() => return element; ); // THIS IS NOT SUPPORTED :( return template; } }*/ }
35.554855
172
0.538145
[ "MIT" ]
Ruddy2007/CarouselView
CarouselView/CarouselView.FormsPlugin.UWP/CarouselViewImplementation.cs
28,197
C#
using System.Collections.Generic; using System.Linq; using BoutiqueCommonXUnit.Data; using BoutiqueCommonXUnit.Data.Models.Implementations; using BoutiqueDTOXUnit.Data.Models.Implementations; using BoutiqueDTOXUnit.Data.Models.Interfaces; namespace BoutiqueMVCXUnit.Data { public class TransferData { /// <summary> /// Получить трансферные модели для теста /// </summary> public static IReadOnlyCollection<ITestTransfer> GetTestTransfers() => TestData.TestDomains. Select(testDomain => new TestTransfer(testDomain, testDomain.TestIncludes.Select(testInclude => new TestIncludeTransfer(testInclude)))). ToList(); /// <summary> /// Получить трансферную модель для теста /// </summary> public static ITestTransfer GetTestTransfer() => GetTestTransfers().First(); /// <summary> /// Получить идентификаторы /// </summary> public static IReadOnlyCollection<TestEnum> GetTestIds(IEnumerable<ITestTransfer> testTransfers) => testTransfers.Select(test => test.Id).ToList().AsReadOnly(); } }
37.545455
137
0.62954
[ "MIT" ]
rubilnik4/VeraBoutique
BoutiqueMVCXUnit/Data/TransferData.cs
1,329
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; namespace WeersProductions { public class OnHover : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { public delegate void OnPointerEvent(PointerEventData eventData); public OnPointerEvent onPointerEnter; public OnPointerEvent onPointerExit; /// <summary> /// Called after <see cref="Delay"/> time is over and the mouse is still hovering on the object. /// </summary> public UnityAction onPointerDelay; /// <summary> /// If bigger than 0, onPointerDelay will be called after x seconds if the mouse is still on the object. /// Can be used to show a tooltip after some time of hovering. /// </summary> public float Delay; /// <summary> /// If true, the mouse is inside this object. /// </summary> private bool _inside; /// <summary> /// Called when the pointer enters this object. /// If <see cref="onPointerEnter"/> has been set, it will be called. /// </summary> /// <param name="eventData"></param> public void OnPointerEnter(PointerEventData eventData) { _inside = true; if (onPointerEnter != null) { onPointerEnter(eventData); } if (Delay > 0 && onPointerDelay != null) { StartCoroutine(InvokeAfter(Delay)); } } IEnumerator InvokeAfter(float seconds) { yield return new WaitForSecondsRealtime(seconds); if (_inside) { onPointerDelay(); } } /// <summary> /// Called when the pointer leaves this object. /// If < onPointerLeave/> has been set, it will be called. /// </summary> /// <param name="eventData"></param> public void OnPointerExit(PointerEventData eventData) { _inside = false; if (onPointerExit != null) { onPointerExit(eventData); } } } }
25.232877
107
0.686211
[ "MIT" ]
WeersProductions/MenuManager
Scripts/CustomPresets/Components/OnHover.cs
1,844
C#
namespace MassTransit.AmazonSqsTransport.Configuration.Configuration { using System; using System.Collections.Generic; using Builders; using Context; using GreenPipes; using GreenPipes.Agents; using GreenPipes.Builders; using GreenPipes.Configurators; using MassTransit.Configuration; using MassTransit.Pipeline.Filters; using Pipeline; using Topology; using Topology.Settings; using Transport; using Transports; public class AmazonSqsReceiveEndpointConfiguration : ReceiveEndpointConfiguration, IAmazonSqsReceiveEndpointConfiguration, IAmazonSqsReceiveEndpointConfigurator { readonly IBuildPipeConfigurator<ConnectionContext> _connectionConfigurator; readonly IAmazonSqsEndpointConfiguration _endpointConfiguration; readonly IAmazonSqsHostConfiguration _hostConfiguration; readonly Lazy<Uri> _inputAddress; readonly IBuildPipeConfigurator<ModelContext> _modelConfigurator; readonly AmazonSqsReceiveSettings _settings; public AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, string queueName, IAmazonSqsEndpointConfiguration endpointConfiguration) : this(hostConfiguration, endpointConfiguration) { BindMessageTopics = true; _settings = new AmazonSqsReceiveSettings(queueName, true, false); } public AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, AmazonSqsReceiveSettings settings, IAmazonSqsEndpointConfiguration endpointConfiguration) : this(hostConfiguration, endpointConfiguration) { _settings = settings; } AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, IAmazonSqsEndpointConfiguration endpointConfiguration) : base(hostConfiguration, endpointConfiguration) { _hostConfiguration = hostConfiguration; _endpointConfiguration = endpointConfiguration; _connectionConfigurator = new PipeConfigurator<ConnectionContext>(); _modelConfigurator = new PipeConfigurator<ModelContext>(); HostAddress = hostConfiguration.Host.Address; _inputAddress = new Lazy<Uri>(FormatInputAddress); } public IAmazonSqsReceiveEndpointConfigurator Configurator => this; public IAmazonSqsBusConfiguration BusConfiguration => _hostConfiguration.BusConfiguration; public IAmazonSqsHostControl Host => _hostConfiguration.Host; public bool BindMessageTopics { get; set; } public ReceiveSettings Settings => _settings; public override Uri HostAddress { get; } public override Uri InputAddress => _inputAddress.Value; IAmazonSqsTopologyConfiguration IAmazonSqsEndpointConfiguration.Topology => _endpointConfiguration.Topology; public override IReceiveEndpoint Build() { var builder = new AmazonSqsReceiveEndpointBuilder(this); ApplySpecifications(builder); var receivePipe = CreateReceivePipe(); var receiveEndpointContext = builder.CreateReceiveEndpointContext(); _modelConfigurator.UseFilter(new ConfigureTopologyFilter<ReceiveSettings>(_settings, receiveEndpointContext.BrokerTopology)); IAgent consumerAgent; if (_hostConfiguration.BusConfiguration.DeployTopologyOnly) { var transportReadyFilter = new TransportReadyFilter<ModelContext>(builder.TransportObservers, InputAddress); _modelConfigurator.UseFilter(transportReadyFilter); consumerAgent = transportReadyFilter; } else { var deadLetterTransport = CreateDeadLetterTransport(); var errorTransport = CreateErrorTransport(); var consumerFilter = new AmazonSqsConsumerFilter(receivePipe, builder.ReceiveObservers, builder.TransportObservers, receiveEndpointContext, deadLetterTransport, errorTransport); _modelConfigurator.UseFilter(consumerFilter); consumerAgent = consumerFilter; } IFilter<ConnectionContext> sessionFilter = new ReceiveModelFilter(_modelConfigurator.Build(), _hostConfiguration.Host); _connectionConfigurator.UseFilter(sessionFilter); var transport = new AmazonSqsReceiveTransport(_hostConfiguration.Host, _settings, _connectionConfigurator.Build(), receiveEndpointContext, builder.ReceiveObservers, builder.TransportObservers); transport.Add(consumerAgent); return CreateReceiveEndpoint(_settings.EntityName ?? NewId.Next().ToString(), transport, receiveEndpointContext); } IAmazonSqsHost IAmazonSqsReceiveEndpointConfigurator.Host => Host; public bool Durable { set { _settings.Durable = value; Changed("Durable"); } } public bool AutoDelete { set { _settings.AutoDelete = value; Changed("AutoDelete"); } } public ushort PrefetchCount { set { _settings.PrefetchCount = value; Changed("PrefetchCount"); } } public ushort WaitTimeSeconds { set { _settings.WaitTimeSeconds = value; Changed("WaitTimeSeconds"); } } public bool Lazy { set => _settings.Lazy = value; } public void Bind(string topicName, Action<ITopicBindingConfigurator> configure = null) { if (topicName == null) throw new ArgumentNullException(nameof(topicName)); _endpointConfiguration.Topology.Consume.Bind(topicName, configure); } public void Bind<T>(Action<ITopicBindingConfigurator> configure = null) where T : class { _endpointConfiguration.Topology.Consume.GetMessageTopology<T>().Bind(configure); } public void ConfigureSession(Action<IPipeConfigurator<ModelContext>> configure) { configure?.Invoke(_modelConfigurator); } public void ConfigureConnection(Action<IPipeConfigurator<ConnectionContext>> configure) { configure?.Invoke(_connectionConfigurator); } Uri FormatInputAddress() { return _settings.GetInputAddress(_hostConfiguration.Host.Settings.HostAddress); } IErrorTransport CreateErrorTransport() { var errorSettings = _endpointConfiguration.Topology.Send.GetErrorSettings(_settings); var filter = new ConfigureTopologyFilter<ErrorSettings>(errorSettings, errorSettings.GetBrokerTopology()); return new AmazonSqsErrorTransport(errorSettings.EntityName, filter); } IDeadLetterTransport CreateDeadLetterTransport() { var deadLetterSettings = _endpointConfiguration.Topology.Send.GetDeadLetterSettings(_settings); var filter = new ConfigureTopologyFilter<DeadLetterSettings>(deadLetterSettings, deadLetterSettings.GetBrokerTopology()); return new AmazonSqsDeadLetterTransport(deadLetterSettings.EntityName, filter); } protected override bool IsAlreadyConfigured() { return _inputAddress.IsValueCreated || base.IsAlreadyConfigured(); } public override IEnumerable<ValidationResult> Validate() { var queueName = $"{_settings.EntityName}"; if (!AmazonSqsEntityNameValidator.Validator.IsValidEntityName(_settings.EntityName)) yield return this.Failure(queueName, "must be a valid queue name"); if (_settings.PurgeOnStartup) yield return this.Warning(queueName, "Existing messages in the queue will be purged on service start"); foreach (var result in base.Validate()) yield return result.WithParentKey(queueName); } } }
35.717949
155
0.666427
[ "Apache-2.0" ]
dotnetjunkie/MassTransit
src/MassTransit.AmazonSqsTransport/Configuration/Configuration/AmazonSqsReceiveEndpointConfiguration.cs
8,360
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Microsoft.Psi.Visualization.Adapters { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Microsoft.Psi.Visualization.Data; /// <summary> /// Used to adapt streams of lists of rectangles into lists of named rectangles. /// </summary> [StreamAdapter] public class ListRectangleAdapter : StreamAdapter<List<Rectangle>, List<Tuple<Rectangle, string>>> { /// <summary> /// Initializes a new instance of the <see cref="ListRectangleAdapter"/> class. /// </summary> public ListRectangleAdapter() : base(Adapter) { } private static List<Tuple<Rectangle, string>> Adapter(List<Rectangle> value, Envelope env) { return value.Select(p => Tuple.Create(p, "Blah")).ToList(); } } }
30.21875
102
0.638056
[ "MIT" ]
Bhaskers-Blu-Org2/psi
Sources/Visualization/Microsoft.Psi.Visualization.Common.Windows/Adapters/ListRectangleAdapter.cs
969
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Authorization.V20190601 { public static class GetPolicySetDefinition { public static Task<GetPolicySetDefinitionResult> InvokeAsync(GetPolicySetDefinitionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetPolicySetDefinitionResult>("azure-nextgen:authorization/v20190601:getPolicySetDefinition", args ?? new GetPolicySetDefinitionArgs(), options.WithVersion()); } public sealed class GetPolicySetDefinitionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the policy set definition to get. /// </summary> [Input("policySetDefinitionName", required: true)] public string PolicySetDefinitionName { get; set; } = null!; public GetPolicySetDefinitionArgs() { } } [OutputType] public sealed class GetPolicySetDefinitionResult { /// <summary> /// The policy set definition description. /// </summary> public readonly string? Description; /// <summary> /// The display name of the policy set definition. /// </summary> public readonly string? DisplayName; /// <summary> /// The policy set definition metadata. /// </summary> public readonly object? Metadata; /// <summary> /// The name of the policy set definition. /// </summary> public readonly string Name; /// <summary> /// The policy set definition parameters that can be used in policy definition references. /// </summary> public readonly object? Parameters; /// <summary> /// An array of policy definition references. /// </summary> public readonly ImmutableArray<Outputs.PolicyDefinitionReferenceResponse> PolicyDefinitions; /// <summary> /// The type of policy definition. Possible values are NotSpecified, BuiltIn, and Custom. /// </summary> public readonly string? PolicyType; /// <summary> /// The type of the resource (Microsoft.Authorization/policySetDefinitions). /// </summary> public readonly string Type; [OutputConstructor] private GetPolicySetDefinitionResult( string? description, string? displayName, object? metadata, string name, object? parameters, ImmutableArray<Outputs.PolicyDefinitionReferenceResponse> policyDefinitions, string? policyType, string type) { Description = description; DisplayName = displayName; Metadata = metadata; Name = name; Parameters = parameters; PolicyDefinitions = policyDefinitions; PolicyType = policyType; Type = type; } } }
32.806122
213
0.626128
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Authorization/V20190601/GetPolicySetDefinition.cs
3,215
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HeartbeatTests { [Fact] public void HeartbeatIntervalIsOneSecond() { Assert.Equal(TimeSpan.FromSeconds(1), Heartbeat.Interval); } [Fact] public async Task HeartbeatTakingLongerThanIntervalIsLoggedAsWarning() { var systemClock = new MockSystemClock(); var heartbeatHandler = new Mock<IHeartbeatHandler>(); var debugger = new Mock<IDebugger>(); var kestrelTrace = new TestKestrelTrace(); var handlerMre = new ManualResetEventSlim(); var handlerStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var now = systemClock.UtcNow; var heartbeatDuration = TimeSpan.FromSeconds(2); heartbeatHandler.Setup(h => h.OnHeartbeat(now)).Callback(() => { handlerStartedTcs.SetResult(); handlerMre.Wait(); }); debugger.Setup(d => d.IsAttached).Returns(false); Task blockedHeartbeatTask; using (var heartbeat = new Heartbeat(new[] { heartbeatHandler.Object }, systemClock, debugger.Object, kestrelTrace)) { blockedHeartbeatTask = Task.Run(() => heartbeat.OnHeartbeat()); await handlerStartedTcs.Task.DefaultTimeout(); } // 2 seconds passes... systemClock.UtcNow = systemClock.UtcNow.AddSeconds(2); handlerMre.Set(); await blockedHeartbeatTask.DefaultTimeout(); heartbeatHandler.Verify(h => h.OnHeartbeat(now), Times.Once()); var warningMessage = kestrelTrace.Logger.Messages.Single(message => message.LogLevel == LogLevel.Warning).Message; Assert.Equal($"As of \"{now.ToString(CultureInfo.InvariantCulture)}\", the heartbeat has been running for " + $"\"{heartbeatDuration.ToString("c", CultureInfo.InvariantCulture)}\" which is longer than " + $"\"{Heartbeat.Interval.ToString("c", CultureInfo.InvariantCulture)}\". " + "This could be caused by thread pool starvation.", warningMessage); } [Fact] public async Task HeartbeatTakingLongerThanIntervalIsNotLoggedIfDebuggerAttached() { var systemClock = new MockSystemClock(); var heartbeatHandler = new Mock<IHeartbeatHandler>(); var debugger = new Mock<IDebugger>(); var kestrelTrace = new Mock<IKestrelTrace>(); var handlerMre = new ManualResetEventSlim(); var handlerStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var now = systemClock.UtcNow; heartbeatHandler.Setup(h => h.OnHeartbeat(now)).Callback(() => { handlerStartedTcs.SetResult(); handlerMre.Wait(); }); debugger.Setup(d => d.IsAttached).Returns(true); Task blockedHeartbeatTask; using (var heartbeat = new Heartbeat(new[] { heartbeatHandler.Object }, systemClock, debugger.Object, kestrelTrace.Object)) { blockedHeartbeatTask = Task.Run(() => heartbeat.OnHeartbeat()); await handlerStartedTcs.Task.DefaultTimeout(); } // 2 seconds passes... systemClock.UtcNow = systemClock.UtcNow.AddSeconds(2); handlerMre.Set(); await blockedHeartbeatTask.DefaultTimeout(); heartbeatHandler.Verify(h => h.OnHeartbeat(now), Times.Once()); kestrelTrace.Verify(t => t.HeartbeatSlow(TimeSpan.FromSeconds(2), Heartbeat.Interval, now), Times.Never()); } [Fact] public void ExceptionFromHeartbeatHandlerIsLoggedAsError() { var systemClock = new MockSystemClock(); var heartbeatHandler = new Mock<IHeartbeatHandler>(); var kestrelTrace = new TestKestrelTrace(); var ex = new Exception(); heartbeatHandler.Setup(h => h.OnHeartbeat(systemClock.UtcNow)).Throws(ex); using (var heartbeat = new Heartbeat(new[] { heartbeatHandler.Object }, systemClock, DebuggerWrapper.Singleton, kestrelTrace)) { heartbeat.OnHeartbeat(); } Assert.Equal(ex, kestrelTrace.Logger.Messages.Single(message => message.LogLevel == LogLevel.Error).Exception); } } }
39.503937
138
0.628264
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Servers/Kestrel/Core/test/HeartbeatTests.cs
5,017
C#
//using System.Runtime.CompilerServices; namespace Bssom.Serializer.Resolvers { /// <summary> /// Default composited resolver, Object -> Primitive -> Attribute -> BssomValue -> BuildIn -> IDictionary -> ICollection -> MapCodeGen. /// </summary> public sealed class CompositedResolver : IFormatterResolver { /// <summary> /// The singleton instance that can be used. /// </summary> public static readonly CompositedResolver Instance = new CompositedResolver(); private static readonly IFormatterResolver[] Resolvers = new IFormatterResolver[] { ObjectResolver.Instance, PrimitiveResolver.Instance, AttributeFormatterResolver.Instance, BssomValueResolver.Instance, BuildInResolver.Instance, IDictionaryResolver.Instance, ICollectionResolver.Instance, MapCodeGenResolver.Instance }; public IBssomFormatter<T> GetFormatter<T>() { return FormatterCache<T>.Formatter; } private static class FormatterCache<T> { public static readonly IBssomFormatter<T> Formatter; static FormatterCache() { foreach (IFormatterResolver item in Resolvers) { IBssomFormatter<T> f = item.GetFormatter<T>(); if (f != null) { Formatter = f; return; } } } } } }
31.8
139
0.556604
[ "MIT" ]
LeoYang-Chuese/Bssom.Net
Bssom.Serializer/Resolvers/CompositedResolver.cs
1,592
C#
using System.Collections.Generic; using System.Xml.Serialization; using Alipay.AopSdk.Core.Domain; namespace Alipay.AopSdk.Core.Response { /// <summary> /// KoubeiRetailShopitemBatchqueryResponse. /// </summary> public class KoubeiRetailShopitemBatchqueryResponse : AopResponse { /// <summary> /// 店铺商品集合 /// </summary> [XmlArray("shopitemlist")] [XmlArrayItem("ext_shop_item")] public List<ExtShopItem> Shopitemlist { get; set; } } }
25.4
69
0.653543
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Response/KoubeiRetailShopitemBatchqueryResponse.cs
520
C#
using BuildIt.CognitiveServices; using BuildIt.CognitiveServices.Models; using CognitiveServicesDemo.Common; using CognitiveServicesDemo.Model; using MvvmCross.Core.ViewModels; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace CognitiveServicesDemo.ViewModels { public class LanguageTextAnalyticsViewModel : MvxViewModel { private string inputText = "I had a wonderful experience! The rooms were wonderful and the staff were helpful."; private string warningText; private string language; private string isoName = "en"; private string keyPhrases; private string sentimentResult; public string InputText { get { return inputText; } set { inputText = value; RaisePropertyChanged(() => InputText); } } public string WarningText { get { return warningText; } set { warningText = value; RaisePropertyChanged(() => WarningText); } } public string IsoName { get { return isoName; } set { isoName = value; RaisePropertyChanged(() => IsoName); } } public string Language { get { return language; } set { language = value; RaisePropertyChanged(() => Language); } } public string KeyPhrases { get { return keyPhrases; } set { keyPhrases = value; RaisePropertyChanged(() => KeyPhrases); } } public string SentimentResult { get { return sentimentResult; } set { sentimentResult = value; RaisePropertyChanged(() => SentimentResult); } } public async Task TextAnalyticsAsync(string inputText) { //TextAnalyticsReplyBody text = new TextAnalyticsReplyBody(); //text.documents[0].id = DateTime.Now.ToString(); //text.documents[0]. //text.text = inputText; //text.id = DateTime.Now.ToString(); //var jsonString = JsonConvert.SerializeObject(text); var detectLanguage = " {\"documents\": [{ \"id\":\"" + DateTime.Now + "\", \"text\":\"" + inputText + "\"}]}"; var textAnalytics = new AzureMachineLearningTextAnalytics(); BatchInputV2 batch = new BatchInputV2 { Documents = new List<InputV2> { new InputV2(DateTime.Now.ToString("u"), inputText) } }; var languageResult = await textAnalytics.DetectLanguageWithHttpMessagesAsync(1, null, Constants.TextAnalyticsKey, batch); //HTTPClient var client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Constants.TextAnalyticsKey); //request parameters var uri = $"https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?"; HttpResponseMessage response; var cognitiveService1 = new CognitiveServiceClient(); var result1 = await cognitiveService1.DetectLanguageApiRequestAsync(Constants.TextAnalyticsKey, detectLanguage); // Request body byte[] byteData = Encoding.UTF8.GetBytes(detectLanguage); using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = await client.PostAsync(uri, content); } var jsonResult = await response.Content.ReadAsStringAsync(); var feed = JsonConvert.DeserializeObject<TextAnalyticsReplyBody>(jsonResult); //***************************************** //continue call keyPhrases API var detectkeyPhrases = " {\"documents\": [{ \"id\":\"" + DateTime.Now + "\", \"text\":\"" + inputText + "\", \"language\": \"" + IsoName + "\" }]}"; var keyPhrasesUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases?"; HttpResponseMessage response2; //var cognitiveService = new CognitiveServiceClient(); //var result = await cognitiveService.KeyPhrasesApiRequestAsync(Constants.TextAnalyticsKey, detectkeyPhrases); // Request body byte[] byteData2 = Encoding.UTF8.GetBytes(detectkeyPhrases); using (var content = new ByteArrayContent(byteData2)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response2 = await client.PostAsync(keyPhrasesUri, content); } var jsonResult2 = await response2.Content.ReadAsStringAsync(); var feed2 = JsonConvert.DeserializeObject<DetectkeyPhrases>(jsonResult2); //****************************** //continue call sentiment API var detectSentiment = " {\"documents\": [{ \"id\":\"" + DateTime.Now + "\", \"text\":\"" + inputText + "\", \"language\": \"" + IsoName + "\" }]}"; var SentimentUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment?"; HttpResponseMessage response3; var cognitiveService = new CognitiveServiceClient(); var result = await cognitiveService.SentimentApiRequestAsync(Constants.TextAnalyticsKey, detectSentiment); // Request body byte[] byteData3 = Encoding.UTF8.GetBytes(detectSentiment); using (var content = new ByteArrayContent(byteData3)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response3 = await client.PostAsync(SentimentUri, content); } var jsonResult3 = await response3.Content.ReadAsStringAsync(); var feed3 = JsonConvert.DeserializeObject<Sentiment>(jsonResult3); AnalysisResult(feed); AnalysisKeyPhraseResult(feed2); AnalysisSentimentResult(feed3); } private void AnalysisResult(TextAnalyticsReplyBody feed) { foreach (var f in feed.documents) { foreach (var l in f.detectedLanguages) { Language = $"{l.name}(confidence:{l.score:p})"; IsoName = l.iso6391Name; } } if (string.Equals(IsoName, "en") || string.Equals(IsoName, "ja") || string.Equals(IsoName, "de") || string.Equals(IsoName, "es")) { WarningText = ""; } else { WarningText = $"Key phases and sentiment score cannot be detected from {Language} text at this time."; KeyPhrases = ""; SentimentResult = ""; } } private void AnalysisKeyPhraseResult(DetectkeyPhrases feed) { foreach (var doc in feed.documents) { foreach (var keys in doc.keyPhrases) { KeyPhrases += $"{keys}, "; } } } private void AnalysisSentimentResult(Sentiment feed) { foreach (var f in feed.documents) { SentimentResult = $"{f.score:p}"; } } } }
34.086957
160
0.551913
[ "MIT" ]
builttoroam/BuildIt
src/BuildIt.CognitiveServices/Samples/CognitiveServicesDemo/ViewModels/LanguageTextAnalyticsViewModel.cs
7,842
C#
using System; using System.Net.Sockets; using System.Threading.Tasks; using SharpMessaging.Core.Networking.Helpers; namespace SharpMessaging.Core.Networking { public class SocketReceiver : IReceiveState { private readonly SocketAsyncEventArgs _readArgs; private readonly SocketAwaitable _readAwaitable; private readonly Socket _socket; public SocketReceiver(Socket socket, SocketAsyncEventArgs readArgs, SocketAwaitable readAwaitable, byte[] buffer) { _socket = socket; _readArgs = readArgs; _readAwaitable = readAwaitable; Buffer = buffer; } public byte[] Buffer { get; set; } public int Offset { get; set; } public int BytesLeftInBuffer => WriteOffset - Offset; public int WriteOffset { get; set; } /// <summary> /// Number of bytes that are not currently used in the buffer. /// </summary> public int BytesUnallocatedInBuffer => Buffer.Length - WriteOffset; public async Task EnsureEnoughData(int amountOfBytesToGuarantee) { if (BytesLeftInBuffer >= amountOfBytesToGuarantee) return; var bytesReceived = 0; while (amountOfBytesToGuarantee > 0) { // Nearing the end of the buffer, we must move all remaining data to the beginning // so that we can continue to receive. if (Buffer.Length < Offset + BytesLeftInBuffer + amountOfBytesToGuarantee) { if (BytesUnallocatedInBuffer - BytesLeftInBuffer < amountOfBytesToGuarantee) throw new InvalidOperationException("Our buffer is too small."); System.Buffer.BlockCopy(Buffer, Offset, Buffer, 0, BytesLeftInBuffer); Offset = 0; } _readArgs.SetBuffer(Buffer, WriteOffset, BytesUnallocatedInBuffer); var isPending = _socket.ReceiveAsync(_readArgs); if (isPending) { _readAwaitable.Reset(); await _readAwaitable; } if (_readArgs.BytesTransferred == 0) throw new InvalidOperationException("We got disconnected. TODO: Change this exception."); amountOfBytesToGuarantee -= _readArgs.BytesTransferred; bytesReceived += _readArgs.BytesTransferred; } WriteOffset += bytesReceived; } public void EnsureBufferSize(int dataSize) { if (Buffer.Length >= dataSize) return; var buffer = new byte[dataSize]; if (BytesLeftInBuffer <= 0) return; System.Buffer.BlockCopy(Buffer, Offset, buffer, 0, BytesLeftInBuffer); Offset = 0; Buffer = buffer; } } }
34.453488
121
0.58218
[ "Apache-2.0" ]
jgauffin/SharpMessaging
src/SharpMessaging.Core/Networking/SocketReceiver.cs
2,965
C#
#region CVS Version Header /* * $Id$ * Last modified by $Author$ * Last modified at $Date$ * $Revision$ */ #endregion #region usings using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; using Genghis; using Infragistics.Win.UltraWinExplorerBar; using Infragistics.Win.UltraWinToolbars; using RssBandit.WinGui.Interfaces; using RssBandit.WinGui.Utility; #endregion namespace RssBandit.WinGui.Controls { /// <summary> /// Does support general state serialization of on controls /// </summary> public class StateSerializationHelper { #region ctor's private StateSerializationHelper() {} #endregion #region ------- PRIVATE METHODS --------------------------------------- private static string GetKeyOrderArray(Infragistics.Shared.KeyedSubObjectsCollectionBase c, string separator) { StringBuilder sb = new StringBuilder(); Infragistics.Shared.IKeyedSubObject[] a = new Infragistics.Shared.IKeyedSubObject[c.Count]; c.CopyTo(a, 0); for (int i = 0; i < a.Length; i++) { Infragistics.Shared.IKeyedSubObject o = a[i]; if (o.Key == null || o.Key.Length == 0) throw new InvalidOperationException("KeyedSubObjectsCollectionBase must have a unique Key."); if (i > 0) sb.Append(separator); sb.Append(o.Key); } return sb.ToString(); } #endregion #region public members #if USE_UltraDockManager private static Version _infragisticsDockingVersion = null; public static Version InfragisticsDockingVersion { get { if (_infragisticsDockingVersion == null) _infragisticsDockingVersion = Assembly.GetAssembly(typeof(UltraDockManager)).GetName().Version; return _infragisticsDockingVersion; } } /// <summary> /// Saves the current state of a UltraDockManager (including images & texts) to a byte-array. /// No exceptions are catched in this method /// </summary> /// <param name="dockManager">UltraDockManager</param> /// <returns>byte[]</returns> public static byte[] SaveControlStateToByte(UltraDockManager dockManager) { using (MemoryStream stream = SaveDockManager(dockManager, true)) { return stream.ToArray(); } } /// <summary> /// Saves the current state of a UltraDockManager (including images & texts) to a (Xml) string. /// No exceptions are catched in this method /// </summary> /// <param name="dockManager">UltraDockManager</param> /// <returns>string (Xml)</returns> public static string SaveControlStateToString(UltraDockManager dockManager) { using (MemoryStream stream = SaveDockManager(dockManager, false)) { StreamReader r = new StreamReader(stream); return r.ReadToEnd(); } } /// <summary> /// Saves the current state of a DockManager (including images & texts) to a byte-array. /// No exceptions are catched in this method /// </summary> public static MemoryStream SaveDockManager(UltraDockManager dockManager, bool asBinary) { MemoryStream stream = new MemoryStream(); if (asBinary) dockManager.SaveAsBinary(stream); else dockManager.SaveAsXML(stream); stream.Seek(0, SeekOrigin.Begin); return stream; } /// <summary> /// Restores a DockManager using the provided byte-array. /// Prior to applying the settings the property 'Text' of all DockabelControlPanes is /// saved to a collection and restored after applying the settings from the byte-array. /// This avoids that string from a different login-language are restored. /// Load failures are ignored. /// </summary> /// <param name="dockManager">UltraDockManager</param> /// <param name="theSettings">byte[]</param> public static void LoadControlStateFromByte(UltraDockManager dockManager, byte[] theSettings) { if (theSettings == null) return; if (theSettings.Length == 0) return; using (Stream stream = new MemoryStream(theSettings)) { LoadDockManager(dockManager, stream, true); } } /// <summary> /// Restores a DockManager using the provided string. /// Prior to applying the settings the property 'Text' of all DockabelControlPanes is /// saved to a collection and restored after applying the settings from the byte-array. /// This avoids that string from a different login-language are restored. /// Load failures are ignored. /// </summary> /// <param name="dockManager">UltraDockManager</param> /// <param name="theSettings">string</param> public static void LoadControlStateFromString(UltraDockManager dockManager, string theSettings) { if (string.IsNullOrEmpty(theSettings)) return; using (Stream stream = new MemoryStream()) { StreamWriter writer = new StreamWriter(stream); writer.Write(theSettings); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); LoadDockManager(dockManager, stream, false); } } /// <summary> /// Restores a DockManager using the provided byte-array. /// Prior to applying the settings the property 'Text' of all DockableControlPanes is /// saved to a collection and restored after applying the settings from the byte-array. /// This avoids that string from a different login-language are restored. /// No Exceptions are catched by this method. /// </summary> /// <param name="dockManager">UltraDockManager</param> /// <param name="stream">Stream</param> /// <param name="asBinary">bool</param> public static void LoadDockManager(UltraDockManager dockManager, Stream stream, bool asBinary) { DockAreaPane oDockArea; DockableControlPane oDockContPane; int i, j; Hashtable oTexts; //First remember original (current language) strings oTexts = new Hashtable(); for (i = 0; i < dockManager.DockAreas.Count; i++) { oDockArea = dockManager.DockAreas[i]; for (j = 0; j < oDockArea.Panes.Count; j++) { oDockContPane = oDockArea.Panes[j] as DockableControlPane; if (oDockContPane != null) { oTexts.Add(oDockContPane.Control.Name, oDockContPane.Text); } } } //Now load the settings try { if (asBinary) dockManager.LoadFromBinary(stream); else dockManager.LoadFromXML(stream); } catch (Exception ex) { Trace.WriteLine("dockManager.LoadFrom...() failed: " + ex.Message); return; // use it as it was initialized on the original form } //The stream already has the captions stored, so overwrite them //with the current ones (could be different language) for (i = 0; i < dockManager.DockAreas.Count; i++) { oDockArea = dockManager.DockAreas[i]; for (j = 0; j < oDockArea.Panes.Count; j++) { oDockContPane = oDockArea.Panes[j] as DockableControlPane; if (oDockContPane != null) { if (oTexts.Contains(oDockContPane.Control.Name)) { oDockContPane.Text = (string) oTexts[oDockContPane.Control.Name]; } } } } } #endif private static Version _infragisticsToolbarVersion = null; public static Version InfragisticsToolbarVersion { get { if (_infragisticsToolbarVersion == null) _infragisticsToolbarVersion = Assembly.GetAssembly(typeof(UltraToolbarsManager)).GetName().Version; return _infragisticsToolbarVersion; } } /// <summary> /// Saves the current state of a ToolbarManager (including images &amp; texts) to a byte-array. /// No exceptions are catched in this method /// </summary> /// <param name="toolbarManager">UltraToolbarsManager</param> /// <param name="saveUserCustomizations">true, to get also the user customizations saved</param> /// <returns>byte[]</returns> public static byte[] SaveControlStateToByte(UltraToolbarsManager toolbarManager, bool saveUserCustomizations) { using (MemoryStream stream = SaveToolbarManager(toolbarManager, saveUserCustomizations)) { return stream.ToArray(); } } /// <summary> /// Saves the current state of a ToolbarManager (including images &amp; texts) to a (Xml) string. /// No exceptions are catched in this method /// </summary> public static string SaveControlStateToString(UltraToolbarsManager toolbarManager, bool saveUserCustomizations) { //using (MemoryStream stream = SaveToolbarManager(toolbarManager, saveUserCustomizations, false)) { // StreamReader r = new StreamReader(stream); // return r.ReadToEnd(); //} return Convert.ToBase64String(SaveControlStateToByte(toolbarManager, saveUserCustomizations)); } /// <summary> /// Saves the current state of a ToolbarManager (including images &amp; texts) to a byte-array. /// No exceptions are catched in this method /// </summary> /// <param name="toolbarManager">UltraToolbarsManager</param> /// <param name="saveUserCustomizations">True, if user customizations should be included</param> public static MemoryStream SaveToolbarManager(UltraToolbarsManager toolbarManager, bool saveUserCustomizations) { MemoryStream stream = new MemoryStream(); toolbarManager.SaveAsBinary(stream, saveUserCustomizations); stream.Seek(0, SeekOrigin.Begin); return stream; } /// <summary> /// Restores a ToolbarManager using the provided byte-array. /// Prior to applying the settings the (shared) properties 'Caption' and 'ToolTip' /// of each element in the Tools-Collection /// saved and restored after applying the settings from the byte-array. /// This avoids that strings from a different login-language are restored. /// No Exceptions are catched by this method. /// </summary> /// <param name="toolbarManager">UltraToolbarsManager</param> /// <param name="theSettings">byte[]</param> /// <param name="mediator">The mediator.</param> public static void LoadControlStateFromByte(UltraToolbarsManager toolbarManager, byte[] theSettings, CommandMediator mediator) { if (theSettings == null) return; if (theSettings.Length == 0) return; using (Stream stream = new MemoryStream(theSettings)) { LoadToolbarManager(toolbarManager, stream, mediator); } } /// <summary> /// Restores a ToolbarManager using the provided byte-array. /// Prior to applying the settings the (shared) properties 'Caption' and 'ToolTip' /// of each element in the Tools-Collection /// saved and restored after applying the settings from the byte-array. /// This avoids that strings from a different login-language are restored. /// No Exceptions are catched by this method. /// </summary> /// <param name="toolbarManager">UltraToolbarsManager</param> /// <param name="theSettings">string</param> /// <param name="mediator">The mediator.</param> public static void LoadControlStateFromString(UltraToolbarsManager toolbarManager, string theSettings, CommandMediator mediator) { if (string.IsNullOrEmpty(theSettings)) return; var bytes = Convert.FromBase64String(theSettings); LoadControlStateFromByte(toolbarManager, bytes, mediator); //using (Stream stream = new MemoryStream()) { // StreamWriter writer = new StreamWriter(stream); // writer.Write(theSettings); // writer.Flush(); // stream.Seek(0, SeekOrigin.Begin); // LoadToolbarManager(toolbarManager, stream, mediator); //} } struct LocalizedProperties { public string Caption; public string ToolTipText; public string StatusText; public string DescriptionOnMenu; public string Category; public string CustomizerCaption; public string CustomizerDescription; public LocalizedProperties(ToolBase tool) { Caption = tool.SharedProps.Caption; ToolTipText = tool.SharedProps.ToolTipText; StatusText = tool.SharedProps.StatusText; DescriptionOnMenu = tool.SharedProps.DescriptionOnMenu; Category = tool.SharedProps.Category; CustomizerCaption= tool.SharedProps.CustomizerCaption; CustomizerDescription = tool.SharedProps.CustomizerDescription; } public void Apply(ToolBase tool) { tool.SharedProps.Caption = Caption; tool.SharedProps.ToolTipText = ToolTipText; tool.SharedProps.StatusText = StatusText; tool.SharedProps.DescriptionOnMenu = DescriptionOnMenu; tool.SharedProps.Category = Category; tool.SharedProps.CustomizerCaption = CustomizerCaption; tool.SharedProps.CustomizerDescription = CustomizerDescription; } } /// <summary> /// Restores a ToolbarManager using the provided byte-array. /// Prior to applying the settings the (shared) properties 'Caption' and 'ToolTip' /// of each element in the Tools-Collection /// saved and restored after applying the settings from the byte-array. /// This avoids that strings from a different login-language are restored. /// No Exceptions are catched by this method. /// </summary> /// <param name="toolbarManager">UltraToolbarsManager</param> /// <param name="stream">Stream</param> /// <param name="mediator">The mediator.</param> public static void LoadToolbarManager(UltraToolbarsManager toolbarManager, Stream stream, CommandMediator mediator) { //First remember original (current language) strings Hashtable oCaptions = new Hashtable(); for (int i = 0; i < toolbarManager.Tools.Count; i++) { ToolBase oTool = toolbarManager.Tools[i]; LocalizedProperties props = new LocalizedProperties(oTool); oCaptions.Add(oTool.Key, props); } //Now load the settings try { toolbarManager.LoadFromBinary(stream); } catch (Exception ex) { Trace.WriteLine("toolbarManager.LoadFrom...() failed: " + ex.Message); return; // use it as it was initialized on the original form } //The stream already has the captions stored, so overwrite them //with the current ones (could be different language) for (int i = 0; i < toolbarManager.Tools.Count; i++) { ToolBase oTool = toolbarManager.Tools[i]; if (oCaptions.Contains(oTool.Key)) { LocalizedProperties props = (LocalizedProperties) oCaptions[oTool.Key]; props.Apply(oTool); } mediator.ReRegisterCommand(oTool as ICommand); } } private static Version _infragisticsExplorerBarVersion = null; public static Version InfragisticsExplorerBarVersion { get { if (_infragisticsExplorerBarVersion == null) _infragisticsExplorerBarVersion = Assembly.GetAssembly(typeof(UltraExplorerBar)).GetName().Version; return _infragisticsExplorerBarVersion; } } /// <summary> /// Restores a UltraExplorerBar using the provided Preferences. /// </summary> /// <param name="explorerBar">UltraExplorerBar</param> /// <param name="store">Settings</param> /// <param name="preferenceId">String. The ID the settings should come from /// (multiple sets may exist in the Preference store)</param> /// <exception cref="ArgumentNullException">If any of the parameters is null</exception> /// <exception cref="InvalidOperationException">If the collection of groups allow duplicate keys /// or any group does not have a unique key</exception> internal static void LoadExplorerBar(UltraExplorerBar explorerBar, UiStateSettings store, string preferenceId) { if (explorerBar == null) throw new ArgumentNullException("explorerBar"); if (store == null) throw new ArgumentNullException("store"); if (preferenceId == null || preferenceId.Length == 0) throw new ArgumentNullException("preferenceId"); if (explorerBar.Groups.AllowDuplicateKeys) throw new InvalidOperationException("UltraExplorerBarGroupsCollection must provide unique Keys to support Load/Save settings operations."); // explorerBar.LoadFromXml(@"D:\expl.xml"); // return; Preferences prefReader = store.GetSubnode(preferenceId); int version = prefReader.GetInt32("version", 0); // make the impl. extendable if (version < 1) return; // wrong version Rectangle dimensions = new Rectangle(); dimensions.X = prefReader.GetInt32("Location.X", explorerBar.Location.X); dimensions.Y = prefReader.GetInt32("Location.Y", explorerBar.Location.Y); dimensions.Width = prefReader.GetInt32("Size.Width", explorerBar.Size.Width); dimensions.Height = prefReader.GetInt32("Size.Height", explorerBar.Size.Height); if (explorerBar.Dock == DockStyle.None && explorerBar.Anchor == AnchorStyles.None) explorerBar.Bounds = dimensions; explorerBar.NavigationMaxGroupHeaders = prefReader.GetInt32("MaxGroupHeaders", explorerBar.NavigationMaxGroupHeaders); // no groups: nothing more to initialize if (explorerBar.Groups.Count == 0) return; // First handle order of groups. // build the default order array: string defaultOrder = GetKeyOrderArray(explorerBar.Groups, ";"); // read saved order: string orderArray = prefReader.GetString("groupOrder", defaultOrder); ArrayList groupOrder = new ArrayList(orderArray.Split(new char[]{';'})); for (int i = 0; i < groupOrder.Count; i++) { string key = (string)groupOrder[i]; if (explorerBar.Groups.Exists(key) && explorerBar.Groups.IndexOf(key) != i && i < explorerBar.Groups.Count) { // restore: UltraExplorerBarGroup group = explorerBar.Groups[key]; explorerBar.Groups.Remove(group); explorerBar.Groups.Insert(i, group); } } string selectedGroup = prefReader.GetString("selected", explorerBar.SelectedGroup.Key); for (int i = 0; i < explorerBar.Groups.Count; i++) { UltraExplorerBarGroup group = explorerBar.Groups[i]; string key = String.Format("group.{0}", i); if (group.Key != null && group.Key.Length > 0) key = String.Format("group.{0}", group.Key); group.Visible = prefReader.GetBoolean(String.Format("{0}.Visible", key), group.Visible); if (selectedGroup == key) group.Selected = true; } } /// <summary> /// Saves a UltraExplorerBar using the provided Preferences store. /// </summary> /// <param name="explorerBar">UltraExplorerBar</param> /// <param name="store">Settings</param> /// <param name="preferenceId">String. The ID the settings should come from /// (multiple sets may exist in the Preference store)</param> /// <exception cref="ArgumentNullException">If any of the parameters is null</exception> /// <exception cref="InvalidOperationException">If the collection of groups allow duplicate keys /// or any group does not have a unique key</exception> internal static void SaveExplorerBar(UltraExplorerBar explorerBar, UiStateSettings store, string preferenceId) { if (explorerBar == null) throw new ArgumentNullException("explorerBar"); if (store == null) throw new ArgumentNullException("store"); if (string.IsNullOrEmpty(preferenceId)) throw new ArgumentNullException("preferenceId"); if (explorerBar.Groups.AllowDuplicateKeys) throw new InvalidOperationException("UltraExplorerBarGroupsCollection must provide unique Keys to support Load/Save settings operations."); // explorerBar.SaveAsXml(@"D:\expl.xml"); // return; Preferences prefWriter = store.GetSubnode(preferenceId); prefWriter.SetProperty("version", 1); // make the impl. extendable prefWriter.SetProperty("Location.X", explorerBar.Location.X); prefWriter.SetProperty("Location.Y", explorerBar.Location.Y); prefWriter.SetProperty("Size.Width", explorerBar.Size.Width); prefWriter.SetProperty("Size.Height", explorerBar.Size.Height); prefWriter.SetProperty("MaxGroupHeaders", explorerBar.NavigationMaxGroupHeaders); // no groups: nothing more to write if (explorerBar.Groups.Count == 0) { prefWriter.SetProperty("groupOrder", null); return; } // build/write the order array: prefWriter.SetProperty("groupOrder", GetKeyOrderArray(explorerBar.Groups, ";")); for (int i = 0; i < explorerBar.Groups.Count; i++) { UltraExplorerBarGroup group = explorerBar.Groups[i]; string key = String.Format("group.{0}", i); if (group.Key != null && group.Key.Length > 0) key = String.Format("group.{0}", group.Key); if (group.Selected) prefWriter.SetProperty("selected", key); prefWriter.SetProperty(String.Format("{0}.Visible", key), group.Visible); } } #endregion } } #region CVS Version Log /* * $Log: StateSerializationHelper.cs,v $ * Revision 1.4 2006/12/15 13:31:00 t_rendelmann * reworked to make dynamic menus work after toolbar gets loaded from .settings.xml * * Revision 1.3 2006/12/12 12:04:24 t_rendelmann * finished: all toolbar migrations; save/restore/customization works * * Revision 1.2 2006/11/30 12:05:29 t_rendelmann * changed; next version with the new menubar and the main toolbar migrated to IG - still work in progress * * Revision 1.1 2006/10/10 17:43:30 t_rendelmann * feature: added a commandline option to allow users to reset the UI (don't init from .settings.xml); * fixed: explorer bar state was not saved/restored, corresponding menu entries hold the wrong state on explorer group change * */ #endregion
38.022968
144
0.694577
[ "BSD-3-Clause" ]
RssBandit/RssBandit
source/RssBandit/WinGui/Controls/StateSerializationHelper.cs
21,523
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Linq; using System.Net; using Xunit; namespace Compute.Tests { public class VMImagesTests { [Fact] public void TestVMImageGet() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); string[] availableWindowsServerImageVersions = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter").Select(t => t.Name).ToArray(); var vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", availableWindowsServerImageVersions[0]); Assert.Equal(availableWindowsServerImageVersions[0], vmimage.Name); Assert.Equal(ComputeManagementTestUtilities.DefaultLocation, vmimage.Location, StringComparer.OrdinalIgnoreCase); // FIXME: This doesn't work with a real Windows Server images, which is what's in the query parameters. // Bug 4196378 /* Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Name == "name"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Publisher == "publisher"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Product == "product"); */ Assert.Equal(OperatingSystemTypes.Windows, vmimage.OsDiskImage.OperatingSystem); //Assert.True(vmimage.VirtualMachineImage.DataDiskImages.Count(ddi => ddi.Lun == 123456789) != 0); } } [Fact] public void TestVMImageAutomaticOSUpgradeProperties() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // Validate if images supporting automatic OS upgrades return // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = true in GET VMImageVesion call string imagePublisher = "MicrosoftWindowsServer"; string imageOffer = "WindowsServer"; string imageSku = "2016-Datacenter"; string[] availableWindowsServerImageVersions =_pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray(); string firstVersion = availableWindowsServerImageVersions.First(); string lastVersion = null; if (availableWindowsServerImageVersions.Length >= 2) { lastVersion = availableWindowsServerImageVersions.Last(); } var vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion); Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); if (!string.IsNullOrEmpty(lastVersion)) { vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion); Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); } // Validate if image not whitelisted to support automatic OS upgrades, return // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = false in GET VMImageVesion call imagePublisher = "Canonical"; imageOffer = "UbuntuServer"; imageSku = _pirClient.VirtualMachineImages.ListSkus(ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer).FirstOrDefault().Name; string[] availableUbuntuImageVersions = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray(); firstVersion = availableUbuntuImageVersions.First(); lastVersion = null; if (availableUbuntuImageVersions.Length >= 2) { lastVersion = availableUbuntuImageVersions.Last(); } vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion); Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); if (!string.IsNullOrEmpty(lastVersion)) { vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion); Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); } } } [Fact] public void TestVMImageListNoFilter() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter"); Assert.True(vmimages.Count > 0); //Assert.True(vmimages.Count(vmi => vmi.Name == AvailableWindowsServerImageVersions[0]) != 0); //Assert.True(vmimages.Count(vmi => vmi.Name == AvailableWindowsServerImageVersions[1]) != 0); } } [Fact] public void TestVMImageListFilters() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // Filter: top - Negative Test var vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 0); Assert.True(vmimages.Count == 0); // Filter: top - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1); Assert.True(vmimages.Count == 1); // Filter: top - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 2); Assert.True(vmimages.Count == 2); // Filter: orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", orderby: "name desc"); // Filter: orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 2, orderby: "name asc"); Assert.True(vmimages.Count == 2); // Filter: top orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1, orderby: "name desc"); Assert.True(vmimages.Count == 1); // Filter: top orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1, orderby: "name asc"); Assert.True(vmimages.Count == 1); } } [Fact] public void TestVMImageListPublishers() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var publishers = _pirClient.VirtualMachineImages.ListPublishers( ComputeManagementTestUtilities.DefaultLocation); Assert.True(publishers.Count > 0); Assert.True(publishers.Count(pub => pub.Name == "MicrosoftWindowsServer") != 0); } } [Fact] public void TestVMImageListOffers() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var offers = _pirClient.VirtualMachineImages.ListOffers( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer"); Assert.True(offers.Count > 0); Assert.True(offers.Count(offer => offer.Name == "WindowsServer") != 0); } } [Fact] public void TestVMImageListSkus() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var skus = _pirClient.VirtualMachineImages.ListSkus( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer"); Assert.True(skus.Count > 0); Assert.True(skus.Count(sku => sku.Name == "2012-R2-Datacenter") != 0); } } } }
46.353383
166
0.592944
[ "MIT" ]
HaoQian-MS/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/tests/ScenarioTests/VMImageTests.cs
12,330
C#
// Copyright (c) 2015 AlphaSierraPapa for the SharpDevelop Team // // 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 ICSharpCode.PackageManagement; namespace PackageManagement.Tests.Helpers { public class TestableInstallPackageAction : InstallPackageAction { public TestableInstallPackageAction( IPackageManagementProject project, IPackageManagementEvents packageManagementEvents) : base(project, packageManagementEvents) { CreateOpenPackageReadMeMonitorAction = packageId => { IOpenPackageReadMeMonitor monitor = base.CreateOpenPackageReadMeMonitor(packageId); OpenPackageReadMeMonitor = monitor as OpenPackageReadMeMonitor; NullOpenPackageReadMeMonitorIsCreated = monitor is NullOpenPackageReadMeMonitor; return monitor; }; } public OpenPackageReadMeMonitor OpenPackageReadMeMonitor; public Func<string, IOpenPackageReadMeMonitor> CreateOpenPackageReadMeMonitorAction; protected override IOpenPackageReadMeMonitor CreateOpenPackageReadMeMonitor(string packageId) { return CreateOpenPackageReadMeMonitorAction(packageId); } public bool NullOpenPackageReadMeMonitorIsCreated; } }
43.72
95
0.798262
[ "MIT" ]
TetradogOther/SharpDevelop
src/AddIns/Misc/PackageManagement/Test/Src/Helpers/TestableInstallPackageAction.cs
2,188
C#
using System; using System.Collections.Generic; using System.Text; using Utils.EnumResourse; namespace EntitysServices { public class BillingRequest { public int Id { get; set; } public int Idclient { get; set; } public int IdPayment { get; set; } public int IdOrder { get; set; } public List<BillingProductRequest> products { get; set; } } }
22.166667
65
0.64411
[ "MIT" ]
andrez299321/JvMySandwiche
JvBillingServices/EntitysServices/BillingRequest.cs
401
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request to modify the system's default policy settings. /// The response is either SuccessResponse or ErrorResponse. /// The following elements are only used in AS data mode: /// GroupAdminDialableCallerIDAccess /// ServiceProviderAdminDialableCallerIDAccess /// GroupAdminCommunicationBarringUserProfileAccess (This element is only used for groups in an Enterprise) /// GroupAdminVerifyTranslationAndRoutingAccess /// ServiceProviderVerifyTranslationAndRoutingAccess /// groupUserAutoAttendantNameDialingAccess /// The following elements are only used in XS data mode: /// serviceProviderAdminCommunicationBarringAccess /// /// Replaced by: SystemPolicyModifyDefaultRequest22 in AS mode /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// <see cref="SystemPolicyModifyDefaultRequest22"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""de4d76f01f337fe4694212ec9f771753:9170""}]")] public class SystemPolicyModifyDefaultRequest14 : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.C.SuccessResponse> { private BroadWorksConnector.Ocip.Models.GroupCallingPlanAccess _groupCallingPlanAccess; [XmlElement(ElementName = "groupCallingPlanAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupCallingPlanAccess GroupCallingPlanAccess { get => _groupCallingPlanAccess; set { GroupCallingPlanAccessSpecified = true; _groupCallingPlanAccess = value; } } [XmlIgnore] protected bool GroupCallingPlanAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupExtensionAccess _groupExtensionAccess; [XmlElement(ElementName = "groupExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupExtensionAccess GroupExtensionAccess { get => _groupExtensionAccess; set { GroupExtensionAccessSpecified = true; _groupExtensionAccess = value; } } [XmlIgnore] protected bool GroupExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupLDAPIntegrationAccess _groupLDAPIntegrationAccess; [XmlElement(ElementName = "groupLDAPIntegrationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupLDAPIntegrationAccess GroupLDAPIntegrationAccess { get => _groupLDAPIntegrationAccess; set { GroupLDAPIntegrationAccessSpecified = true; _groupLDAPIntegrationAccess = value; } } [XmlIgnore] protected bool GroupLDAPIntegrationAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupVoiceMessagingAccess _groupVoiceMessagingAccess; [XmlElement(ElementName = "groupVoiceMessagingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupVoiceMessagingAccess GroupVoiceMessagingAccess { get => _groupVoiceMessagingAccess; set { GroupVoiceMessagingAccessSpecified = true; _groupVoiceMessagingAccess = value; } } [XmlIgnore] protected bool GroupVoiceMessagingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminUserAccess _groupDepartmentAdminUserAccess; [XmlElement(ElementName = "groupDepartmentAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminUserAccess GroupDepartmentAdminUserAccess { get => _groupDepartmentAdminUserAccess; set { GroupDepartmentAdminUserAccessSpecified = true; _groupDepartmentAdminUserAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminTrunkGroupAccess _groupDepartmentAdminTrunkGroupAccess; [XmlElement(ElementName = "groupDepartmentAdminTrunkGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminTrunkGroupAccess GroupDepartmentAdminTrunkGroupAccess { get => _groupDepartmentAdminTrunkGroupAccess; set { GroupDepartmentAdminTrunkGroupAccessSpecified = true; _groupDepartmentAdminTrunkGroupAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminTrunkGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminPhoneNumberExtensionAccess _groupDepartmentAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "groupDepartmentAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminPhoneNumberExtensionAccess GroupDepartmentAdminPhoneNumberExtensionAccess { get => _groupDepartmentAdminPhoneNumberExtensionAccess; set { GroupDepartmentAdminPhoneNumberExtensionAccessSpecified = true; _groupDepartmentAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupDepartmentAdminCallingLineIdNumberAccess _groupDepartmentAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "groupDepartmentAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupDepartmentAdminCallingLineIdNumberAccess GroupDepartmentAdminCallingLineIdNumberAccess { get => _groupDepartmentAdminCallingLineIdNumberAccess; set { GroupDepartmentAdminCallingLineIdNumberAccessSpecified = true; _groupDepartmentAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool GroupDepartmentAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserAuthenticationAccess _groupUserAuthenticationAccess; [XmlElement(ElementName = "groupUserAuthenticationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupUserAuthenticationAccess GroupUserAuthenticationAccess { get => _groupUserAuthenticationAccess; set { GroupUserAuthenticationAccessSpecified = true; _groupUserAuthenticationAccess = value; } } [XmlIgnore] protected bool GroupUserAuthenticationAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserGroupDirectoryAccess _groupUserGroupDirectoryAccess; [XmlElement(ElementName = "groupUserGroupDirectoryAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupUserGroupDirectoryAccess GroupUserGroupDirectoryAccess { get => _groupUserGroupDirectoryAccess; set { GroupUserGroupDirectoryAccessSpecified = true; _groupUserGroupDirectoryAccess = value; } } [XmlIgnore] protected bool GroupUserGroupDirectoryAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserProfileAccess _groupUserProfileAccess; [XmlElement(ElementName = "groupUserProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupUserProfileAccess GroupUserProfileAccess { get => _groupUserProfileAccess; set { GroupUserProfileAccessSpecified = true; _groupUserProfileAccess = value; } } [XmlIgnore] protected bool GroupUserProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserCallLogAccess _groupUserEnhancedCallLogsAccess; [XmlElement(ElementName = "groupUserEnhancedCallLogsAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupUserCallLogAccess GroupUserEnhancedCallLogsAccess { get => _groupUserEnhancedCallLogsAccess; set { GroupUserEnhancedCallLogsAccessSpecified = true; _groupUserEnhancedCallLogsAccess = value; } } [XmlIgnore] protected bool GroupUserEnhancedCallLogsAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupUserAutoAttendantNameDialingAccess _groupUserAutoAttendantNameDialingAccess; [XmlElement(ElementName = "groupUserAutoAttendantNameDialingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupUserAutoAttendantNameDialingAccess GroupUserAutoAttendantNameDialingAccess { get => _groupUserAutoAttendantNameDialingAccess; set { GroupUserAutoAttendantNameDialingAccessSpecified = true; _groupUserAutoAttendantNameDialingAccess = value; } } [XmlIgnore] protected bool GroupUserAutoAttendantNameDialingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminProfileAccess _groupAdminProfileAccess; [XmlElement(ElementName = "groupAdminProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminProfileAccess GroupAdminProfileAccess { get => _groupAdminProfileAccess; set { GroupAdminProfileAccessSpecified = true; _groupAdminProfileAccess = value; } } [XmlIgnore] protected bool GroupAdminProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminUserAccess _groupAdminUserAccess; [XmlElement(ElementName = "groupAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminUserAccess GroupAdminUserAccess { get => _groupAdminUserAccess; set { GroupAdminUserAccessSpecified = true; _groupAdminUserAccess = value; } } [XmlIgnore] protected bool GroupAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminAdminAccess _groupAdminAdminAccess; [XmlElement(ElementName = "groupAdminAdminAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminAdminAccess GroupAdminAdminAccess { get => _groupAdminAdminAccess; set { GroupAdminAdminAccessSpecified = true; _groupAdminAdminAccess = value; } } [XmlIgnore] protected bool GroupAdminAdminAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminDepartmentAccess _groupAdminDepartmentAccess; [XmlElement(ElementName = "groupAdminDepartmentAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminDepartmentAccess GroupAdminDepartmentAccess { get => _groupAdminDepartmentAccess; set { GroupAdminDepartmentAccessSpecified = true; _groupAdminDepartmentAccess = value; } } [XmlIgnore] protected bool GroupAdminDepartmentAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminAccessDeviceAccess _groupAdminAccessDeviceAccess; [XmlElement(ElementName = "groupAdminAccessDeviceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminAccessDeviceAccess GroupAdminAccessDeviceAccess { get => _groupAdminAccessDeviceAccess; set { GroupAdminAccessDeviceAccessSpecified = true; _groupAdminAccessDeviceAccess = value; } } [XmlIgnore] protected bool GroupAdminAccessDeviceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminEnhancedServiceInstanceAccess _groupAdminEnhancedServiceInstanceAccess; [XmlElement(ElementName = "groupAdminEnhancedServiceInstanceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminEnhancedServiceInstanceAccess GroupAdminEnhancedServiceInstanceAccess { get => _groupAdminEnhancedServiceInstanceAccess; set { GroupAdminEnhancedServiceInstanceAccessSpecified = true; _groupAdminEnhancedServiceInstanceAccess = value; } } [XmlIgnore] protected bool GroupAdminEnhancedServiceInstanceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminFeatureAccessCodeAccess _groupAdminFeatureAccessCodeAccess; [XmlElement(ElementName = "groupAdminFeatureAccessCodeAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminFeatureAccessCodeAccess GroupAdminFeatureAccessCodeAccess { get => _groupAdminFeatureAccessCodeAccess; set { GroupAdminFeatureAccessCodeAccessSpecified = true; _groupAdminFeatureAccessCodeAccess = value; } } [XmlIgnore] protected bool GroupAdminFeatureAccessCodeAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminPhoneNumberExtensionAccess _groupAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "groupAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminPhoneNumberExtensionAccess GroupAdminPhoneNumberExtensionAccess { get => _groupAdminPhoneNumberExtensionAccess; set { GroupAdminPhoneNumberExtensionAccessSpecified = true; _groupAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool GroupAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminCallingLineIdNumberAccess _groupAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "groupAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminCallingLineIdNumberAccess GroupAdminCallingLineIdNumberAccess { get => _groupAdminCallingLineIdNumberAccess; set { GroupAdminCallingLineIdNumberAccessSpecified = true; _groupAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool GroupAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminServiceAccess _groupAdminServiceAccess; [XmlElement(ElementName = "groupAdminServiceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminServiceAccess GroupAdminServiceAccess { get => _groupAdminServiceAccess; set { GroupAdminServiceAccessSpecified = true; _groupAdminServiceAccess = value; } } [XmlIgnore] protected bool GroupAdminServiceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminTrunkGroupAccess _groupAdminTrunkGroupAccess; [XmlElement(ElementName = "groupAdminTrunkGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminTrunkGroupAccess GroupAdminTrunkGroupAccess { get => _groupAdminTrunkGroupAccess; set { GroupAdminTrunkGroupAccessSpecified = true; _groupAdminTrunkGroupAccess = value; } } [XmlIgnore] protected bool GroupAdminTrunkGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminVerifyTranslationAndRoutingAccess _groupAdminVerifyTranslationAndRoutingAccess; [XmlElement(ElementName = "groupAdminVerifyTranslationAndRoutingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminVerifyTranslationAndRoutingAccess GroupAdminVerifyTranslationAndRoutingAccess { get => _groupAdminVerifyTranslationAndRoutingAccess; set { GroupAdminVerifyTranslationAndRoutingAccessSpecified = true; _groupAdminVerifyTranslationAndRoutingAccess = value; } } [XmlIgnore] protected bool GroupAdminVerifyTranslationAndRoutingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminSessionAdmissionControlAccess _groupAdminSessionAdmissionControlAccess; [XmlElement(ElementName = "groupAdminSessionAdmissionControlAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminSessionAdmissionControlAccess GroupAdminSessionAdmissionControlAccess { get => _groupAdminSessionAdmissionControlAccess; set { GroupAdminSessionAdmissionControlAccessSpecified = true; _groupAdminSessionAdmissionControlAccess = value; } } [XmlIgnore] protected bool GroupAdminSessionAdmissionControlAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminDialableCallerIDAccess _groupAdminDialableCallerIDAccess; [XmlElement(ElementName = "groupAdminDialableCallerIDAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminDialableCallerIDAccess GroupAdminDialableCallerIDAccess { get => _groupAdminDialableCallerIDAccess; set { GroupAdminDialableCallerIDAccessSpecified = true; _groupAdminDialableCallerIDAccess = value; } } [XmlIgnore] protected bool GroupAdminDialableCallerIDAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminOfficeZoneAccess _groupAdminOfficeZoneAccess; [XmlElement(ElementName = "groupAdminOfficeZoneAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminOfficeZoneAccess GroupAdminOfficeZoneAccess { get => _groupAdminOfficeZoneAccess; set { GroupAdminOfficeZoneAccessSpecified = true; _groupAdminOfficeZoneAccess = value; } } [XmlIgnore] protected bool GroupAdminOfficeZoneAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminNumberActivationAccess _groupAdminNumberActivationAccess; [XmlElement(ElementName = "groupAdminNumberActivationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminNumberActivationAccess GroupAdminNumberActivationAccess { get => _groupAdminNumberActivationAccess; set { GroupAdminNumberActivationAccessSpecified = true; _groupAdminNumberActivationAccess = value; } } [XmlIgnore] protected bool GroupAdminNumberActivationAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.GroupAdminCommunicationBarringUserProfileAccess _groupAdminCommunicationBarringUserProfileAccess; [XmlElement(ElementName = "groupAdminCommunicationBarringUserProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.GroupAdminCommunicationBarringUserProfileAccess GroupAdminCommunicationBarringUserProfileAccess { get => _groupAdminCommunicationBarringUserProfileAccess; set { GroupAdminCommunicationBarringUserProfileAccessSpecified = true; _groupAdminCommunicationBarringUserProfileAccess = value; } } [XmlIgnore] protected bool GroupAdminCommunicationBarringUserProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminProfileAccess _serviceProviderAdminProfileAccess; [XmlElement(ElementName = "serviceProviderAdminProfileAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminProfileAccess ServiceProviderAdminProfileAccess { get => _serviceProviderAdminProfileAccess; set { ServiceProviderAdminProfileAccessSpecified = true; _serviceProviderAdminProfileAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminProfileAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminGroupAccess _serviceProviderAdminGroupAccess; [XmlElement(ElementName = "serviceProviderAdminGroupAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminGroupAccess ServiceProviderAdminGroupAccess { get => _serviceProviderAdminGroupAccess; set { ServiceProviderAdminGroupAccessSpecified = true; _serviceProviderAdminGroupAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminGroupAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminUserAccess _serviceProviderAdminUserAccess; [XmlElement(ElementName = "serviceProviderAdminUserAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminUserAccess ServiceProviderAdminUserAccess { get => _serviceProviderAdminUserAccess; set { ServiceProviderAdminUserAccessSpecified = true; _serviceProviderAdminUserAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminUserAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminAdminAccess _serviceProviderAdminAdminAccess; [XmlElement(ElementName = "serviceProviderAdminAdminAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminAdminAccess ServiceProviderAdminAdminAccess { get => _serviceProviderAdminAdminAccess; set { ServiceProviderAdminAdminAccessSpecified = true; _serviceProviderAdminAdminAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminAdminAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminDepartmentAccess _serviceProviderAdminDepartmentAccess; [XmlElement(ElementName = "ServiceProviderAdminDepartmentAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminDepartmentAccess ServiceProviderAdminDepartmentAccess { get => _serviceProviderAdminDepartmentAccess; set { ServiceProviderAdminDepartmentAccessSpecified = true; _serviceProviderAdminDepartmentAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminDepartmentAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminAccessDeviceAccess _serviceProviderAdminAccessDeviceAccess; [XmlElement(ElementName = "serviceProviderAdminAccessDeviceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminAccessDeviceAccess ServiceProviderAdminAccessDeviceAccess { get => _serviceProviderAdminAccessDeviceAccess; set { ServiceProviderAdminAccessDeviceAccessSpecified = true; _serviceProviderAdminAccessDeviceAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminAccessDeviceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminPhoneNumberExtensionAccess _serviceProviderAdminPhoneNumberExtensionAccess; [XmlElement(ElementName = "serviceProviderAdminPhoneNumberExtensionAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminPhoneNumberExtensionAccess ServiceProviderAdminPhoneNumberExtensionAccess { get => _serviceProviderAdminPhoneNumberExtensionAccess; set { ServiceProviderAdminPhoneNumberExtensionAccessSpecified = true; _serviceProviderAdminPhoneNumberExtensionAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminPhoneNumberExtensionAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminCallingLineIdNumberAccess _serviceProviderAdminCallingLineIdNumberAccess; [XmlElement(ElementName = "serviceProviderAdminCallingLineIdNumberAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminCallingLineIdNumberAccess ServiceProviderAdminCallingLineIdNumberAccess { get => _serviceProviderAdminCallingLineIdNumberAccess; set { ServiceProviderAdminCallingLineIdNumberAccessSpecified = true; _serviceProviderAdminCallingLineIdNumberAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminCallingLineIdNumberAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminServiceAccess _serviceProviderAdminServiceAccess; [XmlElement(ElementName = "serviceProviderAdminServiceAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminServiceAccess ServiceProviderAdminServiceAccess { get => _serviceProviderAdminServiceAccess; set { ServiceProviderAdminServiceAccessSpecified = true; _serviceProviderAdminServiceAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminServiceAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminServicePackAccess _serviceProviderAdminServicePackAccess; [XmlElement(ElementName = "serviceProviderAdminServicePackAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminServicePackAccess ServiceProviderAdminServicePackAccess { get => _serviceProviderAdminServicePackAccess; set { ServiceProviderAdminServicePackAccessSpecified = true; _serviceProviderAdminServicePackAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminServicePackAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminSessionAdmissionControlAccess _serviceProviderAdminSessionAdmissionControlAccess; [XmlElement(ElementName = "serviceProviderAdminSessionAdmissionControlAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminSessionAdmissionControlAccess ServiceProviderAdminSessionAdmissionControlAccess { get => _serviceProviderAdminSessionAdmissionControlAccess; set { ServiceProviderAdminSessionAdmissionControlAccessSpecified = true; _serviceProviderAdminSessionAdmissionControlAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminSessionAdmissionControlAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminVerifyTranslationAndRoutingAccess _serviceProviderAdminVerifyTranslationAndRoutingAccess; [XmlElement(ElementName = "serviceProviderAdminVerifyTranslationAndRoutingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminVerifyTranslationAndRoutingAccess ServiceProviderAdminVerifyTranslationAndRoutingAccess { get => _serviceProviderAdminVerifyTranslationAndRoutingAccess; set { ServiceProviderAdminVerifyTranslationAndRoutingAccessSpecified = true; _serviceProviderAdminVerifyTranslationAndRoutingAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminVerifyTranslationAndRoutingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminWebBrandingAccess _serviceProviderAdminWebBrandingAccess; [XmlElement(ElementName = "serviceProviderAdminWebBrandingAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminWebBrandingAccess ServiceProviderAdminWebBrandingAccess { get => _serviceProviderAdminWebBrandingAccess; set { ServiceProviderAdminWebBrandingAccessSpecified = true; _serviceProviderAdminWebBrandingAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminWebBrandingAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminOfficeZoneAccess _serviceProviderAdminOfficeZoneAccess; [XmlElement(ElementName = "serviceProviderAdminOfficeZoneAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminOfficeZoneAccess ServiceProviderAdminOfficeZoneAccess { get => _serviceProviderAdminOfficeZoneAccess; set { ServiceProviderAdminOfficeZoneAccessSpecified = true; _serviceProviderAdminOfficeZoneAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminOfficeZoneAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminCommunicationBarringAccess _serviceProviderAdminCommunicationBarringAccess; [XmlElement(ElementName = "serviceProviderAdminCommunicationBarringAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminCommunicationBarringAccess ServiceProviderAdminCommunicationBarringAccess { get => _serviceProviderAdminCommunicationBarringAccess; set { ServiceProviderAdminCommunicationBarringAccessSpecified = true; _serviceProviderAdminCommunicationBarringAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminCommunicationBarringAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.EnterpriseAdminNetworkPolicyAccess _enterpriseAdminNetworkPolicyAccess; [XmlElement(ElementName = "enterpriseAdminNetworkPolicyAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.EnterpriseAdminNetworkPolicyAccess EnterpriseAdminNetworkPolicyAccess { get => _enterpriseAdminNetworkPolicyAccess; set { EnterpriseAdminNetworkPolicyAccessSpecified = true; _enterpriseAdminNetworkPolicyAccess = value; } } [XmlIgnore] protected bool EnterpriseAdminNetworkPolicyAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ServiceProviderAdminDialableCallerIDAccess _serviceProviderAdminDialableCallerIDAccess; [XmlElement(ElementName = "serviceProviderAdminDialableCallerIDAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.ServiceProviderAdminDialableCallerIDAccess ServiceProviderAdminDialableCallerIDAccess { get => _serviceProviderAdminDialableCallerIDAccess; set { ServiceProviderAdminDialableCallerIDAccessSpecified = true; _serviceProviderAdminDialableCallerIDAccess = value; } } [XmlIgnore] protected bool ServiceProviderAdminDialableCallerIDAccessSpecified { get; set; } private BroadWorksConnector.Ocip.Models.EnterpriseAdminNumberActivationAccess _enterpriseAdminNumberActivationAccess; [XmlElement(ElementName = "enterpriseAdminNumberActivationAccess", IsNullable = false, Namespace = "")] [Optional] [Group(@"de4d76f01f337fe4694212ec9f771753:9170")] public BroadWorksConnector.Ocip.Models.EnterpriseAdminNumberActivationAccess EnterpriseAdminNumberActivationAccess { get => _enterpriseAdminNumberActivationAccess; set { EnterpriseAdminNumberActivationAccessSpecified = true; _enterpriseAdminNumberActivationAccess = value; } } [XmlIgnore] protected bool EnterpriseAdminNumberActivationAccessSpecified { get; set; } } }
42.912222
157
0.690919
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemPolicyModifyDefaultRequest14.cs
38,621
C#
// <copyright file="GetAssemblyFromFile_Should.cs" company="Automate The Planet Ltd."> // Copyright 2018 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System.Reflection; using NUnit.Framework; namespace Meissa.Infrastructure.UnitTests.ReflectionProviderTests { [TestFixture] public class GetAssemblyFromFile_Should { [Test] public void CorrectAssemblyReturned() { // Arrange var expectedAssembly = Assembly.GetExecutingAssembly(); // Act var reflectionProvider = new ReflectionProvider(); var actualAssembly = reflectionProvider.GetAssemblyFromFile(expectedAssembly.Location); // Assert Assert.That(actualAssembly, Is.EqualTo(expectedAssembly)); } } }
39.138889
99
0.709013
[ "Apache-2.0" ]
AutomateThePlanet/Meissa
Meissa.Infrastructure.UnitTests/ReflectionProviderTests/GetAssemblyFromFile_Should.cs
1,411
C#
using System.Security; using System.Windows.Controls; using WorkingWithMaps.Example.Core; namespace WorkingWithMaps.Example.Views { public partial class LoginView : UserControl, IHavePassword { public LoginView() { InitializeComponent(); } public SecureString Password { get { return passwordBox.SecurePassword; } } public void ClearPassword() { passwordBox.Clear(); } } }
19.88
63
0.595573
[ "Apache-2.0" ]
anttikajanus/working-with-maps-arcgis-runtime-dotnet
src/WorkingWithMaps/Views/LoginView.xaml.cs
499
C#
using UnityEditor; using UnityEngine; using UniGLTF; using System.IO; using UniGLTF.MeshUtility; #if UNITY_2020_2_OR_NEWER using UnityEditor.AssetImporters; #else using UnityEditor.Experimental.AssetImporters; #endif namespace UniVRM10 { [CustomEditor(typeof(VrmScriptedImporter))] public class VrmScriptedImporterEditorGUI : ScriptedImporterEditor { VrmScriptedImporter m_importer; GltfParser m_parser; VrmLib.Model m_model; UniGLTF.Extensions.VRMC_vrm.VRMC_vrm m_vrm; string m_message; public override void OnEnable() { base.OnEnable(); m_importer = target as VrmScriptedImporter; m_message = VrmScriptedImporterImpl.TryParseOrMigrate(m_importer.assetPath, m_importer.MigrateToVrm1, out m_parser); if (!string.IsNullOrEmpty(m_message)) { // error return; } if (!UniGLTF.Extensions.VRMC_vrm.GltfDeserializer.TryGet(m_parser.GLTF.extensions, out m_vrm)) { // error m_message = "no vrm1"; m_parser = null; return; } m_model = ModelReader.Read(m_parser); } enum Tabs { Model, Materials, Vrm, } static Tabs s_currentTab; public override void OnInspectorGUI() { if (!string.IsNullOrEmpty(m_message)) { EditorGUILayout.HelpBox(m_message, MessageType.Error); } s_currentTab = TabBar.OnGUI(s_currentTab); GUILayout.Space(10); switch (s_currentTab) { case Tabs.Model: base.OnInspectorGUI(); break; case Tabs.Materials: if (m_parser != null && m_vrm != null) { EditorMaterial.OnGUI(m_importer, m_parser, new Vrm10TextureDescriptorGenerator(m_parser), assetPath => $"{Path.GetFileNameWithoutExtension(assetPath)}.vrm1.Textures", assetPath => $"{Path.GetFileNameWithoutExtension(assetPath)}.vrm1.Materials"); } break; case Tabs.Vrm: if (m_parser != null && m_vrm != null) { EditorVrm.OnGUI(m_importer, m_parser, m_vrm); } break; } } } }
29.101124
128
0.527413
[ "MIT" ]
oocytanb/UniVRM
Assets/VRM10/Editor/ScriptedImporter/VrmScriptedImporterEditorGUI.cs
2,592
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 08.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.Int64.Double{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int64; using T_DATA2 =System.Double; using T_DATA1_U=System.Int64; using T_DATA2_U=System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_BIGINT"; private const string c_NameOf__COL_DATA2 ="COL2_DOUBLE"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=4; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ == /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N_AS_DBL("t",c_NameOf__COL_DATA1).T(" = ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.Int64.Double
29.582781
158
0.562794
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete/Int64/Double/TestSet_001__fields__01__VV.cs
4,469
C#
using System; using ha.models.contracts; using ha.sdk; namespace ha.data.models { class DBCommand : ICommand { public DBCommand() { Id = Guid.NewGuid().ToString(); } public string Id { get; set; } public DbDevice Device { get; set; } public string CommandName { get; set; } public string Parameters { get; set; } public int ExecutionOrder { get; set; } IDevice ICommand.Device { get => Device; set => Device = (DbDevice)value; } } }
23.173913
83
0.574109
[ "MIT" ]
petefield/ha.hub
ha.hub.data/models/DbDeviceState.cs
535
C#
namespace ClassBoxDataValidation { using System; public class Box { // Fields. private double length; private double width; private double height; // Properties. private double Length { set { if (value <= 0) { throw new ArgumentException("Length cannot be zero or negative."); } this.length = value; } } private double Width { set { if (value <= 0) { throw new ArgumentException("Width cannot be zero or negative."); } this.width = value; } } private double Height { set { if (value <= 0) { throw new ArgumentException("Height cannot be zero or negative."); } this.height = value; } } // Constructor. public Box(double length, double width, double height) { this.Length = length; this.Width = width; this.Height = height; } // Methods. public double Volume() { return this.length * this.width * this.height; } public double LateralSurfaceArea() { return (2 * this.length * this.height) + (2 * width * height); } public double SurfaceArea() { return (2 * this.length * this.width) + (2 * this.length * this.height) + (2 * this.width * this.height); } } }
22.855263
117
0.425446
[ "MIT" ]
VeselinBPavlov/csharp-oop-basics
06. Encapsulation - Exercise/ClassBoxDataValidation/Box.cs
1,739
C#
using LinkedLists.Classes; using MergeLists; using System; using Xunit; namespace TestMergeList { public class UnitTest1 { [Theory] [InlineData(0, 1)] [InlineData(3, 9)] [InlineData(5, 4)] public void TestMerge(int position, int expected) { LinkedList list1 = new LinkedList(new Node(2)); LinkedList list2 = new LinkedList(new Node(4)); list1.Add(new Node(3)); list1.Add(new Node(1)); list2.Add(new Node(9)); list2.Add(new Node(5)); Node result = Program.MergeLists(list1, list2); for (int i = 0; i < position; i++) { result = result.Next; } Assert.Equal(expected, result.Value); } } }
25.903226
59
0.524284
[ "MIT" ]
btaylor93/Data-Structures-and-Algorithms
Challenges/MergeLists/TestMergeList/UnitTest1.cs
803
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.Windows.Input; namespace Microsoft.Test.Input { /// <summary> /// The raw actions being reported from the mouse. /// </summary> /// <remarks> /// Note that multiple actions can be reported at once. /// </remarks> [Flags] public enum RawMouseActions { /// <summary> /// No mouse actions. /// </summary> None = 0x0, /// <summary> /// The mouse attributes have changed. The application needs to /// query the mouse attributes. /// </summary> AttributesChanged = 0x1, /// <summary> /// The mouse became active in the application. The application /// may need to refresh its mouse state. /// </summary> Activate = 0x2, /// <summary> /// The mouse became inactive in the application. The application /// may need to clear its mouse state. /// </summary> Deactivate = 0x4, /// <summary> /// The mouse moved, and the position is reported relative to /// the last reported position. /// </summary> RelativeMove = 0x8, /// <summary> /// The mouse moved, and the position is reported in absolute /// coordinates. /// </summary> AbsoluteMove = 0x10, /// <summary> /// The mouse moved, and the position is reported in coordinates /// relative to the virtual desktop. /// </summary> VirtualDesktopMove = 0x20, /// <summary> /// The first button was pressed. /// </summary> Button1Press = 0x40, /// <summary> /// The first button was released. /// </summary> Button1Release = 0x80, /// <summary> /// The second button was pressed. /// </summary> Button2Press = 0x100, /// <summary> /// The second button was released. /// </summary> Button2Release = 0x200, /// <summary> /// The third button was pressed. /// </summary> Button3Press = 0x400, /// <summary> /// The third button was released. /// </summary> Button3Release = 0x800, /// <summary> /// The fourth button was pressed. /// </summary> Button4Press = 0x1000, /// <summary> /// The fourth button was released. /// </summary> Button4Release = 0x2000, /// <summary> /// The fifth button was pressed. /// </summary> Button5Press = 0x4000, /// <summary> /// The fifth button was released. /// </summary> Button5Release = 0x8000, /// <summary> /// The vertical wheel was roteated. /// </summary> VerticalWheelRotate = 0x10000, /// <summary> /// The horizontal wheel was roteated. /// </summary> HorizontalWheelRotate = 0x20000, /// <summary> /// The mouse cursor was queried. /// </summary> QueryCursor = 0x40000, /// <summary> /// The mouse capture was lost. /// </summary> CancelCapture = 0x80000 // update the IsValid method in RawMouseInputReport when this enum is changed } }
28.93985
85
0.491556
[ "MIT" ]
batzen/wpf-test
src/Test/Common/Code/Microsoft/Test/Input/RawMouseActions.cs
3,849
C#
// <copyright file="FieldBlock.cs" company="LeetABit"> // Copyright (c) Hubert Bukowski. All rights reserved. // Licensed under the MIT License. // See LICENSE file in the project root for full license information. // </copyright> namespace LeetABit.Binary.Blocks { using System; /// <summary> /// Represents field definition block. /// </summary> public class FieldBlock : IDefinitionBlock { /// <summary> /// Function that obtains a path to the defined field. /// </summary> private readonly Func<IEvaluationContext, LogicalPath> fieldPath; /// <summary> /// Function that obtains a length of the field. /// </summary> private readonly Func<IEvaluationContext, int> length; /// <summary> /// Function that obtains a default value for the field. /// </summary> private readonly Func<IEvaluationContext, object> defaultValue; /// <summary> /// Function that obtains a field value converter. /// </summary> private readonly Func<IEvaluationContext, IBinaryValueConverter> converter; /// <summary> /// Initializes a new instance of the <see cref="FieldBlock"/> class. /// </summary> /// <param name="fieldPath"> /// Function that obtains a path to the defined field. /// </param> /// <param name="length"> /// Function that obtains a length of the field. /// </param> /// <param name="defaultValue"> /// Function that obtains a default value for the field. /// </param> /// <param name="converter"> /// Function that obtains a field value converter. /// </param> public FieldBlock( Func<IEvaluationContext, LogicalPath> fieldPath, Func<IEvaluationContext, int> length, Func<IEvaluationContext, object> defaultValue, Func<IEvaluationContext, IBinaryValueConverter> converter) { this.fieldPath = Requires.ArgumentNotNull(fieldPath, nameof(fieldPath)); this.length = Requires.ArgumentNotNull(length, nameof(length)); this.defaultValue = Requires.ArgumentNotNull(defaultValue, nameof(defaultValue)); this.converter = Requires.ArgumentNotNull(converter, nameof(converter)); } /// <summary> /// Implements processing of the current definition block using specified coding context. /// </summary> /// <param name="context"> /// Coding context that contans current coding data. /// </param> /// <returns> /// Object that represents processing result. /// </returns> public Result Process(ICodingContext context) { _ = Requires.ArgumentNotNull(context, nameof(context)); return context.MapField(this.fieldPath(context), this.length(context), this.converter(context), this.defaultValue(context)); } } }
38.3625
136
0.60378
[ "MIT" ]
hubuk/Binary
src/LeetABit.Binary.Protocols/Blocks/FieldBlock.cs
3,069
C#
#region File Description //----------------------------------------------------------------------------- // Game.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; using AuroraManagement; using Microsoft.Xna.Framework; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Audio; namespace AuroraGame { /// <summary> /// Sample showing how to manage different game states, with transitions /// between menu screens, a loading screen, the game itself, and a pause /// menu. This main game class is extremely simple: all the interesting /// stuff happens in the ScreenManager component. /// </summary> public class AuroraGame : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; ScreenManager screenManager; ScreenFactory screenFactory; /// <summary> /// The main game constructor. /// </summary> public AuroraGame() { Content.RootDirectory = "Content"; graphics = new GraphicsDeviceManager(this); TargetElapsedTime = TimeSpan.FromTicks(333333); #if WINDOWS_PHONE graphics.IsFullScreen = true; // Choose whether you want a landscape or portait game by using one of the two helper functions. InitializeLandscapeGraphics(); // InitializePortraitGraphics(); #endif // Create the screen factory and add it to the Services screenFactory = new ScreenFactory(); Services.AddService(typeof(IScreenFactory), screenFactory); // Create the screen manager component. screenManager = new ScreenManager(this); Components.Add(screenManager); #if WINDOWS_PHONE // Hook events on the PhoneApplicationService so we're notified of the application's life cycle Microsoft.Phone.Shell.PhoneApplicationService.Current.Launching += new EventHandler<Microsoft.Phone.Shell.LaunchingEventArgs>(GameLaunching); Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(GameActivated); Microsoft.Phone.Shell.PhoneApplicationService.Current.Deactivated += new EventHandler<Microsoft.Phone.Shell.DeactivatedEventArgs>(GameDeactivated); #else // On Windows and Xbox we just add the initial screens AddInitialScreens(); #endif } private void AddInitialScreens() { // Activate the first screens. screenManager.AddScreen(new BackgroundScreen(), null); // We have different menus for Windows Phone to take advantage of the touch interface #if WINDOWS_PHONE screenManager.AddScreen(new PhoneMainMenuScreen(), null); #else screenManager.AddScreen(new MainMenuScreen(), null); #endif } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.Black); // The real drawing happens inside the screen manager component. base.Draw(gameTime); } #if WINDOWS_PHONE /// <summary> /// Helper method to the initialize the game to be a portrait game. /// </summary> private void InitializePortraitGraphics() { graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 800; } /// <summary> /// Helper method to initialize the game to be a landscape game. /// </summary> private void InitializeLandscapeGraphics() { graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 480; } void GameLaunching(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e) { AddInitialScreens(); } void GameActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) { // Try to deserialize the screen manager if (!screenManager.Activate(e.IsApplicationInstancePreserved)) { // If the screen manager fails to deserialize, add the initial screens AddInitialScreens(); } } void GameDeactivated(object sender, Microsoft.Phone.Shell.DeactivatedEventArgs e) { // Serialize the screen manager when the game deactivated screenManager.Deactivate(); } #endif } }
35.627586
109
0.610724
[ "MIT" ]
sa501428/playground
Aurora/GameStateManagementSample/Game.cs
5,166
C#
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ namespace Apache.Ignite.Core.Impl.Cache { using System; using System.Collections; using System.Collections.Generic; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Impl.Binary.IO; /// <summary> /// Real cache enumerator communicating with Java. /// </summary> internal class CacheEnumerator<TK, TV> : PlatformDisposableTargetAdapter, IEnumerator<ICacheEntry<TK, TV>> { /** Operation: next value. */ private const int OpNext = 1; /** Keep binary flag. */ private readonly bool _keepBinary; /** Current entry. */ private CacheEntry<TK, TV>? _cur; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="keepBinary">Keep binary flag.</param> public CacheEnumerator(IPlatformTargetInternal target, bool keepBinary) : base(target) { _keepBinary = keepBinary; } /** <inheritdoc /> */ public bool MoveNext() { ThrowIfDisposed(); return DoInOp(OpNext, stream => { var reader = Marshaller.StartUnmarshal(stream, _keepBinary); bool hasNext = reader.ReadBoolean(); if (hasNext) { reader.DetachNext(); TK key = reader.ReadObject<TK>(); reader.DetachNext(); TV val = reader.ReadObject<TV>(); _cur = new CacheEntry<TK, TV>(key, val); return true; } _cur = null; return false; }); } /** <inheritdoc /> */ public ICacheEntry<TK, TV> Current { get { ThrowIfDisposed(); if (_cur == null) throw new InvalidOperationException( "Invalid enumerator state, enumeration is either finished or not started"); return _cur.Value; } } /** <inheritdoc /> */ object IEnumerator.Current { get { return Current; } } /** <inheritdoc /> */ public void Reset() { throw new NotSupportedException("Specified method is not supported."); } /** <inheritdoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { throw new InvalidOperationException("Should not be called."); } } }
33.824427
110
0.606409
[ "Apache-2.0", "CC0-1.0" ]
DirectXceriD/gridgain
modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/CacheEnumerator.cs
4,443
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ------------------------------------------------------------ namespace Microsoft.Extensions.DependencyInjection { using System; using Dapr; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; /// <summary> /// Provides extension methods for <see cref="IMvcBuilder" />. /// </summary> public static class DaprMvcBuilderExtensions { /// <summary> /// Adds Dapr integration for MVC to the provided <see cref="IMvcBuilder" />. /// </summary> /// <param name="builder">The <see cref="IMvcBuilder" />.</param> /// <returns>The <see cref="IMvcBuilder" /> builder.</returns> public static IMvcBuilder AddDapr(this IMvcBuilder builder) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } // This pattern prevents registering services multiple times in the case AddDapr is called // by non-user-code. if (builder.Services.Contains(ServiceDescriptor.Singleton<DaprMvcMarkerService, DaprMvcMarkerService>())) { return builder; } builder.Services.AddDaprClient(); builder.Services.AddSingleton<DaprMvcMarkerService>(); builder.Services.AddSingleton<IApplicationModelProvider, StateEntryApplicationModelProvider>(); builder.Services.Configure<MvcOptions>(options => { options.ModelBinderProviders.Insert(0, new StateEntryModelBinderProvider()); }); return builder; } private class DaprMvcMarkerService { } } }
35
117
0.572507
[ "MIT" ]
brucehu123/dotnet-sdk
src/Dapr.AspNetCore/DaprMvcBuilderExtensions.cs
1,855
C#
using SistemaTaller.BackEnd.API.Models; using SistemaTaller.BackEnd.API.Repository; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace SistemaTaller.BackEnd.API.RepositorySQL { public class EstadoReparacionesRepository : ConexionDB, IEstadoReparacionesRepository { public EstadoReparacionesRepository(SqlConnection context, SqlTransaction transaction) { this._context = context; this._transaction = transaction; } public void Actualizar(EstadoReparaciones estadoReparaciones) { var query = "UPDATE EstadoReparaciones SET IdEstadoReparacion = @IdEstadoReparacion, NombreEstado = @NombreEstado, ModificadoPor = @ModificadoPor, FechaCreacion = @FechaModificacion WHERE IdEstadoReparacion = @IdEstadoReparacion"; var command = CreateCommand(query); command.Parameters.AddWithValue("@IdEstadoReparacion", estadoReparaciones.IdEstadoReparacion); command.Parameters.AddWithValue("@NombreEstado", estadoReparaciones.NombreEstado); command.Parameters.AddWithValue("@ModificadoPor", estadoReparaciones.ModificadoPor); command.Parameters.AddWithValue("@FechaModificacion", estadoReparaciones.FechaModificacion); command.ExecuteNonQuery(); } public void Elimnar() { throw new NotImplementedException(); } public void Insertar(EstadoReparaciones estadoReparaciones) { var query = "SP_EstadoReparaciones_Insert"; var command = CreateCommand(query); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@IdEstadoReparacion", estadoReparaciones.IdEstadoReparacion); command.Parameters.AddWithValue("@NombreEstado", estadoReparaciones.NombreEstado); command.Parameters.AddWithValue("@CreadoPor", estadoReparaciones.CreadoPor); command.ExecuteNonQuery(); } public EstadoReparaciones SeleccionarPorId(string IdEstadoReparacion) { var query = "SELECT * FROM vwEstadoDeReparaciones_SeleccionarTodo WHERE IdEstadoReparacion = @IdEstadoReparacion"; var command = CreateCommand(query); command.Parameters.AddWithValue("@IdEstadoReparacion", IdEstadoReparacion); SqlDataReader reader = command.ExecuteReader(); EstadoReparaciones estadoSelect = new(); while (reader.Read()) { estadoSelect.IdEstadoReparacion = Convert.ToInt32(reader["IdEstadoReparacion"]); estadoSelect.NombreEstado = Convert.ToString(reader["NombreEstado"]); } reader.Close(); return estadoSelect; } public List<EstadoReparaciones> SeleccionarTodos() { var query = "SELECT * FROM vwEstadoDeReparaciones_SeleccionarTodo"; var command = CreateCommand(query); SqlDataReader reader = command.ExecuteReader(); List<EstadoReparaciones> lisEstadoReparaciones = new List<EstadoReparaciones>(); while (reader.Read()) { EstadoReparaciones estadoSelect = new(); estadoSelect.IdEstadoReparacion = Convert.ToInt32(reader["IdEstadoReparacion"]); estadoSelect.NombreEstado = Convert.ToString(reader["NombreEstado"]); estadoSelect.Activo = Convert.ToBoolean(reader["Activo"]); estadoSelect.FechaCreacion = Convert.ToDateTime(reader["FechaCreacion"]); estadoSelect.FechaModificacion = (DateTime?)(reader.IsDBNull("FechaModificacion") ? null : reader["FechaModificacion"]); estadoSelect.CreadoPor = Convert.ToString(reader["CreadoPor"]); estadoSelect.ModificadoPor = Convert.ToString(reader["ModificadoPor"]); lisEstadoReparaciones.Add(estadoSelect); } reader.Close(); return lisEstadoReparaciones; } } }
41.217822
242
0.668989
[ "MIT" ]
Dynart/SistemaTaller.BackEnd
SistemaTaller.BackEnd.API/RepositorySQL/EstadoReparacionesRepository.cs
4,165
C#
 namespace JobsInterfaces { using Hangfire.Server; public interface IDummyJob { void DoJob(PerformContext context); } }
13.272727
43
0.657534
[ "MIT" ]
face-it/Hangfire.Tags
samples/MultipleDashboards/JobsInterfaces/IDummyJob.cs
148
C#
// Copyright (c) Aurora Studio. All rights reserved. // // Licensed under the MIT License. See LICENSE in the project root for license information. using Com.Aurora.AuWeather.Core.Models.Caiyun.JsonContract; using Com.Aurora.AuWeather.Core.Models.WunderGround.JsonContract; using System; using System.Globalization; namespace Com.Aurora.AuWeather.Models.HeWeather { public class NowWeather { public NowCondition Now { get; private set; } public Temperature BodyTemprature { get; private set; } public float Precipitation { get; private set; } public Length Visibility { get; private set; } public Wind Wind { get; private set; } public Pressure Pressure { get; private set; } public Temperature Temprature { get; private set; } public NowWeather(JsonContract.NowWeatherContract now) { if (now == null) { return; } CultureInfo provider = CultureInfo.InvariantCulture; Now = new NowCondition(now.cond); int fl; if (int.TryParse(now.fl, NumberStyles.Any, provider, out fl)) BodyTemprature = Temperature.FromCelsius(fl); float pcpn; if (float.TryParse(now.pcpn, NumberStyles.Any, provider, out pcpn)) Precipitation = pcpn; if (float.TryParse(now.vis, NumberStyles.Any, provider, out pcpn)) Visibility = Length.FromKM(pcpn); Wind = new Wind(now.wind); if (float.TryParse(now.pres, NumberStyles.Any, provider, out pcpn)) Pressure = Pressure.FromHPa(pcpn); if (int.TryParse(now.tmp, NumberStyles.Any, provider, out fl)) Temprature = Temperature.FromCelsius(fl); } public NowWeather(double temp, string con, PcpnTotal pcpn, WindTotal wind) { Now = new NowCondition(con); BodyTemprature = null; Precipitation = (float)pcpn.local.intensity; Wind = new Wind(wind); Pressure = null; Temprature = Temperature.FromCelsius((float)temp); } public NowWeather(observation current_observation) { if (current_observation == null) { return; } Now = new NowCondition(current_observation); CultureInfo provider = CultureInfo.InvariantCulture; float i; Temprature = Temperature.FromCelsius(current_observation.temp_c); if (float.TryParse(current_observation.feelslike_c, NumberStyles.Any, provider, out i)) { BodyTemprature = Temperature.FromCelsius(i); } if (float.TryParse(current_observation.precip_today_metric, NumberStyles.Any, provider, out i)) { Precipitation = i; } if (float.TryParse(current_observation.visibility_km, NumberStyles.Any, provider, out i)) { Visibility = Length.FromKM(i); } Wind = new Wind(Convert.ToUInt32(current_observation.wind_kph), Convert.ToUInt32(current_observation.wind_degrees)); if (float.TryParse(current_observation.pressure_mb, NumberStyles.Any, provider, out i)) { Pressure = Pressure.FromHPa(i); } } } public class NowCondition : Condition { public WeatherCondition Condition { get; private set; } public NowCondition(JsonContract.Condition_NowContract cond) { Condition = ParseCondition(cond.code); } public NowCondition(string con) { Condition = ParseCondition_C(con); } public NowCondition(observation current_observation) { Condition = ParseCondition_W(current_observation.icon); } } }
31.814815
129
0.549942
[ "MIT" ]
aurora-lzzp/Aurora-Weather
com.aurora.auweather/Com.Aurora.AuWeather.Core/Models/HeWeather/NowWeather.cs
4,297
C#
using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; namespace Stryker.Core.Mutants { public sealed class TestDescription { private static readonly TestDescription AllTestsDescription; private static readonly string AllTestsGuid = "-1"; public TestDescription(string guid, string name, string testFilePath) { Guid = guid; Name = name; TestFilePath = testFilePath; } static TestDescription() { AllTestsDescription = new TestDescription(AllTestsGuid, "All Tests", ""); } /// <summary> /// Returns an 'all tests' description for test runners that does not support test selection. /// </summary> public static TestDescription AllTests() { return AllTestsDescription; } public string Guid { get; } public string Name { get; } public bool IsAllTests => Guid == AllTestsGuid; public string TestFilePath { get; } private bool Equals(TestDescription other) { return string.Equals(Guid, other.Guid) || IsAllTests || other.IsAllTests; } public static implicit operator TestDescription(TestCase test) { return new TestDescription(test.Id.ToString(), test.FullyQualifiedName, test.CodeFilePath); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == this.GetType() && Equals((TestDescription) obj); } public override int GetHashCode() { return (Guid != null ? Guid.GetHashCode() : 0); } } }
28.261538
103
0.602613
[ "Apache-2.0" ]
JohnMcGlynnMSFT/stryker-net
src/Stryker.Core/Stryker.Core/Mutants/TestDescription.cs
1,839
C#
// // Copyright (c) Gianni Rosa Gallina. All rights reserved. // Licensed under the MIT license. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace WPC.AI.Samples.Common.Model { using System; using System.Collections.Generic; public class DataSetEntry { public string Id { get; set; } // Target variable public float Rank { get; set; } // For Azure Search Preview public string Title { get; set; } public string ThumbnailUrl { get; set; } public string SourceUrl { get; set; } public DataSetEntryType EntryType { get; set; } public string Language { get; set; } public double SentimentScore { get; set; } public double AdultContentScore { get; set; } public double RacyContentScore { get; set; } public int ImagesCount { get; set; } public int PeopleTotalCount { get; set; } public int PeopleFemaleCount { get; set; } public int PeopleMaleCount { get; set; } public int VideosCount { get; set; } public double FruitionTime { get; set; } public string Category { get; set; } //public string DominantBackgroundColor { get; set; } //public string DominantForegroundColor { get; set; } //public string AccentColor { get; set; } //public bool IsBlackAndWhiteImage { get; set; } public IList<DataSetTag> Tags { get; } public DataSetEntry() { Id = Guid.NewGuid().ToString("N"); Tags = new List<DataSetTag>(); Language = "-"; Category = "-"; Rank = 0.0f; SentimentScore = -1.0; FruitionTime = 0; //DominantBackgroundColor = "-"; //DominantForegroundColor = "-"; //AccentColor = "-"; } } }
37.3125
74
0.625461
[ "MIT" ]
gianni-rg/wpc-2017-ai
WPC.AI.Samples.Common/Model/DataSetEntry.cs
2,987
C#
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using System; using System.Collections; using System.Linq; namespace Neo.Cryptography { /// <summary> /// Represents a bloom filter. /// </summary> public class BloomFilter { private readonly uint[] seeds; private readonly BitArray bits; /// <summary> /// The number of hash functions used by the bloom filter. /// </summary> public int K => seeds.Length; /// <summary> /// The size of the bit array used by the bloom filter. /// </summary> public int M => bits.Length; /// <summary> /// Used to generate the seeds of the murmur hash functions. /// </summary> public uint Tweak { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="BloomFilter"/> class. /// </summary> /// <param name="m">The size of the bit array used by the bloom filter.</param> /// <param name="k">The number of hash functions used by the bloom filter.</param> /// <param name="nTweak">Used to generate the seeds of the murmur hash functions.</param> public BloomFilter(int m, int k, uint nTweak) { if (k < 0 || m < 0) throw new ArgumentOutOfRangeException(); this.seeds = Enumerable.Range(0, k).Select(p => (uint)p * 0xFBA4C795 + nTweak).ToArray(); this.bits = new BitArray(m); this.bits.Length = m; this.Tweak = nTweak; } /// <summary> /// Initializes a new instance of the <see cref="BloomFilter"/> class. /// </summary> /// <param name="m">The size of the bit array used by the bloom filter.</param> /// <param name="k">The number of hash functions used by the bloom filter.</param> /// <param name="nTweak">Used to generate the seeds of the murmur hash functions.</param> /// <param name="elements">The initial elements contained in this <see cref="BloomFilter"/> object.</param> public BloomFilter(int m, int k, uint nTweak, ReadOnlyMemory<byte> elements) { if (k < 0 || m < 0) throw new ArgumentOutOfRangeException(); this.seeds = Enumerable.Range(0, k).Select(p => (uint)p * 0xFBA4C795 + nTweak).ToArray(); this.bits = new BitArray(elements.ToArray()); this.bits.Length = m; this.Tweak = nTweak; } /// <summary> /// Adds an element to the <see cref="BloomFilter"/>. /// </summary> /// <param name="element">The object to add to the <see cref="BloomFilter"/>.</param> public void Add(ReadOnlyMemory<byte> element) { foreach (uint i in seeds.AsParallel().Select(s => element.Span.Murmur32(s))) bits.Set((int)(i % (uint)bits.Length), true); } /// <summary> /// Determines whether the <see cref="BloomFilter"/> contains a specific element. /// </summary> /// <param name="element">The object to locate in the <see cref="BloomFilter"/>.</param> /// <returns><see langword="true"/> if <paramref name="element"/> is found in the <see cref="BloomFilter"/>; otherwise, <see langword="false"/>.</returns> public bool Check(byte[] element) { foreach (uint i in seeds.AsParallel().Select(s => element.Murmur32(s))) if (!bits.Get((int)(i % (uint)bits.Length))) return false; return true; } /// <summary> /// Gets the bit array in this <see cref="BloomFilter"/>. /// </summary> /// <param name="newBits">The byte array to store the bits.</param> public void GetBits(byte[] newBits) { bits.CopyTo(newBits, 0); } } }
40.230769
162
0.58174
[ "MIT" ]
awatin/neo
src/neo/Cryptography/BloomFilter.cs
4,184
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("zamnMetronome")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("zamnMetronome")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c05b9fad-2905-4659-8951-e0d3feb80008")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.675676
84
0.748207
[ "MIT" ]
Allbeert/zamnMetronome
zamnMetronome/Properties/AssemblyInfo.cs
1,397
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace BlockText.WinPhone81 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new BlockText.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
34.392157
94
0.67959
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter21/BlockText/BlockText/BlockText.WinPhone81/MainPage.xaml.cs
1,756
C#
// MIT License // // Copyright (c) [2020] [Joe Chavez] // // 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.ComponentModel; using Xamarin.Forms; using Spitzer.Models.NasaMedia; using Spitzer.ViewModels; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Acr.UserDialogs; using Microsoft.AppCenter.Analytics; using Microsoft.AppCenter.Crashes; using Xamarin.Essentials; using FFImageLoading.Forms; namespace Spitzer.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class ItemDetailPage : ContentPage { readonly ItemDetailViewModel viewModel; public ItemDetailPage(ItemDetailViewModel viewModel) { InitializeComponent(); BindingContext = this.viewModel = viewModel; BackgroundPreviewImage.Source = viewModel.Item.ImagePreview; Analytics.TrackEvent($"Opening: {MethodBase.GetCurrentMethod().ReflectedType?.Name}.{MethodBase.GetCurrentMethod().Name}"); } public ItemDetailPage() { InitializeComponent(); var item = new MediaItem(); item.Data = new List<Datum>(1); item.Data.Add(new Datum { Title = "No Images Found", Description = "Please try again later..." }); viewModel = new ItemDetailViewModel(item); BindingContext = viewModel; } private async void OnItemSelected(object sender, SelectionChangedEventArgs args) { var item = (args.CurrentSelection.FirstOrDefault() as ItemImagePreviewViewModel); if (item == null) { ItemDetailView.SelectedItem = null; return; } var viewButton = "View"; var shareImage = "Share - image"; var shareWebLink = "Share - Web link"; var action = await DisplayActionSheet("View or Share?", "Cancel", null, viewButton, shareImage, shareWebLink); Analytics.TrackEvent($"{action} for image: {item.ImageTitle}"); if (action == viewButton) { await Navigation.PushAsync(new ItemImagePage(new ItemImageViewModel(item))); } else if (action == shareImage) { try { var destDirectory = FileSystem.CacheDirectory + Path.DirectorySeparatorChar + "images"; var destFile = FileSystem.CacheDirectory + Path.DirectorySeparatorChar + "images" + Path.DirectorySeparatorChar + item.ImageTitle + "." + item.ImageInformation.Type.ToString().ToLower(); if (item.FileWriteInfo.FilePath != null) { if (!Directory.Exists(destDirectory)) { Directory.CreateDirectory(destDirectory); } File.Copy(item.FileWriteInfo.FilePath, destFile, true); if (File.Exists(destFile)) { await Share.RequestAsync(new ShareFileRequest() { File = new ShareFile(destFile), Title = item.ImageTitle, PresentationSourceBounds = DeviceInfo.Platform== DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet ? new System.Drawing.Rectangle(0, 20, 0, 0) : System.Drawing.Rectangle.Empty }); } else { await UserDialogs.Instance.AlertAsync("There was a problem sharing the image, please try again later.", "Unable to Share", "Okay"); } } else { await UserDialogs.Instance.AlertAsync("There was a problem sharing the image, please try again later.", "Unable to Share", "Okay"); } } catch (Exception e) { Crashes.TrackError(e); await UserDialogs.Instance.AlertAsync("There was a problem sharing the image, please try again later.", "Unable to Share", "Okay"); } } else if (action == shareWebLink) { try { await Share.RequestAsync(new ShareTextRequest { Uri = item.ImagePreview.ToString(), Title = item.ImageTitle, PresentationSourceBounds = DeviceInfo.Platform== DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet ? new System.Drawing.Rectangle(0, 20, 0, 0) : System.Drawing.Rectangle.Empty }); } catch (Exception e) { Crashes.TrackError(e); await UserDialogs.Instance.AlertAsync("There was a problem sharing the link, please try again later.", "Unable to Share", "Okay"); } } // Manually deselect item. ItemDetailView.SelectedItem = null; } private void CachedImage_OnFileWriteFinished(object sender, CachedImageEvents.FileWriteFinishedEventArgs e) { Console.WriteLine($"CachedImage_OnFileWriteFinished : {e.FileWriteInfo.FilePath}"); if (sender is CachedImage cachedImage) { if (cachedImage.BindingContext is ItemImagePreviewViewModel itemImagePreview) { itemImagePreview.FileWriteInfo = e.FileWriteInfo; } } } } }
41.485714
159
0.558815
[ "MIT" ]
gitizenme/spitzer
Spitzer/Views/ItemDetailPage.xaml.cs
7,262
C#
namespace ExRam.Gremlinq.Core.Models { public readonly struct ElementMetadata { public ElementMetadata(string label) { Label = label; } public string Label { get; } } }
17.461538
44
0.568282
[ "MIT" ]
BlacktopSoftwareStudios/ExRam.Gremlinq
src/ExRam.Gremlinq.Core/Models/Metadata/ElementMetadata.cs
229
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using Duality; using Duality.Components; using Duality.Components.Renderers; using Duality.Resources; using Duality.Drawing; using Duality.Editor; namespace Duality.Editor.Plugins.Base.DataConverters { public class ComponentFromMaterial : DataConverter { public override Type TargetType { get { return typeof(SpriteRenderer); } } public override bool CanConvertFrom(ConvertOperation convert) { return convert.AllowedOperations.HasFlag(ConvertOperation.Operation.CreateObj) && convert.CanPerform<Material>(); } public override bool Convert(ConvertOperation convert) { // If we already have a renderer in the result set, consider generating // another one to be not the right course of action. if (convert.Result.OfType<ICmpRenderer>().Any()) return false; List<object> results = new List<object>(); List<Material> availData = convert.Perform<Material>().ToList(); // Generate objects foreach (Material mat in availData) { if (convert.IsObjectHandled(mat)) continue; Texture mainTex = mat.MainTexture.Res; Pixmap basePixmap = (mainTex != null) ? mainTex.BasePixmap.Res : null; GameObject gameobj = convert.Result.OfType<GameObject>().FirstOrDefault(); bool hasAnimation = (mainTex != null && basePixmap != null && basePixmap.Atlas != null && basePixmap.Atlas.Count > 0); // Determine the size of the displayed sprite Vector2 spriteSize; if (hasAnimation) { Rect atlasRect = basePixmap.LookupAtlas(0); spriteSize = atlasRect.Size; } else if (mainTex != null) { spriteSize = mainTex.ContentSize; // If we're dealing with default content, clamp sprite size to // something easily visible in order to avoid 1x1 sprites for // default White / Black or similar fallback textures. if (mainTex.IsDefaultContent) spriteSize = Vector2.Max(spriteSize, new Vector2(32.0f, 32.0f)); } else { spriteSize = Pixmap.Checkerboard.Res.Size; } // Create a sprite Component in any case SpriteRenderer sprite = convert.Result.OfType<SpriteRenderer>().FirstOrDefault(); if (sprite == null && gameobj != null) sprite = gameobj.GetComponent<SpriteRenderer>(); if (sprite == null) sprite = new SpriteRenderer(); sprite.SharedMaterial = mat; sprite.Rect = Rect.Align(Alignment.Center, 0.0f, 0.0f, spriteSize.X, spriteSize.Y); results.Add(sprite); // If we have animation data, create an animator component as well if (hasAnimation) { SpriteAnimator animator = convert.Result.OfType<SpriteAnimator>().FirstOrDefault(); if (animator == null && gameobj != null) animator = gameobj.GetComponent<SpriteAnimator>(); if (animator == null) animator = new SpriteAnimator(); animator.AnimDuration = 5.0f; animator.FrameCount = basePixmap.Atlas.Count; results.Add(animator); } convert.SuggestResultName(sprite, mat.Name); convert.MarkObjectHandled(mat); } convert.AddResult(results); return false; } } }
31.938776
122
0.701597
[ "MIT" ]
AdamsLair/duality
Source/Plugins/EditorBase/DataConverters/ComponentFromMaterial.cs
3,132
C#
namespace StealthTech.RayTracer.Library { public class TriangleGeometry { public string Group { get; set; } public int Vertex1 { get; set; } public int Vertex2 { get; set; } public int Vertex3 { get; set; } public int Normal1 { get; set; } public int Normal2 { get; set; } public int Normal3 { get; set; } public TriangleGeometry() { Group = "Default"; } public TriangleGeometry(string group) { Group = group; } } }
19.1
45
0.514834
[ "MIT" ]
y2k4life/StealthTechRayTracer
src/StealthTech.RayTracer.Library/VertexIndex.cs
575
C#
#if NET35 using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using Theraot; namespace System.Threading.Tasks { public partial class Task { /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. /// </para> /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> collection contained a null task. /// </exception> public static Task WhenAll(IEnumerable<Task> tasks) { // Take a more efficient path if tasks is actually an array var taskArray = tasks as Task[]; if (taskArray != null) { return WhenAll(taskArray); } // Skip a List allocation/copy if tasks is a collection var taskCollection = tasks as ICollection<Task>; if (taskCollection != null) { var index = 0; taskArray = new Task[taskCollection.Count]; foreach (var task in tasks) { if (task == null) throw new ArgumentException("The tasks argument included a null value.", "tasks"); taskArray[index++] = task; } return InternalWhenAll(taskArray); } // Do some argument checking and convert tasks to a List (and later an array). if (tasks == null) throw new ArgumentNullException("tasks"); var taskList = new List<Task>(); foreach (var task in tasks) { if (task == null) throw new ArgumentException("The tasks argument included a null value.", "tasks"); taskList.Add(task); } // Delegate the rest to InternalWhenAll() return InternalWhenAll(taskList.ToArray()); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. /// </para> /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> array contained a null task. /// </exception> public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) throw new ArgumentNullException("tasks"); Contract.EndContractBlock(); var taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // Small optimization in the case of an empty array. var tasksCopy = new Task[taskCount]; for (var i = 0; i < taskCount; i++) { var task = tasks[i]; if (task == null) throw new ArgumentException("The tasks argument included a null value.", "tasks"); tasksCopy[i] = task; } // The rest can be delegated to InternalWhenAll() return InternalWhenAll(tasksCopy); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// </para> /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> collection contained a null task. /// </exception> public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks) { // Take a more efficient route if tasks is actually an array var taskArray = tasks as Task<TResult>[]; if (taskArray != null) { return WhenAll(taskArray); } // Skip a List allocation/copy if tasks is a collection var taskCollection = tasks as ICollection<Task<TResult>>; if (taskCollection != null) { var index = 0; taskArray = new Task<TResult>[taskCollection.Count]; foreach (var task in tasks) { if (task == null) throw new ArgumentException("The tasks argument included a null value.", "tasks"); taskArray[index++] = task; } return InternalWhenAll(taskArray); } // Do some argument checking and convert tasks into a List (later an array) if (tasks == null) throw new ArgumentNullException("tasks"); var taskList = new List<Task<TResult>>(); foreach (var task in tasks) { if (task == null) throw new ArgumentException("Task_MultiTaskContinuation_NullTask", "tasks"); taskList.Add(task); } // Delegate the rest to InternalWhenAll<TResult>(). return InternalWhenAll(taskList.ToArray()); } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <remarks> /// <para> /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. /// </para> /// <para> /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state. /// </para> /// <para> /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. /// The Result of the returned task will be set to an array containing all of the results of the /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). /// </para> /// <para> /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion /// state before it's returned to the caller. The returned TResult[] will be an array of 0 elements. /// </para> /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> array contained a null task. /// </exception> public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) throw new ArgumentNullException("tasks"); Contract.EndContractBlock(); var taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // small optimization in the case of an empty task array var tasksCopy = new Task<TResult>[taskCount]; for (var i = 0; i < taskCount; i++) { var task = tasks[i]; if (task == null) throw new ArgumentException("The tasks argument included a null value.", "tasks"); tasksCopy[i] = task; } // Delegate the rest to InternalWhenAll<TResult>() return InternalWhenAll(tasksCopy); } /// <summary>Returns true if any of the supplied tasks require wait notification.</summary> /// <param name="tasks">The tasks to check.</param> /// <returns>true if any of the tasks require notification; otherwise, false.</returns> internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(IEnumerable<Task> tasks) { if (tasks == null) { Contract.Assert(false, "Expected non-null array of tasks"); throw new ArgumentNullException("tasks"); } foreach (var task in tasks) { if ( task != null && task.IsWaitNotificationEnabled && task.ShouldNotifyDebuggerOfWaitCompletion ) // potential recursion { return true; } } return false; } // Some common logic to support WhenAll() methods // tasks should be a defensive copy. private static Task InternalWhenAll(Task[] tasks) { Contract.Requires(tasks != null, "Expected a non-null tasks array"); // take shortcut if there are no tasks upon which to wait if (tasks.Length == 0) { return CompletedTask; } return new WhenAllPromise(tasks); } // Some common logic to support WhenAll<TResult> methods private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] tasks) { Contract.Requires(tasks != null, "Expected a non-null tasks array"); // take shortcut if there are no tasks upon which to wait if (tasks.Length == 0) { return FromResult(new TResult[0]); } return new WhenAllPromise<TResult>(tasks); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed.</returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> array contained a null task, or was empty. /// </exception> public static Task<Task> WhenAny(params Task[] tasks) { if (tasks == null) { throw new ArgumentNullException("tasks"); } if (tasks.Length == 0) { throw new ArgumentException("The tasks argument contains no tasks.", "tasks"); } Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks array // after we return but before the WhenAny asynchronously completes. var taskCount = tasks.Length; var tasksCopy = new Task[taskCount]; for (var index = 0; index < taskCount; index++) { var task = tasks[index]; if (task == null) { throw new ArgumentException("The tasks argument included a null value.", "tasks"); } tasksCopy[index] = task; } var signaledTaskIndex = -1; return PrivateWhenAny(tasksCopy, ref signaledTaskIndex); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed.</returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> collection contained a null task, or was empty. /// </exception> public static Task<Task> WhenAny(IEnumerable<Task> tasks) { if (tasks == null) { throw new ArgumentNullException("tasks"); } Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks collection // after we return but before the WhenAny asynchronously completes. var taskList = new List<Task>(); foreach (var task in tasks) { if (task == null) { throw new ArgumentException("The tasks argument included a null value.", "tasks"); } taskList.Add(task); } if (taskList.Count == 0) { throw new ArgumentException("The tasks argument contains no tasks.", "tasks"); } var signaledTaskIndex = -1; return PrivateWhenAny(taskList, ref signaledTaskIndex); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed.</returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> array contained a null task, or was empty. /// </exception> public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks) { // We would just like to do this: // return (Task<Task<TResult>>) WhenAny( (Task[]) tasks); // but classes are not covariant to enable casting Task<TResult> to Task<Task<TResult>>. // Call WhenAny(Task[]) for basic functionality var intermediate = WhenAny((Task[])tasks); // Return a continuation task with the correct result type return intermediate.ContinueWith(Task<TResult>.ContinuationConvertion, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return Task's Result is the task that completed.</returns> /// <remarks> /// The returned task will complete when any of the supplied tasks has completed. The returned task will always end in the RanToCompletion state /// with its Result set to the first task to complete. This is true even if the first task to complete ended in the Canceled or Faulted state. /// </remarks> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="tasks"/> argument was null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="tasks"/> collection contained a null task, or was empty. /// </exception> public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks) { // We would just like to do this: // return (Task<Task<TResult>>) WhenAny( (IEnumerable<Task>) tasks); // but classes are not covariant to enable casting Task<TResult> to Task<Task<TResult>>. // Call WhenAny(IEnumerable<Task>) for basic functionality var intermediate = WhenAny((IEnumerable<Task>)tasks); // Return a continuation task with the correct result type return intermediate.ContinueWith(Task<TResult>.ContinuationConvertion, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } } } #endif
51.901442
222
0.594136
[ "Apache-2.0" ]
FFFF0h/SharedMemoryStream.Library
lib/NetSerializer.Library/lib/System.Core.Net35/Core/System/Threading/Tasks/Task.when.net35.cs
21,591
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.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Sas.Transform; using Aliyun.Acs.Sas.Transform.V20181203; namespace Aliyun.Acs.Sas.Model.V20181203 { public class ModifyCreateVulWhitelistRequest : RpcAcsRequest<ModifyCreateVulWhitelistResponse> { public ModifyCreateVulWhitelistRequest() : base("Sas", "2018-12-03", "ModifyCreateVulWhitelist", "sas", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Sas.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Sas.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string reason; private string whitelist; public string Reason { get { return reason; } set { reason = value; DictionaryUtil.Add(QueryParameters, "Reason", value); } } public string Whitelist { get { return whitelist; } set { whitelist = value; DictionaryUtil.Add(QueryParameters, "Whitelist", value); } } public override bool CheckShowJsonItemName() { return false; } public override ModifyCreateVulWhitelistResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ModifyCreateVulWhitelistResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
30.071429
134
0.691607
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-sas/Sas/Model/V20181203/ModifyCreateVulWhitelistRequest.cs
2,526
C#
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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 Apache.Ignite.Linq.Impl { using System.Linq; using System.Linq.Expressions; using Apache.Ignite.Core.Cache; /// <summary> /// Fields <see cref="IQueryable{T}"/> implementation for <see cref="ICache{TK,TV}"/>. /// </summary> internal class CacheFieldsQueryable<T> : CacheQueryableBase<T> { /// <summary> /// Initializes a new instance of the <see cref="CacheQueryable{TKey, TValue}"/> class. /// </summary> /// <param name="provider">The provider used to execute the query represented by this queryable /// and to construct new queries.</param> /// <param name="expression">The expression representing the query.</param> public CacheFieldsQueryable(IQueryProvider provider, Expression expression) : base(provider, expression) { // No-op. } } }
40
112
0.688462
[ "CC0-1.0" ]
Diffblue-benchmarks/Gridgain-gridgain
modules/platforms/dotnet/Apache.Ignite.Linq/Impl/CacheFieldsQueryable.cs
1,562
C#
using System; using SolastaCommunityExpansion.Builders; using SolastaCommunityExpansion.Builders.Features; using static SolastaModApi.DatabaseHelper; using static SolastaModApi.DatabaseHelper.CharacterSubclassDefinitions; using static SolastaModApi.DatabaseHelper.ConditionDefinitions; namespace SolastaCommunityExpansion.Subclasses.Fighter { internal class SpellShield : AbstractSubclass { private static Guid SubclassNamespace = new("d4732dc2-c4f9-4a35-a12a-ae2d7858ff74"); private readonly CharacterSubclassDefinition Subclass; internal override FeatureDefinitionSubclassChoice GetSubclassChoiceList() { return FeatureDefinitionSubclassChoices.SubclassChoiceFighterMartialArchetypes; } internal override CharacterSubclassDefinition GetSubclass() { return Subclass; } internal SpellShield() { FeatureDefinitionMagicAffinity magicAffinity = FeatureDefinitionMagicAffinityBuilder .Create("MagicAffinityFighterSpellShield", SubclassNamespace) .SetGuiPresentation(Category.Subclass) .SetConcentrationModifiers(RuleDefinitions.ConcentrationAffinity.Advantage, 0) .SetHandsFullCastingModifiers(true, true, true) .SetCastingModifiers(0, RuleDefinitions.SpellParamsModifierType.None, 0, RuleDefinitions.SpellParamsModifierType.FlatValue, true, false, false) .AddToDB(); FeatureDefinitionCastSpellBuilder spellCasting = FeatureDefinitionCastSpellBuilder .Create("CastSpellSpellShield", SubclassNamespace) .SetGuiPresentation("FighterSpellShieldSpellcasting", Category.Subclass) .SetSpellCastingOrigin(FeatureDefinitionCastSpell.CastingOrigin.Subclass) .SetSpellCastingAbility(AttributeDefinitions.Intelligence) .SetSpellList(SpellListDefinitions.SpellListWizard) .AddRestrictedSchool(SchoolOfMagicDefinitions.SchoolAbjuration) .AddRestrictedSchool(SchoolOfMagicDefinitions.SchoolTransmutation) .AddRestrictedSchool(SchoolOfMagicDefinitions.SchoolNecromancy) .AddRestrictedSchool(SchoolOfMagicDefinitions.SchoolIllusion) .SetSpellKnowledge(RuleDefinitions.SpellKnowledge.Selection) .SetSpellReadyness(RuleDefinitions.SpellReadyness.AllKnown) .SetSlotsRecharge(RuleDefinitions.RechargeRate.LongRest) .SetKnownCantrips(3, 3, FeatureDefinitionCastSpellBuilder.CasterProgression.THIRD_CASTER) .SetKnownSpells(4, 3, FeatureDefinitionCastSpellBuilder.CasterProgression.THIRD_CASTER) .SetSlotsPerLevel(3, FeatureDefinitionCastSpellBuilder.CasterProgression.THIRD_CASTER); FeatureDefinitionSavingThrowAffinity spellShieldResistance = FeatureDefinitionSavingThrowAffinityBuilder .Create("SpellShieldSpellResistance", SubclassNamespace) .SetGuiPresentation("FighterSpellShieldSpellResistance", Category.Subclass) .SetAffinities(RuleDefinitions.CharacterSavingThrowAffinity.Advantage, true, AttributeDefinitions.Strength, AttributeDefinitions.Dexterity, AttributeDefinitions.Constitution, AttributeDefinitions.Wisdom, AttributeDefinitions.Intelligence, AttributeDefinitions.Charisma) .AddToDB(); // or maybe some boost to the spell shield spells? FeatureDefinitionAdditionalAction bonusSpell = FeatureDefinitionAdditionalActionBuilder .Create("SpellShieldAdditionalAction", SubclassNamespace) .SetGuiPresentation(Category.Subclass) .SetActionType(ActionDefinitions.ActionType.Main) .SetRestrictedActions(ActionDefinitions.Id.CastMain) .SetMaxAttacksNumber(-1) .SetTriggerCondition(RuleDefinitions.AdditionalActionTriggerCondition.HasDownedAnEnemy) .AddToDB(); ConditionDefinition deflectionCondition = ConditionDefinitionBuilder .Create("ConditionSpellShieldArcaneDeflection", SubclassNamespace) .SetGuiPresentation(Category.Subclass) .AddFeatures(FeatureDefinitionAttributeModifierBuilder .Create("AttributeSpellShieldArcaneDeflection", SubclassNamespace) .SetModifier(FeatureDefinitionAttributeModifier.AttributeModifierOperation.Additive, AttributeDefinitions.ArmorClass, 3) .SetGuiPresentation("ConditionSpellShieldArcaneDeflection", Category.Subclass, ConditionShielded.GuiPresentation.SpriteReference) .AddToDB()) .SetConditionType(RuleDefinitions.ConditionType.Beneficial) .SetAllowMultipleInstances(false) .SetDuration(RuleDefinitions.DurationType.Round, 1) .AddToDB(); var arcaneDeflection = EffectDescriptionBuilder .Create() .SetTargetingData(RuleDefinitions.Side.Ally, RuleDefinitions.RangeType.Self, 1, RuleDefinitions.TargetType.Self, 1, 0, ActionDefinitions.ItemSelectionType.None) .AddEffectForm(EffectFormBuilder .Create() .CreatedByCharacter() .SetConditionForm(deflectionCondition, ConditionForm.ConditionOperation.Add, true, true) .Build()) .Build(); FeatureDefinitionPower arcaneDeflectionPower = FeatureDefinitionPowerBuilder .Create("PowerSpellShieldArcaneDeflection", SubclassNamespace) .SetGuiPresentation(Category.Subclass, ConditionShielded.GuiPresentation.SpriteReference) .Configure( 0, RuleDefinitions.UsesDetermination.AbilityBonusPlusFixed, AttributeDefinitions.Intelligence, RuleDefinitions.ActivationTime.Reaction, 0, RuleDefinitions.RechargeRate.AtWill, false, false, AttributeDefinitions.Intelligence, arcaneDeflection, false /* unique instance */) .AddToDB(); var actionAffinitySpellShieldRangedDefense = FeatureDefinitionActionAffinityBuilder .Create(FeatureDefinitionActionAffinitys.ActionAffinityTraditionGreenMageLeafScales, "ActionAffinitySpellShieldRangedDefense", SubclassNamespace) .SetGuiPresentation("PowerSpellShieldRangedDeflection", Category.Subclass) .AddToDB(); // Make Spell Shield subclass Subclass = CharacterSubclassDefinitionBuilder .Create("FighterSpellShield", SubclassNamespace) .SetGuiPresentation(Category.Subclass, DomainBattle.GuiPresentation.SpriteReference) .AddFeatureAtLevel(magicAffinity, 3) .AddFeatureAtLevel(spellCasting.AddToDB(), 3) .AddFeatureAtLevel(spellShieldResistance, 7) .AddFeatureAtLevel(bonusSpell, 10) .AddFeatureAtLevel(arcaneDeflectionPower, 15) .AddFeatureAtLevel(actionAffinitySpellShieldRangedDefense, 18).AddToDB(); } } }
58.967742
195
0.697347
[ "MIT" ]
RedOrcaCode/SolastaCommunityExpansion
SolastaCommunityExpansion/Subclasses/Fighter/SpellShield.cs
7,314
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DisasterRecovery { [Flags] public enum TaskExecutionModeFlag { None = 0x00, /// <summary> /// Execute task /// </summary> Execute = 0x01, /// <summary> /// Script task /// </summary> Script = 0x02, /// <summary> /// Execute and script task /// Needed for tasks that will show the script when execution completes /// </summary> ExecuteAndScript = Execute | Script } }
22.181818
101
0.590164
[ "MIT" ]
Bhaskers-Blu-Org2/sqltoolsservice
test/Microsoft.SqlTools.ServiceLayer.IntegrationTests/DisasterRecovery/TaskExecutionModeFlag.cs
734
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Web.Script.Serialization; /** * PubNub 3.0 Real-time Push Cloud API * * @author Stephen Blum * @package pubnub */ namespace PubNubUtils { public class PubNubApi { private string ORIGIN = "pubsub.pubnub.com"; private int LIMIT = 1800; private string PUBLISH_KEY = ""; private string SUBSCRIBE_KEY = ""; private string SECRET_KEY = ""; private bool SSL = false; public string PORIGIN { get { return this.ORIGIN; } set { this.ORIGIN = value; } } public int PLIMIT { get { return this.LIMIT; } set { this.LIMIT = value; } } public string PPUBLISH_KEY { get { return this.PUBLISH_KEY; } set { this.PUBLISH_KEY = value; } } public string PSUBSCRIBE_KEY { get { return this.SUBSCRIBE_KEY; } set { this.SUBSCRIBE_KEY = value; } } public string PSECRET_KEY { get { return this.SECRET_KEY; } set { this.SECRET_KEY = value; } } public bool PSSL { get { return this.SSL; } set { this.SSL = value; } } public delegate bool Procedure(object message); /** * PubNub 3.0 * * Prepare PubNub Class State. * * @param string Publish Key. * @param string Subscribe Key. * @param string Secret Key. * @param bool SSL Enabled. */ public PubNubApi( string publish_key, string subscribe_key, string secret_key, bool ssl_on ) { this.init(publish_key, subscribe_key, secret_key, ssl_on); } /** * PubNub 2.0 Compatibility * * Prepare PubNub Class State. * * @param string Publish Key. * @param string Subscribe Key. */ public PubNubApi( string publish_key, string subscribe_key ) { this.init(publish_key, subscribe_key, "", false); } /** * PubNub 3.0 without SSL * * Prepare PubNub Class State. * * @param string Publish Key. * @param string Subscribe Key. * @param string Secret Key. */ public PubNubApi( string publish_key, string subscribe_key, string secret_key ) { this.init(publish_key, subscribe_key, secret_key, false); } /** * Init * * Prepare PubNub Class State. * * @param string Publish Key. * @param string Subscribe Key. * @param string Secret Key. * @param bool SSL Enabled. */ public void init( string publish_key, string subscribe_key, string secret_key, bool ssl_on ) { this.PUBLISH_KEY = publish_key; this.SUBSCRIBE_KEY = subscribe_key; this.SECRET_KEY = secret_key; this.SSL = ssl_on; // SSL On? if (this.SSL) { this.ORIGIN = "https://" + this.ORIGIN; } else { this.ORIGIN = "http://" + this.ORIGIN; } } /** * History * * Load history from a channel. * * @param String channel name. * @param int limit history count response. * @return ListArray of history. */ public List<object> History(string channel, int limit) { List<string> url = new List<string>(); url.Add("history"); url.Add(this.SUBSCRIBE_KEY); url.Add(channel); url.Add("0"); url.Add(limit.ToString()); return _request(url); } /** * Publish * * Send a message to a channel. * * @param String channel name. * @param List<object> info. * @return bool false on fail. */ public List<object> Publish(string channel, object message) { JavaScriptSerializer serializer = new JavaScriptSerializer(); // Generate String to Sign string signature = "0"; if (this.SECRET_KEY.Length > 0) { StringBuilder string_to_sign = new StringBuilder(); string_to_sign .Append(this.PUBLISH_KEY) .Append('/') .Append(this.SUBSCRIBE_KEY) .Append('/') .Append(this.SECRET_KEY) .Append('/') .Append(channel) .Append('/') .Append(serializer.Serialize(message)); // Sign Message signature = md5(string_to_sign.ToString()); } // Build URL List<string> url = new List<string>(); url.Add("publish"); url.Add(this.PUBLISH_KEY); url.Add(this.SUBSCRIBE_KEY); url.Add(signature); url.Add(channel); url.Add("0"); url.Add(serializer.Serialize(message)); // Return JSONArray return _request(url); } /** * Subscribe * * This function is BLOCKING. * Listen for a message on a channel. * * @param string channel name. * @param Procedure function callback. */ public void Subscribe(string channel, Procedure callback) { this._subscribe(channel, callback, 0); } /** * Subscribe - Private Interface * * @param string channel name. * @param Procedure function callback. * @param string timetoken. */ private void _subscribe( string channel, Procedure callback, object timetoken ) { // Begin Recusive Subscribe try { // Build URL List<string> url = new List<string>(); url.Add("subscribe"); url.Add(this.SUBSCRIBE_KEY); url.Add(channel); url.Add("0"); url.Add(timetoken.ToString()); // Wait for Message List<object> response = _request(url); // Update TimeToken if (response[1].ToString().Length > 0) timetoken = (object)response[1]; // Run user Callback and Reconnect if user permits. foreach (object message in (object[])response[0]) { if (!callback(message)) return; } // Keep listening if Okay. this._subscribe(channel, callback, timetoken); } catch { System.Threading.Thread.Sleep(1000); this._subscribe(channel, callback, timetoken); } } /** * Time * * Timestamp from PubNub Cloud. * * @return object timestamp. */ public object Time() { List<string> url = new List<string>(); url.Add("time"); url.Add("0"); List<object> response = _request(url); return response[0]; } /** * Request URL * * @param List<string> request of url directories. * @return List<object> from JSON response. */ private List<object> _request(List<string> url_components) { string temp = null; int count = 0; byte[] buf = new byte[8192]; StringBuilder url = new StringBuilder(); StringBuilder sb = new StringBuilder(); JavaScriptSerializer serializer = new JavaScriptSerializer(); // Add Origin To The Request url.Append(this.ORIGIN); // Generate URL with UTF-8 Encoding foreach (string url_bit in url_components) { url.Append("/"); url.Append(_encodeURIcomponent(url_bit)); } // Fail if string too long if (url.Length > this.LIMIT) { List<object> too_long = new List<object>(); too_long.Add(0); too_long.Add("Message Too Long."); return too_long; } // Create Request HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url.ToString()); // Set Timeout request.Timeout = 200000; request.ReadWriteTimeout = 200000; // Receive Response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStream = response.GetResponseStream(); // Read do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { temp = Encoding.UTF8.GetString(buf, 0, count); sb.Append(temp); } } while (count > 0); // Parse Response string message = sb.ToString(); return serializer.Deserialize<List<object>>(message); } private string _encodeURIcomponent(string s) { StringBuilder o = new StringBuilder(); foreach (char ch in s.ToCharArray()) { if (isUnsafe(ch)) { o.Append('%'); o.Append(toHex(ch / 16)); o.Append(toHex(ch % 16)); } else o.Append(ch); } return o.ToString(); } private char toHex(int ch) { return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10); } private bool isUnsafe(char ch) { return " ~`!@#$%^&*()+=[]\\{}|;':\",./<>?".IndexOf(ch) >= 0; } private static string md5(string text) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] data = Encoding.Default.GetBytes(text); byte[] hash = md5.ComputeHash(data); string hexaHash = ""; foreach (byte b in hash) hexaHash += String.Format("{0:x2}", b); return hexaHash; } } }
26.251716
78
0.448222
[ "MIT" ]
vic-alexiev/CloudServices
CloudServices/PubNubUtils/PubNubApi.cs
11,474
C#
namespace lindexi.MVVM.Framework.ViewModel { /// <summary> /// 表示接口继承 /// </summary> public interface IViewModel { } }
13.181818
43
0.572414
[ "MIT" ]
lindexi/UWP
uwp/src/Framework/Framework/ViewModel/IViewModel.cs
159
C#
using System; using System.Net; using System.IO; using System.Linq; using System.Text; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; namespace Rebilly { public class RebillyAddressInfo { /// <summary> /// customer's first name /// </summary> public string firstName = null; /// <summary> /// customer's last name /// </summary> public string lastName = null; /// <summary> /// customer's address /// </summary> public string address = null; /// <summary> /// customer's address /// </summary> public string address2 = null; /// <summary> /// customer's city /// </summary> public string city = null; /// <summary> /// customer's region /// </summary> public string region = null; /// <summary> /// customer's country /// </summary> public string country = null; /// <summary> /// customer's phone number /// </summary> public string phoneNumber = null; /// <summary> /// customer's postal code /// </summary> public string postalCode = null; } }
24.788462
41
0.524438
[ "MIT" ]
dara123/rebilly-dotnet-client
Library/Rebilly/RebillyAddressInfo.cs
1,291
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using ReactIdentity.Infrastructure.Models; namespace ReactIdentity.Areas.Identity.Pages.Account { [AllowAnonymous] public class LoginWithRecoveryCodeModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<LoginWithRecoveryCodeModel> _logger; public LoginWithRecoveryCodeModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginWithRecoveryCodeModel> logger) { _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public string ReturnUrl { get; set; } public class InputModel { [BindProperty] [Required] [DataType(DataType.Text)] [Display(Name = "Recovery Code")] public string RecoveryCode { get; set; } } public async Task<IActionResult> OnGetAsync(string returnUrl = null) { // Ensure the user has gone through the username & password screen first var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } ReturnUrl = returnUrl; return Page(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return Page(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty); var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id); return LocalRedirect(returnUrl ?? Url.Content("~/")); } if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return RedirectToPage("./Lockout"); } else { _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id); ModelState.AddModelError(string.Empty, "Invalid recovery code entered."); return Page(); } } } }
34.802198
132
0.592359
[ "MIT" ]
aurlaw/ReactIdentity
ReactIdentity/Areas/Identity/Pages/Account/LoginWithRecoveryCode.cshtml.cs
3,167
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="AddDisksProviderSpecificInput" /> /// </summary> public partial class AddDisksProviderSpecificInputTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="AddDisksProviderSpecificInput" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="AddDisksProviderSpecificInput" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="AddDisksProviderSpecificInput" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="AddDisksProviderSpecificInput" />.</param> /// <returns> /// an instance of <see cref="AddDisksProviderSpecificInput" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IAddDisksProviderSpecificInput ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IAddDisksProviderSpecificInput).IsAssignableFrom(type)) { return sourceValue; } try { return AddDisksProviderSpecificInput.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return AddDisksProviderSpecificInput.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return AddDisksProviderSpecificInput.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.422535
245
0.590408
[ "MIT" ]
AverageDesigner/azure-powershell
src/Migrate/generated/api/Models/Api20210210/AddDisksProviderSpecificInput.TypeConverter.cs
7,303
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace Amazon.PowerShell.Cmdlets.IAM { /// <summary> /// Deletes the specified inline policy that is embedded in the specified IAM user. /// /// /// <para> /// A user can also have managed policies attached to it. To detach a managed policy from /// a user, use <a>DetachUserPolicy</a>. For more information about policies, refer to /// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html">Managed /// policies and inline policies</a> in the <i>IAM User Guide</i>. /// </para> /// </summary> [Cmdlet("Remove", "IAMUserPolicy", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType("None")] [AWSCmdlet("Calls the AWS Identity and Access Management DeleteUserPolicy API operation.", Operation = new[] {"DeleteUserPolicy"}, SelectReturnType = typeof(Amazon.IdentityManagement.Model.DeleteUserPolicyResponse))] [AWSCmdletOutput("None or Amazon.IdentityManagement.Model.DeleteUserPolicyResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.IdentityManagement.Model.DeleteUserPolicyResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RemoveIAMUserPolicyCmdlet : AmazonIdentityManagementServiceClientCmdlet, IExecutor { #region Parameter PolicyName /// <summary> /// <para> /// <para>The name identifying the policy document to delete.</para><para>This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex /// pattern</a>) a string of characters consisting of upper and lowercase alphanumeric /// characters with no spaces. You can also include any of the following characters: _+=,.@-</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String PolicyName { get; set; } #endregion #region Parameter UserName /// <summary> /// <para> /// <para>The name (friendly name, not ARN) identifying the user that the policy is embedded /// in.</para><para>This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex /// pattern</a>) a string of characters consisting of upper and lowercase alphanumeric /// characters with no spaces. You can also include any of the following characters: _+=,.@-</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String UserName { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.IdentityManagement.Model.DeleteUserPolicyResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the UserName parameter. /// The -PassThru parameter is deprecated, use -Select '^UserName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^UserName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.PolicyName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-IAMUserPolicy (DeleteUserPolicy)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.IdentityManagement.Model.DeleteUserPolicyResponse, RemoveIAMUserPolicyCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.UserName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.PolicyName = this.PolicyName; #if MODULAR if (this.PolicyName == null && ParameterWasBound(nameof(this.PolicyName))) { WriteWarning("You are passing $null as a value for parameter PolicyName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.UserName = this.UserName; #if MODULAR if (this.UserName == null && ParameterWasBound(nameof(this.UserName))) { WriteWarning("You are passing $null as a value for parameter UserName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.IdentityManagement.Model.DeleteUserPolicyRequest(); if (cmdletContext.PolicyName != null) { request.PolicyName = cmdletContext.PolicyName; } if (cmdletContext.UserName != null) { request.UserName = cmdletContext.UserName; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.IdentityManagement.Model.DeleteUserPolicyResponse CallAWSServiceOperation(IAmazonIdentityManagementService client, Amazon.IdentityManagement.Model.DeleteUserPolicyRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Identity and Access Management", "DeleteUserPolicy"); try { #if DESKTOP return client.DeleteUserPolicy(request); #elif CORECLR return client.DeleteUserPolicyAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String PolicyName { get; set; } public System.String UserName { get; set; } public System.Func<Amazon.IdentityManagement.Model.DeleteUserPolicyResponse, RemoveIAMUserPolicyCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
47.178988
281
0.620371
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/IdentityManagement/Basic/Remove-IAMUserPolicy-Cmdlet.cs
12,125
C#
namespace Constants; public class SharedConstant { public const string CorsPolicyNane = "CorsPolicy"; }
16.571429
55
0.724138
[ "MIT" ]
pragmatic-applications/MAK.Lib.Core
MAK.Lib.Core/Constants/SharedConstant.cs
118
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace fa19projectgroup16.Migrations { public partial class transactionNav : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
19.055556
71
0.6793
[ "MIT" ]
jdalamo/K-Project
Migrations/20191130033410_transactionNav.cs
345
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Mvc.Core; using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Mvc { public class DefaultControllerFactory : IControllerFactory { private readonly ITypeActivator _activator; private readonly IServiceProvider _serviceProvider; public DefaultControllerFactory(IServiceProvider serviceProvider, ITypeActivator activator) { _serviceProvider = serviceProvider; _activator = activator; } public object CreateController(ActionContext actionContext) { var actionDescriptor = actionContext.ActionDescriptor as ReflectedActionDescriptor; if (actionDescriptor == null) { throw new ArgumentException( Resources.FormatDefaultControllerFactory_ActionDescriptorMustBeReflected( typeof(ReflectedActionDescriptor)), "actionContext"); } var controller = _activator.CreateInstance(_serviceProvider, actionDescriptor.ControllerDescriptor.ControllerTypeInfo.AsType()); InitializeController(controller, actionContext); return controller; } public void ReleaseController(object controller) { var disposableController = controller as IDisposable; if (disposableController != null) { disposableController.Dispose(); } } private void InitializeController(object controller, ActionContext actionContext) { Injector.InjectProperty(controller, "ActionContext", actionContext); var viewData = new ViewDataDictionary( _serviceProvider.GetService<IModelMetadataProvider>(), actionContext.ModelState); Injector.InjectProperty(controller, "ViewData", viewData); var urlHelper = _serviceProvider.GetService<IUrlHelper>(); Injector.InjectProperty(controller, "Url", urlHelper); Injector.CallInitializer(controller, _serviceProvider); } } }
36.060606
140
0.666387
[ "Apache-2.0" ]
loxadim/Mvc
src/Microsoft.AspNet.Mvc.Core/DefaultControllerFactory.cs
2,380
C#
namespace helpDesk { partial class Sobre { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Sobre)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Location = new System.Drawing.Point(202, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(333, 76); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Arial Black", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.Black; this.label2.Location = new System.Drawing.Point(274, 33); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(57, 27); this.label2.TabIndex = 1; this.label2.Text = "1.00"; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Arial Black", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(6, 33); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(276, 27); this.label1.TabIndex = 0; this.label1.Text = "VERSÃO DO SOFTWARE: "; // // groupBox2 // this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Location = new System.Drawing.Point(12, 117); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(776, 279); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Arial Black", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.Color.Black; this.label4.Location = new System.Drawing.Point(7, 74); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(724, 184); this.label4.TabIndex = 1; this.label4.Text = resources.GetString("label4.Text"); // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Arial Black", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.Black; this.label3.Location = new System.Drawing.Point(253, 16); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(246, 27); this.label3.TabIndex = 0; this.label3.Text = "SOBRE O SOFTWARE :"; // // Sobre // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.LightSkyBlue; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "Sobre"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "SOBRE"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; } }
45.136691
157
0.584794
[ "Apache-2.0" ]
jmvicente1992/HelpMais
helpDesk/helpDesk/Sobre.Designer.cs
6,277
C#
using System; using System.Windows; namespace PPDEditorCommon.Dialog { /// <summary> /// SettingWindow.xaml の相互作用ロジック /// </summary> public partial class SettingWindow : Window { public SettingWindow() { InitializeComponent(); } protected override void OnSourceInitialized(EventArgs e) { IconHelper.RemoveIcon(this); } private void OkButton_Click(object sender, RoutedEventArgs e) { DialogResult = true; this.Close(); } private void CancelButton_Click(object sender, RoutedEventArgs e) { DialogResult = false; this.Close(); } } }
21.382353
73
0.562586
[ "Apache-2.0" ]
KHCmaster/PPD
Win/PPDEditorCommon/Dialog/SettingWindow.xaml.cs
747
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Hearthstone_Sim_Parser { public class Parser { // TODO /// Add the final parser /* * Function: ReadFromCSV * Input: Set to find, path of the file to read from * Output: String array of all cards of a given set * Remarks: Being given the card set that one wishes to have all the cards for, and the path to read from, the function gathers all lines of card names from a given set */ public static string[] ReadFromCSV(string set, string path) { int lineAmount = FindLineAmount(set, path); // lineAmount determines how many lines is necessary to have in the array, aka amount of cards in the given set string[] CSVArray = new string[lineAmount]; // array is initialised based on amount of lines found CSVArray = PopulateCSVArray(CSVArray, set, path); // array is populated return CSVArray; } /* * Function: FindLineAmount * Input: The set (as string) that is looked for in the file, the path (as string) to the file * Output: An integer of amount of lines to write * Remarks: None */ public static int FindLineAmount(string set, string path) { int lineAmount = 1; // This variable is set to 1 in order to count the header at the top of the document using (StreamReader sr = new StreamReader(path)) // Reads the file given in path { string line; // String variable used to store the read line string cardTrue = "True"; // String to check for collectible flag of the card while ((line = sr.ReadLine()) != null) // Readline() goes to the next line of the file after being called. While loop breaks when ReadLine() returns null { // This if statement is true if the following is true: // The card is from the right set (line contains set) // The card is a collectible card (line contains cardTrue = "True") if (line.Contains(set) && line.Contains(cardTrue)) { lineAmount++; } } } return lineAmount; } /* * Function: PopulateCSVArray * Input: The string array to write to, the set (as string) that is looked for in the file, the path (as string) to the file * Output: The array containing the correct lines from the CSV file * Remarks: None */ public static string[] PopulateCSVArray(string[] CSVArray, string set, string path) { using (StreamReader sr = new StreamReader(path)) // Reads the file given in path { CSVArray[0] = sr.ReadLine(); // First line of the file is the header, which should be included for neatness. StreamReader object remembers how many lines has been read, going down one line with every ReadLine() int arrayIndex = 1; // Integer to put a new line in a new index. Set to 1 because of the header string line; // String variable used to store the read line string cardTrue = "True"; // String to check for collectible flag of the card while ((line = sr.ReadLine()) != null) // Readline() goes to the next line of the file after being called. While loop breaks when ReadLine() returns null { // This if statement is true if the following is true: // The card is from the right set (line contains set) // The card is a collectible card (line contains cardTrue = "True") if (line.Contains(set) && line.Contains(cardTrue)) { Console.Write(line); // Written for clarity purposes CSVArray[arrayIndex] = line; // Line is added to the array Console.WriteLine(" arrayIndex of line: " + arrayIndex); // Written for clarity purposes arrayIndex++; // Increments arrayIndex so the next line to add will be on a new index } } } return CSVArray; } } }
45.326531
226
0.575416
[ "MIT" ]
gaarden2000/Hearthstone_Sim_Parser
Parser.cs
4,444
C#
using System; using System.Collections.Generic; using System.Linq; namespace MsSystem.Sys.Schedule.Infrastructure { /// <summary> /// 任务管理类 /// </summary> public class ScheduleManage { /// <summary> /// 初始化 /// </summary> public static readonly ScheduleManage Instance; static ScheduleManage() { Instance = new ScheduleManage(); } /// <summary> /// 任务计划列表 /// </summary> public static List<ScheduleEntity> ScheduleList = new List<ScheduleEntity>(); /// <summary> /// 任务调度详情列表 /// </summary> public static IList<ScheduleDetailsEntity> ScheduleDetailList = new List<ScheduleDetailsEntity>(); /// <summary> /// 添加任务列表 /// </summary> /// <param name="scheduleEntity"></param> public virtual void AddScheduleList(ScheduleEntity scheduleEntity) { try { ScheduleList.Remove(scheduleEntity); ScheduleList.Add(scheduleEntity); } catch (Exception ex) { Console.Out.WriteLineAsync("添加任务列表失败:" + ex.Message); throw; } } /// <summary> /// 获取任务实例 /// </summary> /// <param name="jobGroup">任务分组</param> /// <param name="jobName">任务名称</param> /// <returns></returns> public virtual ScheduleEntity GetScheduleModel(string jobGroup, string jobName) { return ScheduleList.Where(w => w.JobName == jobName && w.JobGroup == jobGroup).FirstOrDefault(); } /// <summary> /// 移除任务 /// </summary> /// <param name="jobGroup"></param> /// <param name="jobName"></param> /// <returns></returns> public virtual ScheduleEntity RemoveScheduleModel(string jobGroup, string jobName) { ScheduleEntity scheduleModel = this.GetScheduleModel(jobGroup, jobName); if (scheduleModel != null) { ScheduleList.Remove(scheduleModel); } return scheduleModel; } /// <summary> /// 修改任务执行状态 /// </summary> /// <param name="entity"></param> public virtual void UpdateScheduleRunStatus(ScheduleEntity entity) { ScheduleList.Where(w => w.JobName == entity.JobName && w.JobGroup == entity.JobGroup).FirstOrDefault().RunStatus = entity.RunStatus; } /// <summary> /// 添加任务调度详情 /// </summary> /// <param name="detail"></param> public virtual void AddScheduleDetails(ScheduleDetailsEntity detail) { ScheduleDetailList.Add(detail); } /// <summary> /// 修改下一次执行时间 /// </summary> /// <param name="entity"></param> public virtual void UpdateScheduleNextTime(ScheduleEntity entity) { ScheduleList.Where(w => w.JobName == entity.JobName && w.JobGroup == entity.JobGroup).FirstOrDefault().NextTime = entity.NextTime; } /// <summary> /// 修改任务状态 /// </summary> /// <param name="entity"></param> public virtual void UpdateScheduleStatus(ScheduleEntity entity) { ScheduleList.Where(w => w.JobName == entity.JobName && w.JobGroup == entity.JobGroup).FirstOrDefault().Status = entity.Status; } } }
32.849057
144
0.544515
[ "MIT" ]
SpoonySeedLSP/BPM-ServiceAndWebApps
src/Services/System/MsSystem.Sys.Schedule.Infrastructure/ScheduleManage.cs
3,656
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DentedPixel; public class BAR : MonoBehaviour { // Start is called before the first frame update public GameObject bar; public int time; void Start() { AnimateBar(); } // Update is called once per frame void Update() { } public void AnimateBar() { LeanTween.scaleX(bar, 1, time); } }
17.92
52
0.620536
[ "MIT" ]
RageKingBanana/OOPproject
FINQUIZGAME/Assets/Scripts/Mono/BAR.cs
450
C#
namespace School { using Record; using System; using System.Collections.Generic; public class Startup { public static void Main() { var nakovDisciplines = new List<Disciplines> { new Disciplines(DisciplineName.Math, 10, 10), new Disciplines(DisciplineName.Informatics, 20, 20) }; var kiroDisciplines = new List<Disciplines> { new Disciplines(DisciplineName.History, 8, 8), new Disciplines(DisciplineName.Geography, 6, 6) }; var studentsFirstClass = new List<Student> { new Student("Pavel", "Popandov"), new Student("Angel", "Demirev"), new Student("Meri", "Chleri") }; var studentsSecondClass = new List<Student> { new Student("Ganka", "Peicheva"), new Student("Eskenazi", "Evtimov"), new Student("Grigor", "Markov") }; var teachers = new List<Teacher> { new Teacher("Sun", "Tzu", nakovDisciplines), new Teacher("Dalai", "Lama", kiroDisciplines) }; var firstClass = new SchoolClass(teachers, studentsFirstClass); var secondClass = new SchoolClass(teachers, studentsSecondClass); var school = new School(new List<SchoolClass> { firstClass, secondClass }); Console.WriteLine(school); } } }
30.666667
87
0.521739
[ "MIT" ]
DragomirPetrov/TelerikAcademy
C #/C# OOP/04.OOP-Principles-Part-1/01.SchoolClasses/Startup.cs
1,566
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("willzone.ExpressionHelperTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("willzone.ExpressionHelperTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7eaf4ae6-01f8-4c8a-954e-c6849cf39e1a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.750174
[ "Apache-2.0" ]
BorisWilhelms/willezone.ExpressionHelper
src/Willezone.ExpressionHelperTests/Properties/AssemblyInfo.cs
1,436
C#
using UnityEngine; // Contains list of all screens and button behaviours public class UIHandler : MonoBehaviour { // Singleton public static UIHandler Instance { get; private set; } // UI screen objects [Header("Aim Cursor")] [SerializeField] public Texture2D AimCursor; [Header("Screens")] [SerializeField] public UIScreen[] UIScreens; [SerializeField] public UIScreen DefaultScreen; [Header("PopUps")] [SerializeField] public UIPopUp[] UIPopUps; [Header("Error Text")] [SerializeField] public GameObject ErrorText; [Header("Menu Background")] [SerializeField] public GameObject MenuBackground; [Header("NPC UI Prefab")] [SerializeField] public GameObject NPCUIPrefab; [Header("Ship Models")] [SerializeField] public GameObject[] ShipModels; // Start is called before the first frame update private void Start() { Instance = this; } // Change error text public void ChangeErrorText(string newErrorText) { UIController.ChangeErrorText(newErrorText); } // Get selected toggle public void GetShipSelectToggle() { UIController.GetShipSelectToggle(); } // Movement style toggle public void MovementStyleToggle() { UIController.GetMovementStyleToggle(); } // Input type toggle public void InputTypeToggle() { UIController.GetInputTypeToggle(); } // Rebind keybind KBM public void RebindKeybindKBM(string inputToRebind) { PlayerInput.SetupRebind(PlayerInput.InputModeEnum.KeyboardAndMouse, inputToRebind); } // Rebind keybind controller public void RebindKeybindController(string inputToRebind) { PlayerInput.SetupRebind(PlayerInput.InputModeEnum.Controller, inputToRebind); } // Set bindings to default public void SetDefaultBindings() { PlayerInput.SetDefaultBindings(); UIController.ChangeErrorText($@"Input bindings set to defaults."); } // Save settings to file public void SaveSettingsToFile() { FileOps.WriteSettingsToFile(); } // Change game state public void ChangeGameState(int newGameState) { // int 0: menus, 1: playing, 2: paused switch(newGameState) { case 0: { GameController.ChangeGameState(GameController.GameState.Menus); break; } case 1: { GameController.ChangeGameState(GameController.GameState.Playing); break; } case 2: { GameController.ChangeGameState(GameController.GameState.Paused); break; } default: { Debug.Log($@"Invalid Game State: {newGameState}"); Logger.Log($@"Invalid Game State: {newGameState}"); break; } } } // Change screen public void ChangeScreen(UIScreen newScreen) { UIController.ChangeScreen(newScreen); } // Back public void Back() { UIController.Back(); } // Open PopUp public void OpenPopUp(UIPopUp popUpToOpen) { UIController.OpenPopUp(popUpToOpen); } // Close PopUp public void ClosePopUp(UIPopUp popUpToClose) { UIController.ClosePopUp(popUpToClose); } // Close all PopUps public void CloseAllPopUps() { UIController.CloseAllPopUps(); } // Clear all public void ClearAll() { GameController.ClearAll(); } // Start game public void StartNewGame() { GameController.StartNewGame(); } // Quit game public void QuitGame() { Application.Quit(); } }
22.994048
91
0.603158
[ "MIT" ]
AliTsuki/Leviathan
Assets/Scripts/UI/UIHandler.cs
3,865
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Common.DataStructures; using Common.Monads; namespace Common.Lifetimes { public static class LifetimeEx { public static LifetimeDefinition DefineNested(this Lifetime lifetime) { return lifetime.IsAlive ? new LifetimeDefinition(lifetime) : LifetimeDefinition.Terminated; } public static SequentialLifetimes DefineNestedSequential(this Lifetime lifetime) { return lifetime.IsAlive ? new SequentialLifetimes(lifetime) : SequentialLifetimes.Terminated; } public static T WithLifetime<T>(this T value, Lifetime lifetime) where T : IDisposable { lifetime.OnTermination(value); return value; } public static LifetimeDefinition DefineIntersect(this Lifetime lifetime, Lifetime other) { if (lifetime.IsNotAlive || other.IsNotAlive) return LifetimeDefinition.Terminated; var def = new LifetimeDefinition(); lifetime.Def?.AttachOrTerminate(def); other.Def?.AttachOrTerminate(def); return def; } public static Lifetime Intersect(this Lifetime lifetime, Lifetime other) { if (lifetime.IsEternal) return other; if (other.IsEternal) return lifetime; return lifetime.DefineIntersect(other).Lifetime; } public static bool TryExecute(this Lifetime lifetime, Action action) { using var cookie = lifetime.UsingExecuteIfAlive(); if (!cookie.Success) return false; action(); return true; } public static Result<T> TryExecute<T>(this Lifetime lifetime, Func<T> action) { using var cookie = lifetime.UsingExecuteIfAlive(); return cookie.Success ? Result.Create(action()) : Result<T>.Unsuccess; } public static void Execute(this Lifetime lifetime, Action action) { if (lifetime.TryExecute(action)) return; throw new LifetimeCanceledException(lifetime); } [return: MaybeNull] public static T Execute<T>(this Lifetime lifetime, Func<T> action) { var result = lifetime.TryExecute(action); return result.Success ? result.Value : throw new LifetimeCanceledException(lifetime); } public static Result<T> TryBracket<T>(this Lifetime lifetime, Func<T> open, Action<T> close) { T result; using (var cookie = lifetime.UsingExecuteIfAlive()) { if (!cookie.Success) return Result<T>.Unsuccess; result = open(); if (lifetime.TryOnTermination(() => close(result))) return Result.Create(result); } close(result); return Result.Create(result); } public static bool TryBracket(this Lifetime lifetime, Action open, Action close) { using (var cookie = lifetime.UsingExecuteIfAlive()) { if (!cookie.Success) return false; open(); if (lifetime.TryOnTermination(close)) return true; } close(); return true; } public static T Bracket<T>(this Lifetime lifetime, Func<T> open, Action<T> close) { var result = lifetime.TryBracket(open, close); return result.Success ? result.Value : throw new LifetimeCanceledException(lifetime); } public static void Bracket(this Lifetime lifetime, Action open, Action close) { if (!lifetime.TryBracket(open, close)) throw new LifetimeCanceledException(lifetime); } public static void OnTermination(this Lifetime lifetime, Action action) { if (!lifetime.TryOnTermination(action)) throw new LifetimeCanceledException(lifetime); } public static void OnTermination(this Lifetime lifetime, IDisposable disposable) { if (!lifetime.TryOnTermination(disposable)) throw new LifetimeCanceledException(lifetime); } public static void ThrowIfNotAlive(this Lifetime lifetime) { if (lifetime.IsNotAlive) throw new LifetimeCanceledException(lifetime); } public static LifetimeDefinition.ExecuteIfAliveCookie UsingExecuteIfAliveOrThrow(this Lifetime lifetime) { var cookie = lifetime.UsingExecuteIfAlive(); if (!cookie.Success) throw new LifetimeCanceledException(lifetime); // no need to dispose if success is false // todo add tests for this case return cookie; } public static void KeepAlive(this Lifetime lifetime, object obj) => lifetime.OnTermination(() => GC.KeepAlive(obj)); public static bool TryKeepAlive(this Lifetime lifetime, object obj) => lifetime.TryOnTermination(() => GC.KeepAlive(obj)); public static bool AddOrTerminate(this Lifetime lifetime, Action action) { if (lifetime.TryOnTermination(action)) return true; action(); return false; } public static TaskCompletionSource<T> CreateTaskCompletionSource<T>(this Lifetime lifetime, TaskCreationOptions options = TaskCreationOptions.None) { var tcs = new TaskCompletionSource<T>(options); if (lifetime.IsEternal) return tcs; if (lifetime.IsAlive) return tcs.SynchronizeWith(lifetime.DefineNested()); tcs.TrySetCanceled(lifetime); return tcs; } public static TaskCompletionSource<T> SynchronizeWith<T>(this TaskCompletionSource<T> tcs, LifetimeDefinition def) { if (def.Lifetime.AddOrTerminate(() => tcs.TrySetCanceled(def.Lifetime))) tcs.Task.ContinueWith(_ => def.Terminate()); return tcs; } public static void UsingNested(this Lifetime lifetime, Action<Lifetime> action) { using var def = lifetime.DefineNested(); action(def.Lifetime); } public static T UsingNested<T>(this Lifetime lifetime, Func<Lifetime, T> action) { using var def = lifetime.DefineNested(); return action(def.Lifetime); } public static async Task UsingNestedAsync(this Lifetime lifetime, Func<Lifetime, Task> action) { using var def = lifetime.DefineNested(); await action(def.Lifetime); } public static async Task<T> UsingNestedAsync<T>(this Lifetime lifetime, Func<Lifetime, Task<T>> action) { using var def = lifetime.DefineNested(); return await action(def.Lifetime); } } }
31.661616
151
0.680013
[ "Apache-2.0" ]
Iliya-usov/DotNetUtility
Common/Lifetimes/LifetimeEx.cs
6,269
C#
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using Moq; using Neo4j.Driver.Internal.Connector; using Neo4j.Driver.Internal.Routing; using Neo4j.Driver; using Neo4j.Driver.Internal; using Xunit; using static Neo4j.Driver.Tests.Routing.RoutingTableManagerTests; namespace Neo4j.Driver.Tests.Routing { public class LoadBalancerTests { public class ClusterErrorHandlerTests { public class OnConnectionErrorMethod { [Fact] public async Task ShouldRemoveFromLoadBalancer() { var clusterPoolMock = new Mock<IClusterConnectionPool>(); var routingTableMock = new Mock<IRoutingTable>(); var uri = new Uri("https://neo4j.com"); var routingTableManagerMock = new Mock<IRoutingTableManager>(); routingTableManagerMock .Setup(x => x.EnsureRoutingTableForModeAsync(AccessMode.Read, null, null, Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var loadBalancer = new LoadBalancer(clusterPoolMock.Object, routingTableManagerMock.Object); await loadBalancer.OnConnectionErrorAsync(uri, null, new ClientException()); clusterPoolMock.Verify(x => x.DeactivateAsync(uri), Times.Once); routingTableManagerMock.Verify(x => x.ForgetServer(uri, null), Times.Once); routingTableManagerMock.Verify(x => x.ForgetWriter(uri, null), Times.Never); } } public class OnWriteErrorMethod { [Fact] public void ShouldRemoveWriterFromRoutingTable() { var clusterPoolMock = new Mock<IClusterConnectionPool>(); var routingTableMock = new Mock<IRoutingTable>(); var uri = new Uri("https://neo4j.com"); var routingTableManagerMock = new Mock<IRoutingTableManager>(); routingTableManagerMock .Setup(x => x.EnsureRoutingTableForModeAsync(AccessMode.Write, null, null, Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var loadBalancer = new LoadBalancer(clusterPoolMock.Object, routingTableManagerMock.Object); loadBalancer.OnWriteError(uri, null); clusterPoolMock.Verify(x => x.DeactivateAsync(uri), Times.Never); routingTableManagerMock.Verify(x => x.ForgetServer(uri, null), Times.Never); routingTableManagerMock.Verify(x => x.ForgetWriter(uri, null), Times.Once); } } } public class AcquireMethod { [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public async Task ShouldThrowSessionExpiredExceptionIfNoServerAvailable(AccessMode mode) { // Given var mock = new Mock<IRoutingTableManager>(); mock.Setup(x => x.EnsureRoutingTableForModeAsync(mode, null, null, Bookmark.Empty)) .ReturnsAsync(NewMockedRoutingTable(mode, null, string.Empty).Object); var balancer = new LoadBalancer(null, mock.Object); // When var error = await Record.ExceptionAsync(() => balancer.AcquireAsync(mode, null, null, Bookmark.Empty)); // Then error.Should().BeOfType<SessionExpiredException>(); error.Message.Should().Contain("Failed to connect to any"); } [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public async Task ShouldReturnConnectionWithCorrectMode(AccessMode mode) { // Given var uri = new Uri("neo4j://123:456"); var mock = new Mock<IRoutingTableManager>(); var routingTableMock = NewMockedRoutingTable(mode, uri, string.Empty); mock.Setup(x => x.EnsureRoutingTableForModeAsync(mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var clusterPoolMock = new Mock<IClusterConnectionPool>(); var mockedConn = new Mock<IConnection>(); mockedConn.Setup(x => x.Server.Address).Returns(uri.ToString); mockedConn.Setup(x => x.Mode).Returns(mode); var conn = mockedConn.Object; clusterPoolMock.Setup(x => x.AcquireAsync(uri, mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)).ReturnsAsync(conn); var balancer = new LoadBalancer(clusterPoolMock.Object, mock.Object); // When var acquiredConn = await balancer.AcquireAsync(mode, null, null, Bookmark.Empty); // Then acquiredConn.Server.Address.Should().Be(uri.ToString()); } [Theory] [InlineData("OriginalDB", "AliasDB", "AliasDB")] [InlineData("OriginalDB", "OriginalDB", "OriginalDB")] [InlineData("", "AliasDB", "AliasDB")] [InlineData(null, "AliasDB", "AliasDB")] public async Task ShouldReturnConnectionWithDBFromRoutingTable(string dbName, string aliasDbName, string desiredResult) { AccessMode mode = AccessMode.Read; // Given var uri = new Uri("neo4j://123:456"); var mockManager = new Mock<IRoutingTableManager>(); var routingTableMock = NewMockedRoutingTable(mode, uri, aliasDbName); mockManager.Setup(x => x.EnsureRoutingTableForModeAsync(mode, dbName, null, Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var clusterPoolMock = new Mock<IClusterConnectionPool>(); var mockedConn = new Mock<IConnection>(); mockedConn.Setup(x => x.Server.Address).Returns(uri.ToString); mockedConn.Setup(x => x.Mode).Returns(mode); mockedConn.Setup(x => x.Database).Returns(aliasDbName); clusterPoolMock.Setup(x => x.AcquireAsync(uri, mode, aliasDbName, null, Bookmark.Empty)).ReturnsAsync(mockedConn.Object); var balancer = new LoadBalancer(clusterPoolMock.Object, mockManager.Object); // When var acquiredConn = await balancer.AcquireAsync(mode, dbName, null, Bookmark.Empty); // Then acquiredConn.Database.Should().Be(desiredResult); } [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public void ShouldForgetServerWhenFailedToEstablishConn(AccessMode mode) { // Given var uri = new Uri("neo4j://123:456"); var routingTableMock = NewMockedRoutingTable(mode, uri, string.Empty); var mock = new Mock<IRoutingTableManager>(); mock.Setup(x => x.EnsureRoutingTableForModeAsync(mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); mock.Setup(x => x.ForgetServer(It.IsAny<Uri>(), It.IsAny<string>())) .Callback((Uri u, string database) => routingTableMock.Object.Remove(u)); mock.Setup(x => x.ForgetWriter(It.IsAny<Uri>(), It.IsAny<string>())) .Callback((Uri u, string database) => routingTableMock.Object.RemoveWriter(u)); var clusterConnPoolMock = new Mock<IClusterConnectionPool>(); clusterConnPoolMock.Setup(x => x.AcquireAsync(uri, mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .Returns(Task.FromException<IConnection>(new ServiceUnavailableException("failed init"))); var balancer = new LoadBalancer(clusterConnPoolMock.Object, mock.Object); // When & Then balancer.Awaiting(b => b.AcquireAsync(mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)).Should() .Throw<SessionExpiredException>().WithMessage("Failed to connect to any*"); // should be removed routingTableMock.Verify(m => m.Remove(uri), Times.Once); clusterConnPoolMock.Verify(m => m.DeactivateAsync(uri), Times.Once); } [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public async Task ShouldThrowErrorDirectlyIfSecurityError(AccessMode mode) { // Given var uri = new Uri("neo4j://123:456"); var routingTableMock = NewMockedRoutingTable(mode, uri, string.Empty); var mock = new Mock<IRoutingTableManager>(); mock.Setup(x => x.EnsureRoutingTableForModeAsync(mode, null, null, Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var clusterConnPoolMock = new Mock<IClusterConnectionPool>(); clusterConnPoolMock.Setup(x => x.AcquireAsync(uri, mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .Returns(Task.FromException<IConnection>( new SecurityException("Failed to establish ssl connection with the server"))); var balancer = new LoadBalancer(clusterConnPoolMock.Object, mock.Object); // When var error = await Record.ExceptionAsync(() => balancer.AcquireAsync(mode, null, null, Bookmark.Empty)); // Then error.Should().BeOfType<SecurityException>(); error.Message.Should().Contain("ssl connection with the server"); // while the server is not removed routingTableMock.Verify(m => m.Remove(uri), Times.Never); clusterConnPoolMock.Verify(m => m.DeactivateAsync(uri), Times.Never); } [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public void ShouldThrowErrorDirectlyIfProtocolError(AccessMode mode) { // Given var uri = new Uri("neo4j://123:456"); var routingTableMock = NewMockedRoutingTable(mode, uri, string.Empty); var mock = new Mock<IRoutingTableManager>(); mock.Setup(x => x.EnsureRoutingTableForModeAsync(mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .ReturnsAsync(routingTableMock.Object); var clusterConnPoolMock = new Mock<IClusterConnectionPool>(); clusterConnPoolMock.Setup(x => x.AcquireAsync(uri, mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)).Returns( Task.FromException<IConnection>(new ProtocolException("do not understand struct 0x01"))); var balancer = new LoadBalancer(clusterConnPoolMock.Object, mock.Object); // When balancer.Awaiting(b => b.AcquireAsync(mode, null, null, Bookmark.Empty)).Should().Throw<ProtocolException>() .WithMessage("*do not understand struct 0x01*"); // while the server is not removed routingTableMock.Verify(m => m.Remove(uri), Times.Never); clusterConnPoolMock.Verify(m => m.DeactivateAsync(uri), Times.Never); } [Theory] [InlineData(AccessMode.Read)] [InlineData(AccessMode.Write)] public async Task ShouldReturnConnectionAccordingToLoadBalancingStrategy(AccessMode mode) { var routingTable = NewRoutingTable( new List<Uri> {new Uri("router:1"), new Uri("router:2")}, new List<Uri> {new Uri("reader:1"), new Uri("reader:2"), new Uri("reader:3")}, new List<Uri> {new Uri("writer:1"), new Uri("writer:2")}); var routingTableManager = new Mock<IRoutingTableManager>(); routingTableManager.Setup(x => x.EnsureRoutingTableForModeAsync(mode, null, null, Bookmark.Empty)) .ReturnsAsync(routingTable); var clusterPoolMock = new Mock<IClusterConnectionPool>(); clusterPoolMock.Setup(x => x.AcquireAsync(It.IsAny<Uri>(), mode, It.IsAny<string>(), It.IsAny<string>(), Bookmark.Empty)) .ReturnsAsync((Uri uri, AccessMode m, string d, string u, Bookmark b) => NewConnectionMock(uri, m)); var balancer = new LoadBalancer(clusterPoolMock.Object, routingTableManager.Object); if (mode == AccessMode.Read) { (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:1"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:2"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:3"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:1"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:2"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("reader:3"); } else if (mode == AccessMode.Write) { (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("writer:1"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("writer:2"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("writer:1"); (await balancer.AcquireAsync(mode, null, null, Bookmark.Empty)).Server.Address.Should().Be("writer:2"); } else { throw new ArgumentException(); } } private static IConnection NewConnectionMock(Uri uri, AccessMode mode) { var mockedConn = new Mock<IConnection>(); mockedConn.Setup(x => x.Server.Address).Returns(uri.ToString); mockedConn.Setup(x => x.Mode).Returns(mode); return mockedConn.Object; } } } }
50.687708
145
0.601953
[ "Apache-2.0" ]
AndyHeap-NeoTech/neo4j-dotnet-driver
Neo4j.Driver/Neo4j.Driver.Tests/Routing/LoadBalancerTests.cs
15,259
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the transfer-2018-11-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Transfer.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Transfer.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateUser operation /// </summary> public class UpdateUserResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UpdateUserResponse response = new UpdateUserResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ServerId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ServerId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("UserName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.UserName = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServiceError")) { return new InternalServiceErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return new InvalidRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonTransferException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static UpdateUserResponseUnmarshaller _instance = new UpdateUserResponseUnmarshaller(); internal static UpdateUserResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateUserResponseUnmarshaller Instance { get { return _instance; } } } }
40.529412
173
0.649596
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Transfer/Generated/Model/Internal/MarshallTransformations/UpdateUserResponseUnmarshaller.cs
4,823
C#
using System; using System.Collections.Generic; using System.IO; using System.Numerics; using SFML.System; using SFML.Graphics; using Checs; using Shoot_n_Mine.Engine; namespace Shoot_n_Mine { public class TileMap { public TileChunk[] chunks; public int chunksPerRow; public TileMap(int capacity, int chunksPerRow) { this.chunks = new TileChunk[capacity]; this.chunksPerRow = chunksPerRow; } public FloatRect Instantiate(World world, Position position) => Instantiate(world, position, out ReadOnlySpan<Entity> chunks); public FloatRect Instantiate(World world, Position position, out ReadOnlySpan<Entity> chunks) { var tileChunks = world.CreateEntity( world.CreateArchetype(typeof(TileChunk), typeof(Position)), this.chunks.Length); chunks = tileChunks; var currentPos = position.value; for(int i = 0; i < this.chunks.Length;) { for(int col = 0; col < this.chunksPerRow; ++col) { ref var chunk = ref world.RefComponentData<TileChunk>(tileChunks[i]); chunk = this.chunks[i]; world.SetComponentData<Position>(tileChunks[i], new Position(currentPos)); currentPos.X += TileChunk.PixelSize; ++i; } currentPos.X = position.value.X; currentPos.Y += TileChunk.PixelSize; } return new FloatRect( position.value.X, position.value.Y, TileChunk.PixelSize * this.chunksPerRow, currentPos.Y - position.value.Y); } public static TileMap Load(string fileName) { List<Tile[]> tiles = new List<Tile[]>(); string[] lines = File.ReadAllLines(fileName); int maxSizeX = 0; foreach(var line in lines) { var tileTypes = line.Split(' '); var generatedTiles = new Tile[tileTypes.Length]; if(tileTypes.Length > maxSizeX) maxSizeX = tileTypes.Length; for(int i = 0; i < tileTypes.Length; ++i) generatedTiles[i] = ParseTile(tileTypes[i]); tiles.Add(generatedTiles); } int maxSizeY = tiles.Count; int tileChunksX = (maxSizeX + TileChunk.Size - 1) / TileChunk.Size; int tileChunksY = (maxSizeY + TileChunk.Size - 1) / TileChunk.Size; TileMap map = new TileMap(tileChunksX * tileChunksY, tileChunksX); for(int row = 0; row < tileChunksY; ++row) { int startYIndex = row * TileChunk.Size; int endYIndex = Math.Min(startYIndex + TileChunk.Size, startYIndex + (tiles.Count - startYIndex)); for(int col = 0; col < tileChunksX; ++col) { int offset = 0; for(int y = startYIndex; y < endYIndex; ++y) { int startXIndex = col * TileChunk.Size; int endXIndex = Math.Min(startXIndex + TileChunk.Size, startXIndex + (tiles[y].Length - startXIndex)); for(int x = startXIndex; x < endXIndex; ++x) map.chunks[row * tileChunksX + col][offset++] = tiles[y][x]; } } } return map; } private static Tile ParseTile(string tileType) { if(char.IsDigit(tileType, 0)) return new Tile(Enum.Parse<TileType>(tileType)); switch(tileType[0]) { case '?': return new Tile(TileType.RandomBlock); case '-': return new Tile(TileType.RandomNatural); case '+': return new Tile(TileType.RandomResource); case 'x': return new Tile(TileType.Spawn); } return new Tile(TileType.None); } } }
24.56391
128
0.663606
[ "MIT" ]
dn9090/Checs
samples/Shoot-n-Mine/TileMap.cs
3,267
C#
/* * Copyright (c) 2010-2012, Achim 'ahzf' Friedland <achim@graph-database.org> * This file is part of Styx <http://www.github.com/Vanaheimr/Styx> * * 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. */ #region Usings using System; using System.Collections.Generic; #endregion namespace de.ahzf.Styx { /// <summary> /// A HistoryEnumerator wraps and behaves like a classical IEnumerator. /// However, it will remember what was last returned out of the IEnumerator. /// </summary> /// <typeparam name="T">The type of the stored elements.</typeparam> public class HistoryEnumerator<T> : IHistoryEnumerator, IEnumerator<T> { #region Data private readonly IEnumerator<T> _InternalEnumerator; private T _Last; private Boolean _FirstMove; #endregion #region Constructor(s) #region HistoryEnumerator(myIEnumerator) /// <summary> /// Creates a new HistoryEnumerator based on the given myIEnumerator. /// </summary> /// <param name="myIEnumerator">The enumerator to be wrapped.</param> public HistoryEnumerator(IEnumerator<T> myIEnumerator) { _InternalEnumerator = myIEnumerator; _Last = default(T); _FirstMove = true; } #endregion #endregion #region Current /// <summary> /// Return the current element of the internal IEnumertor. /// </summary> public T Current { get { return _InternalEnumerator.Current; } } /// <summary> /// Return the current element of the internal IEnumertor. /// </summary> Object System.Collections.IEnumerator.Current { get { return _InternalEnumerator.Current; } } #endregion #region Last /// <summary> /// Return the last element of the internal IEnumertor&lt;T&gt;. /// </summary> public T Last { get { return _Last; } } /// <summary> /// Return the last element of the internal IEnumertor. /// </summary> Object IHistoryEnumerator.Last { get { return _Last; } } #endregion #region MoveNext() /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns>True if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns> public Boolean MoveNext() { if (!_FirstMove) _Last = _InternalEnumerator.Current; else _FirstMove = false; return _InternalEnumerator.MoveNext(); } #endregion #region Reset() /// <summary> /// Sets the enumerator to its initial position, which is /// before the first element in the collection. /// </summary> public void Reset() { //_InternalEnumerator.Reset(); _Last = default(T); } #endregion #region Dispose() /// <summary> /// Dispose this enumerator. /// </summary> public void Dispose() { _InternalEnumerator.Dispose(); } #endregion } }
24.024096
162
0.578736
[ "Apache-2.0" ]
Vanaheimr/Styx
Styx.MF/Enumerators/HistoryEnumerator.cs
3,988
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ProjectBLL; using ProjectData; using Approve.Common; using Approve.RuleCenter; public partial class JZDW_AppMain_XMJZSLlist : System.Web.UI.Page { ProjectDB db = new ProjectDB(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { conBind(); showInfo(); } } //绑定选项 private void conBind() { for (int i = DateTime.Now.Year; i >= 2013; i--) { drop_FYear.Items.Add(new ListItem(i.ToString(), i.ToString())); } drop_FYear.Items.Insert(0, new ListItem("--全部--", "")); } //显示 private void showInfo() { string FBaseinfoID = CurrentEntUser.EntId; var v = from t in db.CF_App_List join d in db.CF_Prj_Data on t.FLinkId equals d.FId where t.FToBaseinfoId == FBaseinfoID && t.FState >= 1 && t.FManageTypeId == 28001 orderby t.FTime descending select new { t.FId, t.FPrjId, d.FPrjName, d.FPriItemId, t.FName, t.FCount, t.FCreateTime, t.FState, t.FManageTypeId, t.FReportDate, t.FUpDeptId, t.FYear, t.FBaseName, t.FAppDate, t.FLinkId, app = db.CF_App_List.Where(a => a.FLinkId == t.FLinkId && a.FManageTypeId == 280).FirstOrDefault() }; if (!string.IsNullOrEmpty(ttFPrjName.Text.Trim())) v = v.Where(t => t.FPrjName.Contains(ttFPrjName.Text.Trim())); if (!string.IsNullOrEmpty(ddlFState.SelectedValue)) v = v.Where(t => t.FState.ToString() == ddlFState.SelectedValue); if (!string.IsNullOrEmpty(drop_FYear.SelectedValue)) v = v.Where(t => t.FYear.ToString() == drop_FYear.SelectedValue); Pager1.RecordCount = v.Count(); DG_List.DataSource = v.Skip((Pager1.CurrentPageIndex - 1) * Pager1.PageSize).Take(Pager1.PageSize); DG_List.DataBind(); Pager1.Visible = (Pager1.RecordCount > Pager1.PageSize); } //列表 protected void DG_List_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label lbautoid = (Label)e.Row.FindControl("lbautoid"); lbautoid.Text = (e.Row.RowIndex + 1).ToString(); string FID = EConvert.ToString(DataBinder.Eval(e.Row.DataItem, "FID")); string FState = EConvert.ToString(DataBinder.Eval(e.Row.DataItem, "FState")); string ReportServer = db.getSysObjectContent("_ReportServer"); if (string.IsNullOrEmpty(ReportServer)) { ReportServer = "http://" + Request.Url.Host + ":8075/WebReport/ReportServer?reportlet="; } //状态办理结果 string s = ""; string o = "<a href='javascript:showAddWindow(\"../ApplyKCXMWT/Report.aspx?FAppId=" + FID + "\",700,480);'>"; string t = ""; switch (FState) { case "1": s = "<font color='#888888'>还未确认</font>"; e.Row.Cells[4].Text = "<font color='#888888'>--</font>"; o += "确认合同"; t += "<font color='#888888'>还未确认</font>"; break; case "2": s = "<font color='red'>已退回</font>"; o += "查看确认详情"; t += "<font color='#888888'>已退回</font>"; break; case "6": s = "<font color='green'>已确认</font>"; o += "查看确认详情"; t += "<a href='" + ReportServer + "SLD-XMJZ.cpt&FAppId=" + FID + "' target='_blank'>打印合同确认单</a>"; break; case "7": s = "<font color='red'>不予接受</font>"; o += "查看确认详情"; t += "<font color='#888888'>不予接受</font>"; break; } CF_App_List app = DataBinder.Eval(e.Row.DataItem, "app") as CF_App_List; if (app != null) { if (app.FState == 2) { s += "</br><font color='red'>(已被勘察单位退回,业务终止)</font>"; } else if (app.FState == 7) { s += "</br><font color='red'>(合同备案的勘察单位不予接受,业务终止)</font>"; } } e.Row.Cells[5].Text = s; e.Row.Cells[6].Text = o + "</a>"; e.Row.Cells[7].Text = t; //是否二次。 int n = EConvert.ToInt(DataBinder.Eval(e.Row.DataItem, "FCount")); string FPriItemId = EConvert.ToString(DataBinder.Eval(e.Row.DataItem, "FPriItemId")); if (n > 1) { //查询出不合格的意见(从勘查文件审查业务的技术性审查28803中查) var v = db.CF_App_List.Where(a => a.FLinkId == FPriItemId && a.FManageTypeId == 28803).FirstOrDefault(); if (v != null) { string txt = "<a style=\"text-decoration:underline;\" "; txt += "href=\"javascript:showAddWindow('../../KcsjSgt/ApplyKCJSXSC/Report.aspx?FAppId=" + v.FId + "',700,680);\">"; txt += "查看审图机构意见</a>"; ((Literal)e.Row.FindControl("lit_Count")).Text = ("(" + n + "次," + txt + ")"); } } //查询项目的变更时间 string FPrjId = EConvert.ToString(DataBinder.Eval(e.Row.DataItem, "FPrjId")); var prjBG = db.CF_Prj_BaseInfo.Where(st => st.FId == FPrjId) .Select(st => new { st.FIsBG, st.FBGTime, st.FCount }) .FirstOrDefault(); if (prjBG.FCount > 0) { ((Literal)e.Row.FindControl("prj_Count")).Text = ("<br/>(第" + prjBG.FCount + "次变更:" + EConvert.ToShortDateString(prjBG.FBGTime) + ")"); } //判断项目是不是被终止了 var stop = db.CF_Prj_Stop.Count(st => st.FPrjId == FPrjId) > 0; if (stop) { e.Row.Attributes["style"] = "background:#EEEEEE;color:#999999;"; e.Row.ToolTip = "该项目已被中止,所有业务停止进行。"; } else if (prjBG.FIsBG == 1)//判断该项目是否变更 { e.Row.Attributes["style"] = "background:#EEEEEE;color:#999999;"; e.Row.ToolTip = "该项目已经做了变更,变更前的业务停止进行。"; } } } //分页面控件翻页事件 protected void Pager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e) { Pager1.CurrentPageIndex = e.NewPageIndex; showInfo(); } //刷新按钮 protected void btnQuery_Click(object sender, EventArgs e) { showInfo(); } }
36.994792
151
0.485288
[ "MIT" ]
coojee2012/pm3
SurveyDesign/JZDW/AppMain/XMJZSLlist.aspx.cs
7,569
C#
using System.Text; using RimWorld; using UnityEngine; using Verse; namespace Infused { public class ITab_Infused : ITab { static readonly Vector2 WinSize = new Vector2(400, 550); public override bool IsVisible => SelThing?.TryGetComp<CompInfused>()?.IsActive ?? false; public ITab_Infused() { size = WinSize; labelKey = "Infused.Tab"; } protected override void FillTab() { var selectedCompInfusion = SelThing.TryGetComp<CompInfused>(); Text.Font = GameFont.Medium; GUI.color = selectedCompInfusion.InfusedLabelColor; //Label var rectBase = new Rect(0f, 0f, WinSize.x, WinSize.y).ContractedBy(10f); var rectLabel = rectBase; var label = selectedCompInfusion.GetInfusionLabel(false).CapitalizeFirst(); Widgets.Label(rectLabel, label); //Quality var rectQuality = rectBase; rectQuality.yMin += Text.CalcHeight(label, rectBase.width); Text.Font = GameFont.Small; QualityCategory qc; selectedCompInfusion.parent.TryGetQuality(out qc); var subLabelBuilder = new StringBuilder(); subLabelBuilder.Append(qc.GetLabel().CapitalizeFirst()) .Append(" ") .Append(ResourceBank.Strings.Quality) .Append(" "); if (selectedCompInfusion.parent.Stuff != null) { subLabelBuilder.Append(selectedCompInfusion.parent.Stuff.LabelAsStuff).Append(" "); } subLabelBuilder.Append(selectedCompInfusion.parent.def.label); var subLabel = subLabelBuilder.ToString(); Widgets.Label(rectQuality, subLabel); GUI.color = Color.white; //Infusion descriptions Text.Anchor = TextAnchor.UpperLeft; var rectDesc = rectBase; rectDesc.yMin += rectQuality.yMin + Text.CalcHeight(subLabel, rectBase.width); Text.Font = GameFont.Small; Widgets.Label(rectDesc, selectedCompInfusion.GetDescriptionInfused()); } } }
33.575758
99
0.591606
[ "MIT" ]
Endgegner/RimWorld-Infused
Source/ITab_Infused.cs
2,218
C#
using System; using System.Collections.Generic; namespace PizzaBox.Data.Model { public partial class Plocation { public Plocation() { Pizza = new HashSet<Pizza>(); Porder = new HashSet<Porder>(); Puser = new HashSet<Puser>(); } public int LocationId { get; set; } public string Street { get; set; } public string City { get; set; } public string PState { get; set; } public string Zipcode { get; set; } public virtual ICollection<Pizza> Pizza { get; set; } public virtual ICollection<Porder> Porder { get; set; } public virtual ICollection<Puser> Puser { get; set; } } }
27.346154
63
0.579466
[ "MIT" ]
1905-may06-dotnet/Fred_Brume_Project1
PizzaBoxSolution/RestaurantData/Model/Plocation.cs
713
C#
using System; using NUnit.Framework; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI40; using Net.RutokenPkcs11Interop.Common; using Net.RutokenPkcs11Interop.LowLevelAPI40; using NativeULong = System.UInt32; namespace Net.RutokenPkcs11InteropTests.LowLevelAPI40 { [TestFixture()] public class _LL_34_ManageEntityTest { [Test()] public void _LL_34_01_ManageSlotTest() { if (Platform.NativeULongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (var pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath)) { // Инициализация библиотеки rv = pkcs11.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Установление соединения с Рутокен в первом доступном слоте NativeULong slotId = Helpers.GetUsableSlot(pkcs11); // TODO: актуализировать тест с реальными значениями rv = pkcs11.C_EX_SlotManage(slotId, 0, IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Завершение сессии rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } [Test()] public void _LL_34_02_ManageTokenTest() { if (Platform.NativeULongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (var pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath)) { // Инициализация библиотеки rv = pkcs11.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Установление соединения с Рутокен в первом доступном слоте NativeULong slotId = Helpers.GetUsableSlot(pkcs11); // Открытие RW сессии NativeULong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // TODO: актуализировать тест с реальными значениями rv = pkcs11.C_EX_TokenManage(session, (NativeULong)TokenManageMode.ChannelTypeBluetooth, IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Завершение сессии rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
36.786517
118
0.565669
[ "Apache-2.0" ]
lo1ol/RutokenPkcs11Interop
src/RutokenPkcs11Interop.Tests/LowLevelAPI40/_LL_34_ManageEntityTest.cs
3,548
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Jupyter.Core; using Microsoft.Quantum.IQSharp.Common; using Microsoft.Quantum.IQSharp.Jupyter; namespace Microsoft.Quantum.IQSharp.Kernel { /// <summary> /// A magic symbol that provides access to a given workspace. /// </summary> public class WorkspaceMagic : AbstractMagic { private const string ParameterNameCommand = "__command__"; /// <summary> /// Given a workspace, constructs a new magic symbol to control /// that workspace. /// </summary> public WorkspaceMagic(IWorkspace workspace, ILogger<WorkspaceMagic> logger) : base( "workspace", new Microsoft.Jupyter.Core.Documentation { Summary = "Provides actions related to the current workspace.", Description = @" This magic command allows for displaying and reloading the Q# operations and functions defined within .qs files in the current folder. If no parameters are provided, the command displays a list of Q# operations or functions within .qs files in the current folder which are available in the current IQ# session for use with magic commands such as `%simulate` and `%estimate`. The command will also output any errors encountered while compiling the .qs files in the current folder. #### Optional parameters - `reload`: Causes the IQ# kernel to recompile all .qs files in the current folder. ".Dedent(), Examples = new [] { @" Display the list of Q# operations and functions available in the current folder: ``` In []: %workspace Out[]: <list of Q# operation and function names> ``` ".Dedent(), @" Recompile the .qs files in the current folder: ``` In []: %workspace reload Out[]: <list of Q# operation and function names> ``` ".Dedent(), } }, logger) { this.Workspace = workspace; } /// <summary> /// The workspace controlled by this magic symbol. /// </summary> public IWorkspace Workspace { get; } /// <summary> /// Performs checks to verify if the Workspace is available and in a success (no errors) state. /// The method throws Exceptions if it finds it is not ready to execute. /// </summary> public void CheckIfReady() { if (Workspace == null) { throw new InvalidWorkspaceException($"Workspace is not ready. Try again."); } else if (Workspace.HasErrors) { throw new InvalidWorkspaceException(Workspace.ErrorMessages.ToArray()); } } internal static void Reload(IWorkspace workspace, IChannel channel) { var status = new Jupyter.TaskStatus($"Reloading workspace"); var statusUpdater = channel.DisplayUpdatable(status); void Update() => statusUpdater.Update(status); var task = Task.Run(() => { workspace.Reload((newStatus) => { status.Subtask = newStatus; Update(); }); }); try { using (Observable .Interval(TimeSpan.FromSeconds(1)) .TakeUntil((idx) => task.IsCompleted) .Do(idx => Update()) .Subscribe()) { task.Wait(); } status.Subtask = "done"; status.IsCompleted = true; Update(); } catch (Exception) { status.Subtask = "error"; status.IsCompleted = true; Update(); throw; } } /// <inheritdoc /> public override ExecutionResult Run(string input, IChannel channel) { var inputParameters = ParseInputParameters(input, firstParameterInferredName: ParameterNameCommand); var command = inputParameters.DecodeParameter<string>(ParameterNameCommand); if (string.IsNullOrWhiteSpace(command)) { // if no command, just return the current state. } else if ("reload" == command) { Reload(Workspace, channel); } else { channel.Stderr($"Invalid action: {command}"); return ExecuteStatus.Error.ToExecutionResult(); } CheckIfReady(); var names = Workspace? .Assemblies? .SelectMany(asm => asm.Operations) .Select(c => c.FullName) .OrderBy(name => name) .ToArray(); return names.ToExecutionResult(); } } }
35.475
112
0.500705
[ "MIT" ]
Bradben/iqsharp
src/Kernel/Magic/WorkspaceMagic.cs
5,678
C#
/* * GraphHopper Directions API * * With the [GraphHopper Directions API](https://www.graphhopper.com/products/) you can integrate A-to-B route planning, turn-by-turn navigation, route optimization, isochrone calculations and other tools in your application. The GraphHopper Directions API consists of the following RESTful web services: * [Routing](#tag/Routing-API), * [Route Optimization](#tag/Route-Optimization-API), * [Isochrone](#tag/Isochrone-API), * [Map Matching](#tag/Map-Matching-API), * [Matrix](#tag/Matrix-API) and * [Geocoding](#tag/Geocoding-API). # Explore our APIs To play and see the Route Optimization in action try our [route editor](https://graphhopper.com/blog/2015/07/21/graphhoppers-new-route-optimization-editor/) which available in the [dashboard](https://graphhopper.com/dashboard/). See how the Routing and Geocoding is integrated in our route planner website [GraphHopper Maps](https://graphhopper.com/maps) ([sources](https://github.com/graphhopper/graphhopper/tree/0.12/web/src/main/resources/assets)). And [see below](#section/Explore-our-APIs/Insomnia) for a collection of requests for [Insomnia](https://insomnia.rest/) and [Postman](https://www.getpostman.com/). The request file contains all example requests from this documentation. ## Get started 1. To use the GraphHopper Directions API you sign up [here](https://graphhopper.com/dashboard/#/register) and create an API key. 2. Read the documentation of the desired API part below. 3. Start using the GraphHopper Directions API. [Our API clients](#section/Explore-our-APIs/API-Clients) can speed up the integration. To use the GraphHopper Directions API commercially, you can buy paid package [in the dashboard](https://graphhopper.com/dashboard/#/pricing). ## Contact Us If you have problems or questions see the following information: * [FAQ](https://graphhopper.com/api/1/docs/FAQ/) * [Public forum](https://discuss.graphhopper.com/c/directions-api) * [Contact us](https://www.graphhopper.com/contact-form/) To get informed about the newest features and development follow us at [twitter](https://twitter.com/graphhopper/) or [our blog](https://graphhopper.com/blog/). Furthermore you can watch [this git repository](https://github.com/graphhopper/directions-api-doc) of this documentation, sign up at our [dashboard](https://graphhopper.com/dashboard/) to get the newsletter or sign up at [our forum](https://discuss.graphhopper.com/c/directions-api). Pick the channel you like most. ## API Clients To speed up development and make coding easier, we offer the following clients: * [JavaScript client](https://github.com/graphhopper/directions-api-js-client) - try the [live examples](https://graphhopper.com/api/1/examples/) * [Others](https://github.com/graphhopper/directions-api-clients) like C#, Ruby, PHP, Python, ... automatically created for the Route Optimization ### Bandwidth reduction If you create your own client, make sure it supports http/2 and gzipped responses for best speed. If you use the Matrix or Route Optimization and want to solve large problems, we recommend you to reduce bandwidth by [compressing your POST request](https://gist.github.com/karussell/82851e303ea7b3459b2dea01f18949f4) and specifying the header as follows: `Content-Encoding: gzip`. ## Insomnia To explore our APIs with [Insomnia](https://insomnia.rest/), follow these steps: 1. Open Insomnia and Import [our workspace](https://raw.githubusercontent.com/graphhopper/directions-api-doc/master/web/restclients/GraphHopper-Direction-API-Insomnia.json). 2. Specify [your API key](https://graphhopper.com/dashboard/#/register) in your workspace: Manage Environments -> Base Environment -> `\"api_key\": your API key` 3. Start exploring ![Insomnia](./img/insomnia.png) ## Postman To explore our APIs with [Postman](https://www.getpostman.com/), follow these steps: 1. Import our [request collections](https://raw.githubusercontent.com/graphhopper/directions-api-doc/master/web/restclients/graphhopper_directions_api.postman_collection.json) as well as our [environment file](https://raw.githubusercontent.com/graphhopper/directions-api-doc/master/web/restclients/graphhopper_directions_api.postman_environment.json). 2. Specify [your API key](https://graphhopper.com/dashboard/#/register) in your environment: `\"api_key\": your API key` 3. Start exploring ![Postman](./img/postman.png) # Map Data and Routing Profiles Currently, our main data source is [OpenStreetMap](https://www.openstreetmap.org). We also integrated other network data providers. This chapter gives an overview about the options you have. ## OpenStreetMap #### Geographical Coverage [OpenStreetMap](https://www.openstreetmap.org) covers the entire world. If you want to convince yourself whether we can offer appropriate data for your region, please visit [GraphHopper Maps](https://graphhopper.com/maps/). You can edit and modify OpenStreetMap data if you find that important information is missing, for example, a weight restriction for a bridge. [Here](https://wiki.openstreetmap.org/wiki/Beginners%27_guide) is a beginner's guide that shows how to add data. If you edited data, we usually consider your data after 1 week at latest. #### Supported Vehicle Profiles The Routing, Matrix and Route Optimizations support the following vehicle profiles: Name | Description | Restrictions | Icon - -- -- -- -- --|:- -- -- -- -- -- -- -- -- -- -- -|:- -- -- -- -- -- -- -- -- -- -- -- -- -|:- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- car | Car mode | car access | ![car image](https://graphhopper.com/maps/img/car.png) small_truck| Small truck like a Mercedes Sprinter, Ford Transit or Iveco Daily | height=2.7m, width=2+0.4m, length=5.5m, weight=2080+1400 kg | ![small truck image](https://graphhopper.com/maps/img/small_truck.png) truck | Truck like a MAN or Mercedes-Benz Actros | height=3.7m, width=2.6+0.5m, length=12m, weight=13000 + 13000 kg, hgv=yes, 3 Axes | ![truck image](https://graphhopper.com/maps/img/truck.png) scooter | Moped mode | Fast inner city, often used for food delivery, is able to ignore certain bollards, maximum speed of roughly 50km/h | ![scooter image](https://graphhopper.com/maps/img/scooter.png) foot | Pedestrian or walking | foot access | ![foot image](https://graphhopper.com/maps/img/foot.png) hike | Pedestrian or walking with priority for more beautiful hiking tours and potentially a bit longer than `foot` | foot access | ![hike image](https://graphhopper.com/maps/img/hike.png) bike | Trekking bike avoiding hills | bike access | ![bike image](https://graphhopper.com/maps/img/bike.png) mtb | Mountainbike | bike access | ![Mountainbike image](https://graphhopper.com/maps/img/mtb.png) racingbike| Bike preferring roads | bike access | ![racingbike image](https://graphhopper.com/maps/img/racingbike.png) **Please note, that turn restrictions for motor vehicles such as `car` or `truck` are only considered with `edge_based=true` for the Routing (other APIs will follow).** Or if you already use `ch.disable=true` no additional parameter is required to consider turn restrictions for motor vehicles. For the free package you can only choose from `car`, `bike` or `foot`. We also offer a sophisticated `motorcycle` profile powered by the [Kurviger](https://kurviger.de/en) Routing. Kurviger favors curves and slopes while avoiding cities and highways. Also we offer custom vehicle profiles with different properties, different speed profiles or different access options. To find out more about custom profiles, please [contact us](https://www.graphhopper.com/contact-form/). ## TomTom If you need to consider traffic, you can purchase the TomTom add-on. Please note: * Currently we only offer this for our [Route Optimization](#tag/Route-Optimization-API). * This add-on uses the TomTom road network and historical traffic information only. Live traffic is not yet considered. Read more about [how this works](https://www.graphhopper.com/blog/2017/11/06/time-dependent-optimization/). * Additionally to our terms your end users need to accept the [TomTom Eula](https://www.graphhopper.com/tomtom-end-user-license-agreement/). * We do *not* use the TomTom web services. We only use their data with our software. [Contact us](https://www.graphhopper.com/contact-form/) for more details. #### Geographical Coverage We offer - Europe including Russia - North, Central and South America - Saudi Arabia - United Arab Emirates - South Africa - Australia #### Supported Vehicle Profiles Name | Description | Restrictions | Icon - -- -- -- -- --|:- -- -- -- -- -- -- -- -- -- -- -|:- -- -- -- -- -- -- -- -- -- -- -- -- -|:- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- car | Car mode | car access | ![car image](https://graphhopper.com/maps/img/car.png) small_truck| Small truck like a Mercedes Sprinter, Ford Transit or Iveco Daily | height=2.7m, width=2+0.4m, length=5.5m, weight=2080+1400 kg | ![small truck image](https://graphhopper.com/maps/img/small_truck.png) * * OpenAPI spec version: 1.0.0 * Contact: support@graphhopper.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; namespace IO.Swagger.Client { /// <summary> /// API Exception /// </summary> public class ApiException : Exception { /// <summary> /// Gets or sets the error code (HTTP status code) /// </summary> /// <value>The error code (HTTP status code).</value> public int ErrorCode { get; set; } /// <summary> /// Gets or sets the error content (body json object) /// </summary> /// <value>The error content (Http response body).</value> public dynamic ErrorContent { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class. /// </summary> public ApiException() {} /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class. /// </summary> /// <param name="errorCode">HTTP status code.</param> /// <param name="message">Error message.</param> public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } /// <summary> /// Initializes a new instance of the <see cref="ApiException"/> class. /// </summary> /// <param name="errorCode">HTTP status code.</param> /// <param name="message">Error message.</param> /// <param name="errorContent">Error content.</param> public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { this.ErrorCode = errorCode; this.ErrorContent = errorContent; } } }
185.35
9,278
0.698229
[ "Apache-2.0" ]
boldtrn/graphhopper-routing-api-swagger
csharp/src/IO.Swagger/Client/ApiException.cs
11,121
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DBStoreContext.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using ModelsLayer.EFModels; using Microsoft.EntityFrameworkCore; using OnlineStoreBusinessLayer.Interfaces; using OnlineStoreUi; using ModelsLayer.Models; using Microsoft.Extensions.Logging; namespace OnlineStoreUi.Controllers { [Route("api/[controller]")] [ApiController] public class OrderController : ControllerBase { private readonly IOrderRepository _orderRepo; private readonly ILogger<OrderController> _logger; public OrderController(IOrderRepository cr, ILogger<OrderController> logger) { _orderRepo = cr; _logger = logger; } [HttpPost] // public async Task<ActionResult<Order>> PostOrder(Order order) // { // _context.Orders.Add(order); // await _context.SaveChangesAsync(); // return CreatedAtAction("GetOrder", new { id = order.OrderId }, order); // } public async Task<ActionResult<ViewModelOrder>> Create(ViewModelOrder c) { // _context.Orders.Add(order); // await _context.SaveChangesAsync(); // // return Created($"~order/{order.CustomerId}", order); // return CreatedAtAction("GetOrder", new { id = order.OrderId }, order); if (!ModelState.IsValid) return BadRequest(); //ViewModelCustomer c = new ViewModelCustomer() { Fname = fname, Lname = lname }; //send fname and lname into a method of the business layer to check the Db fo that guy/gal; ViewModelOrder c1 = await _orderRepo.RegisterOrdersAsync(c); if (c1 == null) { return NotFound(); } return Created($"~order/{c1.OrderId}", c1); } [HttpGet("{selectorderId}")] public async Task<ActionResult<ViewModelOrder>> GetOrderList(int selectorderId) { // if (!ModelState.IsValid) return BadRequest(); ViewModelOrder o = new ViewModelOrder() { OrderId = selectorderId }; //send fname and lname into a method of the business layer to check the Db fo that guy/gal; List<ViewModelOrder> o1 = await _orderRepo.OrdersListAsync(o); if (o1 == null) { return NotFound(); } return Ok(o1); } } }
30.050633
98
0.659225
[ "MIT" ]
08162021-dotnet-uta/Simran-ManandharRepo1
projects/Project_1/OnlineStore/OnlineStore/OnlineStoreUI/Controllers/OrderController.cs
2,374
C#
namespace Trivality.Web.Areas.HelpPage.ModelDescriptions { public class SimpleTypeModelDescription : ModelDescription { } }
22.5
62
0.77037
[ "MIT" ]
jasonmcl/Trivality
Trivality.Web/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs
135
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 26.11.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; using structure_lib=lcpi.lib.structure; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.CastAs.SET_001.Int64.Byte{ //////////////////////////////////////////////////////////////////////////////// using T_SOURCE_VALUE=System.Int64; using T_TARGET_VALUE=System.Byte; //////////////////////////////////////////////////////////////////////////////// //class TestSet__ER004__param public static class TestSet__ER004__param { private const string c_NameOf__TABLE="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__min_m1() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource=((T_SOURCE_VALUE)T_TARGET_VALUE.MinValue)-1; const T_TARGET_VALUE c_valueTarget=0; T_SOURCE_VALUE vv1=c_valueSource; T_TARGET_VALUE vv2=c_valueTarget; var recs=db.testTable.Where(r => (T_TARGET_VALUE)vv1==(T_TARGET_VALUE)vv2); try { foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r TestServices.ThrowWeWaitError(); } catch(InvalidOperationException exc) { CheckErrors.PrintException_OK(exc); Assert.NotNull (exc.InnerException); Assert.IsInstanceOf<structure_lib.exceptions.t_overflow_exception> (exc.InnerException); var e2=(structure_lib.exceptions.t_overflow_exception)exc.InnerException; Assert.NotNull (e2); Assert.AreEqual (1, TestUtils.GetRecordCount(e2)); Assert.NotNull (TestUtils.GetRecord(e2,0)); CheckErrors.CheckErrorRecord__common_err__cant_convert_value_between_types_2 (TestUtils.GetRecord(e2,0), CheckErrors.c_src__EFCoreDataProvider__Root_Query_Local_Expressions__Cvt_MasterCode__Int64__Byte, lcpi.lib.com.HResultCode.DB_E_DATAOVERFLOW, typeof(T_SOURCE_VALUE), typeof(T_TARGET_VALUE)); }//catch }//using db tr.Rollback(); }//using tr }//using cn }//Test_001__min_m1 //----------------------------------------------------------------------- [Test] public static void Test_002__max_p1() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_SOURCE_VALUE c_valueSource=((T_SOURCE_VALUE)T_TARGET_VALUE.MaxValue)+1; const T_TARGET_VALUE c_valueTarget=0; T_SOURCE_VALUE vv1=c_valueSource; T_TARGET_VALUE vv2=c_valueTarget; var recs=db.testTable.Where(r => (T_TARGET_VALUE)vv1==(T_TARGET_VALUE)vv2); try { foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r TestServices.ThrowWeWaitError(); } catch(InvalidOperationException exc) { CheckErrors.PrintException_OK(exc); Assert.NotNull (exc.InnerException); Assert.IsInstanceOf<structure_lib.exceptions.t_overflow_exception> (exc.InnerException); var e2=(structure_lib.exceptions.t_overflow_exception)exc.InnerException; Assert.NotNull (e2); Assert.AreEqual (1, TestUtils.GetRecordCount(e2)); Assert.NotNull (TestUtils.GetRecord(e2,0)); CheckErrors.CheckErrorRecord__common_err__cant_convert_value_between_types_2 (TestUtils.GetRecord(e2,0), CheckErrors.c_src__EFCoreDataProvider__Root_Query_Local_Expressions__Cvt_MasterCode__Int64__Byte, lcpi.lib.com.HResultCode.DB_E_DATAOVERFLOW, typeof(T_SOURCE_VALUE), typeof(T_TARGET_VALUE)); }//catch }//using db tr.Rollback(); }//using tr }//using cn }//Test_002__max_p1 };//class TestSet__ER004__param //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.CastAs.SET_001.Int64.Byte
27.808743
105
0.615445
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/CastAs/SET_001/Int64/Byte/TestSet__ER004__param.cs
5,091
C#
using System; using NSubstitute; using Octokit.Reactive; using Xunit; namespace Octokit.Tests.Reactive { public class ObservableRepositoryForksClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>( () => new ObservableRepositoryForksClient(null)); } } public class TheGetAllMethod { [Fact] public void RequestsCorrectUrl() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); client.GetAll("fake", "repo"); gitHubClient.Received().Repository.Forks.GetAll("fake", "repo"); } [Fact] public void RequestsCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); client.GetAll(1); gitHubClient.Received().Repository.Forks.GetAll(1); } [Fact] public void RequestsCorrectUrlWithApiOptions() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; client.GetAll("fake", "repo", options); gitHubClient.Received().Repository.Forks.GetAll("fake", "repo", options); } [Fact] public void RequestsCorrectUrlWithRepositoryIdWithApiOptions() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; client.GetAll(1, options); gitHubClient.Received().Repository.Forks.GetAll(1, options); } [Fact] public void RequestsCorrectUrlWithRequestParameters() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var repositoryForksListRequest = new RepositoryForksListRequest { Sort = Sort.Stargazers }; client.GetAll("fake", "repo", repositoryForksListRequest); gitHubClient.Received().Repository.Forks.GetAll( "fake", "repo", repositoryForksListRequest); } [Fact] public void RequestsCorrectUrlWithRepositoryIdWithRequestParameters() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var repositoryForksListRequest = new RepositoryForksListRequest { Sort = Sort.Stargazers }; client.GetAll(1, repositoryForksListRequest); gitHubClient.Received().Repository.Forks.GetAll( 1, repositoryForksListRequest); } [Fact] public void RequestsCorrectUrlWithRequestParametersWithApiOptions() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; var repositoryForksListRequest = new RepositoryForksListRequest { Sort = Sort.Stargazers }; client.GetAll("fake", "repo", repositoryForksListRequest, options); gitHubClient.Received().Repository.Forks.GetAll("fake", "name", repositoryForksListRequest, options); } [Fact] public void RequestsCorrectUrlWithRepositoryIdWithRequestParametersWithApiOptions() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; var repositoryForksListRequest = new RepositoryForksListRequest { Sort = Sort.Stargazers }; client.GetAll(1, repositoryForksListRequest, options); gitHubClient.Received().Repository.Forks.GetAll(1, repositoryForksListRequest, options); } [Fact] public void EnsuresNonNullArguments() { var client = new ObservableRepositoryForksClient(Substitute.For<IGitHubClient>()); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name")); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "name", (ApiOptions)null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name", new RepositoryForksListRequest())); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null, new RepositoryForksListRequest())); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "name", (RepositoryForksListRequest)null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name", new RepositoryForksListRequest(), ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null, new RepositoryForksListRequest(), ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "name", null, ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "name", new RepositoryForksListRequest(), null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(1, (ApiOptions)null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(1, (RepositoryForksListRequest)null)); Assert.Throws<ArgumentNullException>(() => client.GetAll(1, new RepositoryForksListRequest(), null)); Assert.Throws<ArgumentException>(() => client.GetAll("", "name")); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "")); Assert.Throws<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None)); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None)); Assert.Throws<ArgumentException>(() => client.GetAll("", "name", new RepositoryForksListRequest())); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "", new RepositoryForksListRequest())); Assert.Throws<ArgumentException>(() => client.GetAll("", "name", new RepositoryForksListRequest(), ApiOptions.None)); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "", new RepositoryForksListRequest(), ApiOptions.None)); } } public class TheCreateMethod { [Fact] public void RequestsCorrectUrl() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var newRepositoryFork = new NewRepositoryFork(); client.Create("fake", "repo", newRepositoryFork); gitHubClient.Received().Repository.Forks.Create("fake", "repo", newRepositoryFork); } [Fact] public void RequestsCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableRepositoryForksClient(gitHubClient); var newRepositoryFork = new NewRepositoryFork(); client.Create(1, newRepositoryFork); gitHubClient.Received().Repository.Forks.Create(1, newRepositoryFork); } [Fact] public void EnsuresNonNullArguments() { var client = new ObservableRepositoryForksClient(Substitute.For<IGitHubClient>()); Assert.Throws<ArgumentNullException>(() => client.Create(null, "name", new NewRepositoryFork())); Assert.Throws<ArgumentNullException>(() => client.Create("owner", null, new NewRepositoryFork())); Assert.Throws<ArgumentNullException>(() => client.Create("owner", "name", null)); Assert.Throws<ArgumentNullException>(() => client.Create(1, null)); Assert.Throws<ArgumentException>(() => client.Create("", "name", new NewRepositoryFork())); Assert.Throws<ArgumentException>(() => client.Create("owner", "", new NewRepositoryFork())); } } } }
42.964602
140
0.57827
[ "MIT" ]
3shape/octokit.net
Octokit.Tests/Reactive/ObservableRepositoryForksClientTests.cs
9,712
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wincrypt.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public unsafe partial struct CRYPT_ATTRIBUTES { [NativeTypeName("DWORD")] public uint cAttr; [NativeTypeName("PCRYPT_ATTRIBUTE")] public CRYPT_ATTRIBUTE* rgAttr; } }
30.941176
145
0.714829
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/wincrypt/CRYPT_ATTRIBUTES.cs
528
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 osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osuTK; namespace osu.Game.Online.Multiplayer.GameTypes { public class GameTypeTeamVersus : GameType { public override string Name => "Team Versus"; public override Drawable GetIcon(OsuColour colours, float size) { return new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(2f), Children = new[] { new VersusRow(colours.Blue, colours.Pink, size * 0.5f), new VersusRow(colours.Blue, colours.Pink, size * 0.5f), }, }; } } }
32.121212
93
0.559434
[ "MIT" ]
Dragicafit/osu
osu.Game/Online/Multiplayer/GameTypes/GameTypeTeamVersus.cs
1,028
C#
using Application.Interfaces; using MediatR; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Application.Features.VoteFeatures.Commands { public class DeleteVoteByIdCommand : IRequest<int> { public int Id { get; set; } public class DeleteVoteByIdCommandHandler : IRequestHandler<DeleteVoteByIdCommand, int> { private readonly IApplicationDbContext _context; public DeleteVoteByIdCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<int> Handle(DeleteVoteByIdCommand command, CancellationToken cancellationToken) { var vote = await _context.Votes.Where(a => a.Id == command.Id).FirstOrDefaultAsync(); if (vote == null) return default; _context.Votes.Remove(vote); await _context.SaveChanges(); return vote.Id; } } } }
32.84375
109
0.635585
[ "MIT" ]
Gjognumskygni/TransparencyAPI
Application/Features/VoteFeatures/Commands/DeleteVoteByIdCommand.cs
1,053
C#
using Autofac; using OlympicGames.Core; using OlympicGames.Core.ConsoleWrappers; using OlympicGames.Core.Contracts; using OlympicGames.Core.Factories; using OlympicGames.Core.Providers; namespace OlympicGames.Client { public class InjectConfig : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<CommandParser>().As<ICommandParser>(); builder.RegisterType<CommandProcessor>().As<ICommandProcessor>(); builder.RegisterType<OlympicCommittee>().As<IOlympicCommittee>(); builder.RegisterType<OlympicsFactory>().As<IOlympicsFactory>(); builder.RegisterType<ConsoleWrapper>().As<IConsoleWrapper>(); builder.RegisterType<ConsoleWriter>().As<IConsoleWriter>(); builder.RegisterType<ConsoleReader>().As<IConsoleReader>(); builder.RegisterType<Engine>().As<IEngine>().SingleInstance(); } } }
36.692308
77
0.697065
[ "MIT" ]
dobri19/TelerikHomeWork
04C#UnitTesting&DesignPatterns/04-DependencyInversion/OlympicGames0802Solution/OlympicGames.Client/InjectConfig.cs
956
C#
using System.Collections.Generic; using System.Linq; using LinqToDB.Configuration; namespace LinqToDB.DataProvider.DB2iSeries { public class DB2iSeriesFactory : IDataProviderFactory { public IDataProvider GetDataProvider(IEnumerable<NamedValue> attributes) { var versionText = attributes.FirstOrDefault(_ => _.Name == "version"); var version = versionText.Value switch { var x when x.StartsWith("7.3.") || x == "7.3" || x == "7_3" => DB2iSeriesVersion.V7_3, var x when x.StartsWith("7.2.") || x == "7.2" || x == "7_2" => DB2iSeriesVersion.V7_2, _ => DB2iSeriesVersion.V7_1 }; var providerType = attributes.FirstOrDefault(_ => _.Name == "assemblyName")?.Value switch { #if NETFRAMEWORK DB2iSeriesAccessClientProviderAdapter.AssemblyName => DB2iSeriesProviderType.AccessClient, #endif DB2.DB2ProviderAdapter.AssemblyName => DB2iSeriesProviderType.DB2, OleDbProviderAdapter.AssemblyName => DB2iSeriesProviderType.OleDb, OdbcProviderAdapter.AssemblyName => DB2iSeriesProviderType.Odbc, null => DB2iSeriesProviderOptions.Defaults.ProviderType, var x => throw ExceptionHelper.InvalidAssemblyName(x) }; var mapGuidAsString = attributes.Any(x => x.Name == Constants.ProviderFlags.MapGuidAsString); return DB2iSeriesTools.GetDataProvider(version, providerType, new DB2iSeriesMappingOptions(mapGuidAsString)); } } }
36.421053
112
0.746387
[ "MIT" ]
LinqToDB4iSeries/Linq2DB4iSeries
Source/ISeriesProvider/DB2iSeriesFactory.cs
1,386
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace WInterop { /// <summary> /// Contains definitions for various fixed size strings for creating blittable /// structs. Provides easy string property access. Set strings are always null /// terminated and will truncate if too large. /// /// Usage: Instead of "fixed char _buffer[12]" use "FixedBuffer.Size12 _buffer" /// </summary> public static unsafe class FixedString { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size12 { private const int Size = 12; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size14 { private const int Size = 14; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size16 { private const int Size = 16; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size32 { private const int Size = 32; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size64 { private const int Size = 64; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size128 { private const int Size = 128; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size256 { private const int Size = 256; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct Size260 { private const int Size = 260; private fixed char _buffer[Size]; public Span<char> Buffer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { fixed (char* c = _buffer) return new Span<char>(c, Size); } } } } }
39.945055
157
0.632187
[ "MIT" ]
JeremyKuhne/WInterop
src/WInterop.Desktop/Support.Root/FixedString.cs
3,637
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Minotaur.Core { public interface IUpdateable { void Update(GameClock clock); } }
14.538462
33
0.746032
[ "MIT" ]
mlunnay/minotaur
minotaur/src/Core/IUpdateable.cs
191
C#