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.Diagnostics; using System.IO; using System.Linq; using Celeste.Mod; using Ionic.Zip; namespace PlattekMod.EverestInterop { public static class StudioHelper { private const string StudioName = "PlattenTek"; private static EverestModuleMetadata Metadata => PlattenTekModule.Instance.Metadata; private static string StudioNameWithExe => StudioName + ".exe"; private static string StudioNameInZip => $"net452/{StudioNameWithExe}"; private static string CopiedStudioExePath => Path.Combine(Everest.PathGame, StudioNameWithExe); public static void Initialize() { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { ExtractStudio(out bool studioProcessWasKilled); LaunchStudioAtBoot(studioProcessWasKilled); } } private static void ExtractStudio(out bool studioProcessWasKilled) { studioProcessWasKilled = false; if (!File.Exists(CopiedStudioExePath) || CheckNewerStudio()) { try { Process studioProcess = Process.GetProcesses().FirstOrDefault(process => process.ProcessName.Contains("PlattenTek")); if (studioProcess != null) { studioProcess.Kill(); studioProcess.WaitForExit(50000); } if (studioProcess?.HasExited == false) { return; } if (studioProcess?.HasExited == true) { studioProcessWasKilled = true; } if (!string.IsNullOrEmpty(Metadata.PathArchive)) { using (ZipFile zip = ZipFile.Read(Metadata.PathArchive)) { if (zip.EntryFileNames.Contains(StudioNameWithExe)) { foreach (ZipEntry entry in zip.Entries) { if (entry.FileName.StartsWith(StudioName) && !entry.FileName.Contains(".dll")) { entry.Extract(Everest.PathGame, ExtractExistingFileAction.OverwriteSilently); } } } } } else if (!string.IsNullOrEmpty(Metadata.PathDirectory)) { string[] files = Directory.GetFiles(Metadata.PathDirectory, "*", SearchOption.AllDirectories); if (files.Any(filePath => filePath.EndsWith(StudioNameWithExe))) { foreach (string sourceFile in files) { string fileName = Path.GetFileName(sourceFile); if (fileName.StartsWith(StudioName) && !fileName.Contains(".dll")) { string destFile = Path.Combine(Everest.PathGame, fileName); File.Copy(sourceFile, destFile, true); } } } } PlattenTekModule.Settings.StudioLastModifiedTime = File.GetLastWriteTime(CopiedStudioExePath); PlattenTekModule.Instance.SaveSettings(); } catch (UnauthorizedAccessException e) { Logger.Log("PlattenTekModule", "Failed to extract studio. UnauthorizedAccessException"); Logger.LogDetailed(e); } catch (Exception e) { Logger.Log("PlattenTekModule", "Failed to extract studio. Unknown Exception"); Logger.LogDetailed(e); } } else { foreach (string file in Directory.GetFiles(Everest.PathGame, "*.PendingOverwrite")) { File.Delete(file); } } } private static bool CheckNewerStudio() { if (!PlattenTekModule.Settings.AutoExtractNewStudio) { return false; } DateTime modifiedTime = new(); if (!string.IsNullOrEmpty(Metadata.PathArchive)) { using (ZipFile zip = ZipFile.Read(Metadata.PathArchive)) { if (zip.Entries.FirstOrDefault(zipEntry => zipEntry.FileName == StudioNameWithExe) is { } studioZipEntry) { modifiedTime = studioZipEntry.LastModified; } } } else if (!string.IsNullOrEmpty(Metadata.PathDirectory)) { string[] files = Directory.GetFiles(Metadata.PathDirectory); if (files.FirstOrDefault(filePath => filePath.EndsWith(StudioNameWithExe)) is { } studioFilePath) { modifiedTime = File.GetLastWriteTime(studioFilePath); } } return modifiedTime.CompareTo(PlattenTekModule.Settings.StudioLastModifiedTime) > 0; } private static void LaunchStudioAtBoot(bool studioProcessWasKilled) { if (PlattenTekModule.Settings.LaunchStudioAtBoot || studioProcessWasKilled) { try { Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { if (process.ProcessName.Contains(StudioName)) { return; } } if (File.Exists(CopiedStudioExePath)) { Process.Start(CopiedStudioExePath); } } catch (Exception e) { Logger.Log("PlattenTekModule", "Failed to launch studio at boot."); Logger.LogDetailed(e); } } } } }
43.932836
127
0.521828
[ "MIT" ]
IsaGoodFriend/PlattenTek
PlattenTek-Everest/EverestInterop/StudioHelper.cs
5,887
C#
namespace ProActive.SharePoint.Build.Services.Strings { public static class Files { public const string AppManifest = "AppManifest.xml"; public const string WebPartProduct = "product.json"; public const string WebPartMainModuleFileName = "module.webpart.main.js"; public const string ApplicationCustomizerMainModuleFileName = "module.application-customizer.main.js"; public const string LibraryMainModuleFileName = "module.library.main.js"; } }
41.5
110
0.732932
[ "Apache-2.0" ]
phaetto/proactive-sharepoint-build
ProActive.SharePoint.Build/Services/Strings/Files.cs
500
C#
using System; using System.Text; using System.Transactions; using Rhino.Queues; using Rhino.Queues.Model; using Rhino.ServiceBus.DataStructures; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Transport; namespace Rhino.ServiceBus.RhinoQueues { public class ErrorAction { private readonly int numberOfRetries; private readonly Hashtable<string, ErrorCounter> failureCounts = new Hashtable<string, ErrorCounter>(); public ErrorAction(int numberOfRetries) { this.numberOfRetries = numberOfRetries; } public void Init(ITransport transport) { transport.MessageSerializationException += Transport_OnMessageSerializationException; transport.MessageProcessingFailure += Transport_OnMessageProcessingFailure; transport.MessageProcessingCompleted += Transport_OnMessageProcessingCompleted; transport.MessageArrived += Transport_OnMessageArrived; } private bool Transport_OnMessageArrived(CurrentMessageInformation information) { var info = (RhinoQueueCurrentMessageInformation)information; ErrorCounter val = null; failureCounts.Read(reader => reader.TryGetValue(info.TransportMessageId, out val)); if (val == null || val.FailureCount < numberOfRetries) return false; var result = false; failureCounts.Write(writer => { if (writer.TryGetValue(info.TransportMessageId, out val) == false) return; info.Queue.MoveTo(SubQueue.Errors.ToString(), info.TransportMessage); info.Queue.EnqueueDirectlyTo(SubQueue.Errors.ToString(), new MessagePayload { Data = val.ExceptionText == null ? null : Encoding.Unicode.GetBytes(val.ExceptionText), Headers = { {"correlation-id", info.TransportMessageId}, {"retries", val.FailureCount.ToString()} } }); result = true; }); return result; } private void Transport_OnMessageSerializationException(CurrentMessageInformation information, Exception exception) { var info = (RhinoQueueCurrentMessageInformation)information; failureCounts.Write(writer => writer.Add(info.TransportMessageId, new ErrorCounter { ExceptionText = exception == null ? null : exception.ToString(), FailureCount = numberOfRetries + 1 })); using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew)) { info.Queue.MoveTo(SubQueue.Errors.ToString(), info.TransportMessage); info.Queue.EnqueueDirectlyTo(SubQueue.Errors.ToString(), new MessagePayload { Data = exception == null ? null : Encoding.Unicode.GetBytes(exception.ToString()), Headers = { {"correlation-id", info.TransportMessageId}, {"retries", "1"} } }); tx.Complete(); } } private void Transport_OnMessageProcessingCompleted(CurrentMessageInformation information, Exception ex) { if (ex != null) return; ErrorCounter val = null; failureCounts.Read(reader => reader.TryGetValue(information.TransportMessageId, out val)); if (val == null) return; failureCounts.Write(writer => writer.Remove(information.TransportMessageId)); } private void Transport_OnMessageProcessingFailure(CurrentMessageInformation information, Exception exception) { failureCounts.Write(writer => { ErrorCounter errorCounter; if (writer.TryGetValue(information.TransportMessageId, out errorCounter) == false) { errorCounter = new ErrorCounter { ExceptionText = exception == null ? null : exception.ToString(), FailureCount = 0 }; writer.Add(information.TransportMessageId, errorCounter); } errorCounter.FailureCount += 1; }); } private class ErrorCounter { public string ExceptionText; public int FailureCount; } } }
38.596774
123
0.570832
[ "BSD-3-Clause" ]
EzyWebwerkstaden/rhino-esb
Rhino.ServiceBus.RhinoQueues/RhinoQueues/ErrorAction.cs
4,786
C#
using System; using System.Collections.Generic; using System.Text; namespace ByteStream.Interfaces { public interface IByteStream { int Offset { get; } int Length { get; } SerializationMode Mode { get; } void Serialize<T>(ref T value) where T : unmanaged; void SerializeString(ref string value, Encoding encoding); } }
20.833333
66
0.653333
[ "MIT" ]
DennisCorvers/ByteStream
ByteStream/ByteStream/Interfaces/IByteStream.cs
377
C#
using CaseManagement.HumanTask.Domains; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CaseManagement.HumanTask.Persistence.InMemory { public class HumanTaskDefCommandRepository : IHumanTaskDefCommandRepository { private readonly ConcurrentBag<HumanTaskDefinitionAggregate> _humanTaskDefs; public HumanTaskDefCommandRepository(ConcurrentBag<HumanTaskDefinitionAggregate> humanTaskDefs) { _humanTaskDefs = humanTaskDefs; } public Task<bool> Add(HumanTaskDefinitionAggregate humanTaskDef, CancellationToken token) { _humanTaskDefs.Add(humanTaskDef); return Task.FromResult(true); } public Task<bool> Update(HumanTaskDefinitionAggregate humanTaskDef, CancellationToken token) { var r = _humanTaskDefs.First(_ => _.AggregateId == humanTaskDef.AggregateId); _humanTaskDefs.Remove(r); _humanTaskDefs.Add((HumanTaskDefinitionAggregate)humanTaskDef.Clone()); return Task.FromResult(true); } public Task<bool> Delete(string name, CancellationToken token) { var record = _humanTaskDefs.FirstOrDefault(_ => _.Name == name); if (record == null) { return Task.FromResult(false); } _humanTaskDefs.Remove(record); return Task.FromResult(true); } public Task<int> SaveChanges(CancellationToken token) { return Task.FromResult(1); } } }
32.5
103
0.656615
[ "Apache-2.0" ]
lulzzz/CaseManagement
src/CaseManagement.HumanTask/Persistence/InMemory/HumanTaskDefCommandRepository.cs
1,627
C#
using System.Diagnostics.CodeAnalysis; namespace Gee.External.Capstone.Mips { /// <summary> /// MIPS Instruction Group Unique Identifier. /// </summary> [SuppressMessage("ReSharper", "IdentifierTypo")] [SuppressMessage("ReSharper", "InconsistentNaming")] public enum MipsInstructionGroupId { /// <summary> /// Indicates an invalid, or an uninitialized, instruction group. /// </summary> Invalid = 0, MIPS_GRP_JUMP, MIPS_GRP_CALL, MIPS_GRP_RET, MIPS_GRP_INT, MIPS_GRP_IRET, MIPS_GRP_PRIVILEGE, MIPS_GRP_BRANCH_RELATIVE, MIPS_GRP_BITCOUNT = 128, MIPS_GRP_DSP, MIPS_GRP_DSPR2, MIPS_GRP_FPIDX, MIPS_GRP_MSA, MIPS_GRP_MIPS32R2, MIPS_GRP_MIPS64, MIPS_GRP_MIPS64R2, MIPS_GRP_SEINREG, MIPS_GRP_STDENC, MIPS_GRP_SWAP, MIPS_GRP_MICROMIPS, MIPS_GRP_MIPS16MODE, MIPS_GRP_FP64BIT, MIPS_GRP_NONANSFPMATH, MIPS_GRP_NOTFP64BIT, MIPS_GRP_NOTINMICROMIPS, MIPS_GRP_NOTNACL, MIPS_GRP_NOTMIPS32R6, MIPS_GRP_NOTMIPS64R6, MIPS_GRP_CNMIPS, MIPS_GRP_MIPS32, MIPS_GRP_MIPS32R6, MIPS_GRP_MIPS64R6, MIPS_GRP_MIPS2, MIPS_GRP_MIPS3, MIPS_GRP_MIPS3_32, MIPS_GRP_MIPS3_32R2, MIPS_GRP_MIPS4_32, MIPS_GRP_MIPS4_32R2, MIPS_GRP_MIPS5_32R2, MIPS_GRP_GP32BIT, MIPS_GRP_GP64BIT } }
27.854545
77
0.625326
[ "MIT" ]
9ee1/Capstone.NET
Gee.External.Capstone/Mips/MipsInstructionGroupId.cs
1,534
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.Personalize; using Amazon.Personalize.Model; namespace Amazon.PowerShell.Cmdlets.PERS { /// <summary> /// Describes a recipe. /// /// /// <para> /// A recipe contains three items: /// </para><ul><li><para> /// An algorithm that trains a model. /// </para></li><li><para> /// Hyperparameters that govern the training. /// </para></li><li><para> /// Feature transformation information for modifying the input data before training. /// </para></li></ul><para> /// Amazon Personalize provides a set of predefined recipes. You specify a recipe when /// you create a solution with the <a>CreateSolution</a> API. <code>CreateSolution</code> /// trains a model by using the algorithm in the specified recipe and a training dataset. /// The solution, when deployed as a campaign, can provide recommendations using the <a href="https://docs.aws.amazon.com/personalize/latest/dg/API_RS_GetRecommendations.html">GetRecommendations</a> /// API. /// </para> /// </summary> [Cmdlet("Get", "PERSRecipe")] [OutputType("Amazon.Personalize.Model.Recipe")] [AWSCmdlet("Calls the AWS Personalize DescribeRecipe API operation.", Operation = new[] {"DescribeRecipe"}, SelectReturnType = typeof(Amazon.Personalize.Model.DescribeRecipeResponse))] [AWSCmdletOutput("Amazon.Personalize.Model.Recipe or Amazon.Personalize.Model.DescribeRecipeResponse", "This cmdlet returns an Amazon.Personalize.Model.Recipe object.", "The service call response (type Amazon.Personalize.Model.DescribeRecipeResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetPERSRecipeCmdlet : AmazonPersonalizeClientCmdlet, IExecutor { #region Parameter RecipeArn /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of the recipe to describe.</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 RecipeArn { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Recipe'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Personalize.Model.DescribeRecipeResponse). /// Specifying the name of a property of type Amazon.Personalize.Model.DescribeRecipeResponse will result in that property being returned. /// 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; } = "Recipe"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the RecipeArn parameter. /// The -PassThru parameter is deprecated, use -Select '^RecipeArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^RecipeArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); 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.Personalize.Model.DescribeRecipeResponse, GetPERSRecipeCmdlet>(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.RecipeArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.RecipeArn = this.RecipeArn; #if MODULAR if (this.RecipeArn == null && ParameterWasBound(nameof(this.RecipeArn))) { WriteWarning("You are passing $null as a value for parameter RecipeArn 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.Personalize.Model.DescribeRecipeRequest(); if (cmdletContext.RecipeArn != null) { request.RecipeArn = cmdletContext.RecipeArn; } 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.Personalize.Model.DescribeRecipeResponse CallAWSServiceOperation(IAmazonPersonalize client, Amazon.Personalize.Model.DescribeRecipeRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Personalize", "DescribeRecipe"); try { #if DESKTOP return client.DescribeRecipe(request); #elif CORECLR return client.DescribeRecipeAsync(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 RecipeArn { get; set; } public System.Func<Amazon.Personalize.Model.DescribeRecipeResponse, GetPERSRecipeCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Recipe; } } }
44.875576
280
0.612549
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/Personalize/Basic/Get-PERSRecipe-Cmdlet.cs
9,738
C#
using FluentValidation; namespace Lab.Business.Models.Validations { public class EnderecoValidation : AbstractValidator<Endereco> { public EnderecoValidation() { RuleFor(c => c.Logradouro) .NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido") .Length(2, 200).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres"); RuleFor(c => c.Bairro) .NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido") .Length(2, 100).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres"); RuleFor(c => c.Cep) .NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido") .Length(8).WithMessage("O campo {PropertyName} precisa ter {MaxLength} caracteres"); RuleFor(c => c.Cidade) .NotEmpty().WithMessage("A campo {PropertyName} precisa ser fornecida") .Length(2, 100).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres"); RuleFor(c => c.Estado) .NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido") .Length(2, 50).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres"); RuleFor(c => c.Numero) .NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido") .Length(1, 50).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres"); } } }
49.352941
125
0.620381
[ "MIT" ]
edulima2412/mvc-completa
src/Lab.Business/Models/Validations/EnderecoValidation.cs
1,680
C#
using static BuckarooSdk.Constants.Services; namespace BuckarooSdk.Services.PayPal.Push { public class PayPalPayPush : ActionPush { public override ServiceNames ServiceNames => ServiceNames.PayPal; public string PayerStatus { get; set; } public string NoteText { get; set; } public string PayerEmail { get; set; } public string PayerCountry { get; set; } public string PayerFirstName { get; set; } public string PayerLastName { get; set; } public string PayerTransactionId { get; set; } } }
28.5
67
0.738791
[ "MIT" ]
buckaroo-it/BuckarooSdk_DotNet
BuckarooSdk/Services/PayPal/Push/PayPalPayPush.cs
515
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Imaging; namespace Ev3Controller.Model { public enum ConnectionState { /// <summary> /// Device is disconnected. /// </summary> Disconnected, /// <summary> /// Canceling the connection. /// </summary> Disconnecting, /// <summary> /// Establishing device connection. /// </summary> Connecting, /// <summary> /// Established device connection. /// </summary> Connected, /// <summary> /// Sending data to device. /// </summary> Sending, /// <summary> /// Receiving data from device. /// </summary> Receiving, /// <summary> /// Connection state with device is unknown. /// </summary> Unknown, }; /// <summary> /// Represents the connection state with device. /// </summary> public class ConnectState { #region Private fields and constants (in a region) protected static Dictionary<ConnectionState, string> ResourceDictionary = new Dictionary<ConnectionState, string> { { ConnectionState.Disconnected, @"../Resource/pict/disconnected.png" }, { ConnectionState.Disconnecting,@"../Resource/pict/disconnecting.png" }, { ConnectionState.Connecting, @"../Resource/pict/connecting.png" }, { ConnectionState.Connected, @"../Resource/pict/connected.png" }, { ConnectionState.Sending, @"../Resource/pict/connected.png" }, { ConnectionState.Receiving, @"../Resource/pict/connected.png" }, { ConnectionState.Unknown, @"../Resource/pict/disconnected.png" }, }; #endregion #region Constructors and the Finalizer /// <summary> /// Constructor /// </summary> /// <param name="State">Connection state to set to State property.</param> public ConnectState(ConnectionState State) { this.State = State; this.StateImage = ConnectState.ResourceDictionary[this.State]; } #endregion #region Public properties /// <summary> /// Represent state of connection with device. /// </summary> public ConnectionState State { get; protected set; } /// <summary> /// Bitmap image which shows state. /// </summary> public string StateImage { get; protected set; } #endregion #region Other methods and private properties in calling order. #endregion } }
31.910112
85
0.554225
[ "MIT" ]
CountrySideEngineer/Ev3Controller
dev/src/Ev3Controller/Model/ConnectState.cs
2,842
C#
// Copyright (c) Isaiah Williams. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Store.PartnerCenter.Analytics { using System; using System.Threading; using System.Threading.Tasks; using Models; using Models.Analytics; /// <summary> /// Implements the operations on partner licenses usage insights collection. /// </summary> internal class PartnerLicensesUsageInsightsCollectionOperations : BasePartnerComponent<string>, IPartnerLicensesUsageInsightsCollection { /// <summary> /// Initializes a new instance of the <see cref="PartnerLicensesUsageInsightsCollectionOperations" /> class. /// </summary> /// <param name="rootPartnerOperations">The root partner operations instance.</param> public PartnerLicensesUsageInsightsCollectionOperations(IPartner rootPartnerOperations) : base(rootPartnerOperations) { } /// <summary> /// Retrieves the collection of partner's licenses' usage insights. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Collection of licenses usage insights</returns> public async Task<ResourceCollection<PartnerLicensesUsageInsights>> GetAsync(CancellationToken cancellationToken = default) { return await Partner.ServiceClient.GetAsync<ResourceCollection<PartnerLicensesUsageInsights>>( new Uri( $"/{PartnerService.Instance.ApiVersion}/{PartnerService.Instance.Configuration.Apis.PartnerLicensesUsageInsights.Path}", UriKind.Relative), cancellationToken).ConfigureAwait(false); } } }
47.175
152
0.697933
[ "MIT" ]
erickbp/partner-center-dotnet
src/PartnerCenter/Analytics/PartnerLicensesUsageInsightsCollectionOperations.cs
1,889
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace InteropTypes.Graphics.Drawing { /// <summary> /// Represents a Camera transform in 2D space. /// </summary> [System.Diagnostics.DebuggerDisplay("")] public struct CameraTransform2D : IEquatable<CameraTransform2D> { #region constructors public static bool TryGetFromServiceProvider(Object obj, out CameraTransform2D cameraTransform) { if (obj is ISource source) { cameraTransform = source.GetCameraTransform2D(); return true; } if (obj is IServiceProvider provider) { if (provider.GetService(typeof(CameraTransform2D)) is CameraTransform2D ct2d) { cameraTransform = ct2d; return true; } if (provider.GetService(typeof(ISource)) is ISource ct2ds) { cameraTransform = ct2ds.GetCameraTransform2D(); return true; } } cameraTransform = default; return false; } /// <summary> /// Tries to get the physical render target size and returns it converted to virtual space. /// </summary> /// <param name="dc"></param> /// <param name="camera"></param> /// <returns></returns> public static bool TryGetOuterCamera(ICoreCanvas2D dc, out CameraTransform2D camera) { camera = default; if (!TryGetRenderTargetInfo(dc, out var vinfo)) return false; if (vinfo == null) return false; var w = vinfo.PixelsWidth; var h = vinfo.PixelsHeight; if (w <= 0 || h <= 0) return false; // query for any in between transformations if (dc is ITransformer2D xform) { // transform points from physical screen space to virtual space Span<Point2> points = stackalloc Point2[3]; points[0] = (0, 0); points[1] = (w, 0); points[2] = (0, h); xform.TransformInverse(points); // create matrix from points var dx = Point2.Normalize(points[1] - points[0], out var ww); var dy = Point2.Normalize(points[2] - points[0], out var hh); var m = new Matrix3x2(dx.X, dx.Y, dy.X, dy.Y, points[0].X, points[0].Y); // create camera camera = new CameraTransform2D(m, new Vector2(ww, hh), false); } else { camera = Create(Matrix3x2.Identity, new Vector2(w, h)); } return true; } public static CameraTransform2D Create(Matrix3x2 worldMatrix) { return new CameraTransform2D(worldMatrix, null, null); } public static CameraTransform2D Create(Matrix3x2 worldMatrix, Point2 virtualSize) { return new CameraTransform2D(worldMatrix, virtualSize.XY, true); } public static CameraTransform2D Create(Matrix3x2 worldMatrix, Point2 virtualSize, bool keepAspectRatio) { return new CameraTransform2D(worldMatrix, virtualSize.XY, keepAspectRatio); } private CameraTransform2D(Matrix3x2 worldMatrix, Vector2? virtualSize, bool? keepAspectRatio) { nameof(worldMatrix).GuardIsFinite(worldMatrix); this.WorldMatrix = worldMatrix; this.VirtualSize = virtualSize; this.KeepAspectRatio = keepAspectRatio; } #endregion #region constants public static CameraTransform2D Empty => default; public static CameraTransform2D Identity => new CameraTransform2D(Matrix3x2.Identity, null, null); #endregion #region data /// <summary> /// Transform Matrix of the camera in World Space. /// </summary> /// <remarks> /// The camera looks into the negative Z /// </remarks> public Matrix3x2 WorldMatrix; /// <summary> /// Represents the world's scale size onscreen. /// </summary> /// <remarks> /// X and Y values cannot be zero, but they can be negative to reverse the axis. /// </remarks> public Vector2? VirtualSize; /// <summary> /// true to keep aspect ratio /// </summary> public bool? KeepAspectRatio; /// <inheritdoc/> public override int GetHashCode() { if (!IsInitialized) return 0; return WorldMatrix.GetHashCode() ^ VirtualSize.GetHashCode() ^ KeepAspectRatio.GetHashCode(); } /// <inheritdoc/> public override bool Equals(object obj) { return obj is CameraTransform2D other && Equals(other); } /// <inheritdoc/> public bool Equals(CameraTransform2D other) { if (!this.IsInitialized && !other.IsInitialized) return true; if (this.WorldMatrix != other.WorldMatrix) return false; if (this.VirtualSize != other.VirtualSize) return false; return true; } /// <inheritdoc/> public static bool operator ==(in CameraTransform2D a, in CameraTransform2D b) => a.Equals(b); /// <inheritdoc/> public static bool operator !=(in CameraTransform2D a, in CameraTransform2D b) => !a.Equals(b); #endregion #region properties public bool IsValid { get { if (!IsInitialized) return false; if (VirtualSize.HasValue) { if (VirtualSize.Value.X == 0) return false; if (VirtualSize.Value.Y == 0) return false; } return true; } } /// <summary> /// Gets a value indicating whether this object has been initialized. /// </summary> public bool IsInitialized => WorldMatrix.IsFiniteAndNotZero(); #endregion #region API public bool TryCreateFinalMatrix(ICoreCanvas2D dc, out Matrix3x2 finalMatrix) { finalMatrix = Matrix3x2.Identity; if (!TryGetRenderTargetInfo(dc, out var vinfo)) return false; if (vinfo == null) return false; int w = vinfo.PixelsWidth; int h = vinfo.PixelsHeight; if (w <= 0 || h <= 0) return false; finalMatrix = CreateFinalMatrix((vinfo.PixelsWidth, vinfo.PixelsHeight)); return true; } public static bool TryGetRenderTargetInfo(ICoreCanvas2D dc, out IRenderTargetInfo rtinfo) { rtinfo = null; // if this is a render target, return direct values. if (dc is IRenderTargetInfo vinfo0) { rtinfo = vinfo0; return true; } // query for the IRenderTargetInfo down the chain. if (!(dc is IServiceProvider srv)) return false; if (srv.GetService(typeof(IRenderTargetInfo)) is IRenderTargetInfo vinfo) { rtinfo = vinfo; return true; } return false; } public static CameraTransform2D Multiply(CameraTransform2D camera, in Matrix3x2 xform) { camera.WorldMatrix = camera.WorldMatrix * xform; return camera; } public static CameraTransform2D Multiply(in Matrix3x2 xform, CameraTransform2D camera) { camera.WorldMatrix = xform * camera.WorldMatrix; return camera; } public System.Drawing.RectangleF GetOuterBoundingRect() { var vs = VirtualSize ?? Vector2.One; Span<Vector2> points = stackalloc Vector2[4]; points[0] = Vector2.Transform(Vector2.Zero, WorldMatrix); points[1] = Vector2.Transform(new Vector2(vs.X,0), WorldMatrix); points[2] = Vector2.Transform(new Vector2(vs.X, vs.Y), WorldMatrix); points[3] = Vector2.Transform(new Vector2(0, vs.Y), WorldMatrix); bool first = true; System.Drawing.RectangleF bounds = default; foreach (var p in points) { var other = new System.Drawing.RectangleF(p.X, p.Y, 0, 0); bounds = first ? other : System.Drawing.RectangleF.Union(bounds, other); first = false; } return bounds; } public Matrix3x2 CreateFinalMatrix(Point2 physicalSize) { return CreateViewMatrix() * CreateViewportMatrix(physicalSize); } /// <summary> /// Gets the inverse of <see cref="WorldMatrix"/> /// </summary> /// <returns>A matrix.</returns> public Matrix3x2 CreateViewMatrix() { if (!WorldMatrix.IsFiniteAndNotZero()) throw new InvalidOperationException($"Invalid {nameof(WorldMatrix)}"); return !Matrix3x2.Invert(WorldMatrix, out Matrix3x2 viewMatrix) ? Matrix3x2.Identity : viewMatrix; } public Matrix3x2 CreateViewportMatrix(Point2 physicalSize) { return _CreateVirtualToPhysical(physicalSize.XY, this.VirtualSize ?? physicalSize.XY, this.KeepAspectRatio ?? false); } private static Matrix3x2 _CreateVirtualToPhysical(Vector2 physicalSize, Vector2 virtualSize, bool keepAspect) { if (virtualSize.X == 0 || virtualSize.Y == 0) throw new ArgumentException("Must not be zero", nameof(virtualSize)); if (physicalSize.X <= 0 || physicalSize.Y <= 0) throw new ArgumentException("Must be positive", nameof(virtualSize)); var ws = physicalSize.X / Math.Abs(virtualSize.X); var hs = physicalSize.Y / Math.Abs(virtualSize.Y); if (keepAspect) ws = hs; var xform = Matrix3x2.CreateScale(ws, hs); if (virtualSize.X < 0) xform.M11 *= -1; if (virtualSize.Y < 0) xform.M22 *= -1; var offsx = (physicalSize.X - virtualSize.X * hs) * 0.5f; var offsy = (physicalSize.Y - virtualSize.Y * hs) * 0.5f; return xform * Matrix3x2.CreateTranslation(offsx, offsy); } #endregion #region nested types public interface ISource { CameraTransform2D GetCameraTransform2D(); } #endregion } }
32.962963
139
0.563483
[ "MIT" ]
vpenades/InteropBitmaps
src/InteropTypes.Graphics.Drawing.Core/Types/CameraTransform2D.cs
10,682
C#
#region --- License & Copyright Notice --- /* Custom collections and collection extensions for .NET Copyright (c) 2018-2020 Jeevan James All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System.Linq; #if EXPLICIT using System; using System.Collections.Generic; using Collections.Net.Collection; namespace Collections.Net.List #else // ReSharper disable once CheckNamespace namespace System.Collections.Generic #endif { public static class ListExtensions { /// <summary> /// Populates each item in a <paramref name="list"/> with a specific <paramref name="value"/>. /// </summary> /// <typeparam name="T">The type of the elements of the list</typeparam> /// <param name="list">The collection to be populated.</param> /// <param name="value">The value with which to populate the collection.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> public static void Fill<T>(this IList<T> list, T value) { if (list == null) throw new ArgumentNullException(nameof(list)); if (list.Count == 0) return; for (int i = 0; i < list.Count; i++) list[i] = value; } /// <summary> /// Populates each item in a <paramref name="list"/> with the values from a <paramref name="generator"/> /// delegate. /// </summary> /// <typeparam name="T">The type of the elements of the list</typeparam> /// <param name="list">The collection to be populated.</param> /// <param name="generator">The delegate to generate the values for each item.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> public static void Fill<T>(this IList<T> list, Func<int, T> generator) { if (list == null) throw new ArgumentNullException(nameof(list)); if (list.Count == 0) return; if (generator == null) throw new ArgumentNullException(nameof(generator)); for (int i = 0; i < list.Count; i++) list[i] = generator(i); } /// <summary> /// Returns the index of the first element in a <paramref name="list"/> that matches the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The <paramref name="predicate"/> to check against.</param> /// <returns>The index of the element, if found; otherwise -1.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="predicate"/> is <c>null</c>.</exception> public static int IndexOf<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) { if (predicate(list[i])) return i; } return -1; } /// <summary> /// Returns all indices of elements in a <paramref name="list"/> that match the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The <paramref name="predicate"/> to check against.</param> /// <returns> /// A sequence of indices of the matches elements in the list, if any are found; otherwise -1. /// </returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="predicate"/> is <c>null</c>.</exception> public static IEnumerable<int> IndexOfAll<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) { if (predicate(list[i])) yield return i; } } public static void InsertRange<T>(this IList<T> list, int index, params T[] items) { InsertRange(list, index, (IEnumerable<T>)items); } public static void InsertRange<T>(this IList<T> list, int index, IEnumerable<T>? items) { if (list == null) throw new ArgumentNullException(nameof(list)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (items == null) return; if (index >= list.Count) list.AddRange(items); else { int originalCount = list.Count; foreach (T item in items) list.Insert(index + (list.Count - originalCount), item); } } public static void InsertRange<T>(this IList<T> list, int index, IEnumerable<T> items, Func<T, bool> predicate) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); InsertRange(list, index, items.Where(predicate)); } public static void InsertRange<TDest, TSource>(this IList<TDest> list, int index, IEnumerable<TSource> items, Func<TSource, TDest> converter) { if (converter == null) throw new ArgumentNullException(nameof(converter)); InsertRange(list, index, items.Select(converter)); } public static void InsertRange<TDest, TSource>(this IList<TDest> list, int index, IEnumerable<TSource> items, Func<TSource, bool> predicate, Func<TSource, TDest> converter, Func<TDest, bool>? afterConvertPredicate = null) { if (predicate == null) throw new ArgumentNullException(nameof(predicate)); if (converter == null) throw new ArgumentNullException(nameof(converter)); IEnumerable<TDest> convertedItems = items.Where(predicate).Select(converter); if (afterConvertPredicate != null) convertedItems = convertedItems.Where(afterConvertPredicate); InsertRange(list, index, convertedItems); } /// <summary> /// Returns the index of the last element in a <paramref name="list"/> that matches the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The <paramref name="predicate"/> to check against.</param> /// <returns>The index of the element, if found; otherwise -1.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="predicate"/> is <c>null</c>.</exception> public static int LastIndexOf<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = list.Count - 1; i >= 0; i--) { if (predicate(list[i])) return i; } return -1; } public static IEnumerable<T> Random<T>(this IList<T> list, int count) { if (list == null) throw new ArgumentNullException(nameof(list)); if (list.Count == 0) yield break; if (count < 1) throw new ArgumentOutOfRangeException(nameof(count)); var rng = new Rng(list.Count); for (int i = 0; i < count; i++) { int index = rng.Next(); yield return list[index]; } } /// <summary> /// Removes all elements from the <paramref name="list"/> that satisfy the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The predicate delegate to check against.</param> /// <returns>The number of elements removed.</returns> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="predicate"/> is <c>null</c>.</exception> public static int RemoveAll<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); int count = 0; for (int i = list.Count - 1; i >= 0; i--) { if (predicate(list[i])) { list.RemoveAt(i); count++; } } return count; } /// <summary> /// Removes the first element from the <paramref name="list"/> that satisfies the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The predicate delegate to check against.</param> /// <returns><c>true</c> if an element was found and removed; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="predicate"/> is <c>null</c>.</exception> public static bool RemoveFirst<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) { if (predicate(list[i])) { list.RemoveAt(i); return true; } } return false; } /// <summary> /// Removes the last element from the <paramref name="list"/> that satisfies the specified /// <paramref name="predicate"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="predicate">The predicate delegate to check against.</param> /// <returns><c>true</c> if an element was found and removed; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="predicate"/> is <c>null</c>.</exception> public static bool RemoveLast<T>(this IList<T> list, Func<T, bool> predicate) { if (list == null) throw new ArgumentNullException(nameof(list)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); for (int i = list.Count - 1; i >= 0; i--) { if (predicate(list[i])) { list.RemoveAt(i); return true; } } return false; } /// <summary> /// Shuffles the elements of the <paramref name="list"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="iterations">The number of times to repeat the shuffle operation.</param> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if the <paramref name="iterations"/> is less than one.</exception> public static void ShuffleInplace<T>(this IList<T> list, int iterations = 1) { if (list == null) throw new ArgumentNullException(nameof(list)); if (iterations < 1) throw new ArgumentOutOfRangeException(nameof(iterations)); var rng = new Rng(list.Count); for (int iteration = 0; iteration < iterations; iteration++) { for (int i = 0; i < list.Count; i++) { int index1 = rng.Next(); int index2 = rng.Next(); T temp = list[index1]; list[index1] = list[index2]; list[index2] = temp; } } } /// <summary> /// Returns overlapping chunks of the specified <paramref name="chunkSize"/>. /// </summary> /// <typeparam name="T">The type of the elements of list.</typeparam> /// <param name="list">The list.</param> /// <param name="chunkSize">The size of the chunks.</param> /// <returns>Collection of overlapping chunks.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="list"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="chunkSize"/> is less than one. /// </exception> public static IEnumerable<IList<T>> SlidingChunk<T>(this IList<T> list, int chunkSize) { if (list == null) throw new ArgumentNullException(nameof(list)); if (chunkSize < 1) throw new ArgumentOutOfRangeException(nameof(chunkSize)); if (chunkSize > list.Count) chunkSize = list.Count; int upperLimit = Math.Max(0, list.Count - chunkSize); for (int i = 0; i <= upperLimit; i++) { var chunk = new T[chunkSize]; for (int j = i; j < i + chunkSize; j++) chunk[j - i] = list[j]; yield return chunk; } } } }
42.80914
131
0.554474
[ "Apache-2.0" ]
JeevanJames/Collections
src/Collections/ListExtensions.cs
15,927
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace SitemapAspNet.Extensions { /// <summary> /// Extension class for <see cref="ICustomAttributeProvider" />. /// </summary> [CLSCompliant(true)] public static class ICustomAttributeProviderExtensions { #region Methods section. /// <summary> /// Return attributes by type. /// </summary> /// <typeparam name="T">Attributes type.</typeparam> /// <param name="customAttributeProvider">Attribute.</param> /// <returns>Attributes.</returns> /// <exception cref="ArgumentNullException">Throw if <paramref name="customAttributeProvider" /> is null.</exception> public static IEnumerable<T> GetCustomAttributesByType<T>(this ICustomAttributeProvider customAttributeProvider) where T : class { if (customAttributeProvider == null) { throw new ArgumentNullException("customAttributeProvider"); } return from customAttribute in customAttributeProvider.GetCustomAttributes(true).OfType<T>() select customAttribute; } #endregion Methods section. } }
34.243243
125
0.637727
[ "MIT" ]
cyrilschumacher/SitemapAspNet
SitemapAspNet/Extensions/ICustomAttributeProviderExtensions.cs
1,269
C#
// Copyright (c) Nate McMaster. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace McMaster.Extensions.CommandLineUtils { /// <summary> /// Represents a subcommand. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class SubcommandAttribute : Attribute { /// <summary> /// Initializes a new instance of <see cref="SubcommandAttribute" />. /// </summary> /// <param name="name">The name of the subcommand</param> /// <param name="commandType">The type of the subcommand.</param> public SubcommandAttribute(string name, Type commandType) { CommandType = commandType; Name = name; } /// <summary> /// The name of the subcommand. /// </summary> public string Name { get; set; } /// <summary> /// The type of the subcommand. /// </summary> public Type CommandType { get; set; } internal void Configure(CommandLineApplication app) { if (string.IsNullOrEmpty(Name)) { throw new ArgumentException(Strings.IsNullOrEmpty, nameof(Name)); } app.Name = Name; } } }
29.804348
111
0.582786
[ "Apache-2.0" ]
adamskt/CommandLineUtils
src/CommandLineUtils/Attributes/SubcommandAttribute.cs
1,371
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Its.Recipes; using Microsoft.MockService; using Microsoft.MockService.Extensions.ODataV4; using Vipr.Core; using Xunit; namespace CSharpWriterUnitTests { public class Given_an_OdcmClass_Entity_Collection_AddAsync_Method : EntityTestBase { private MockService _serviceMock; public Given_an_OdcmClass_Entity_Collection_AddAsync_Method() { Init(); } [Fact] public void When_the_entity_is_null_then_AddAsync_POSTs_to_the_EntitySet_and_updates_the_added_instance() { var keyValues = Class.GetSampleKeyArguments().ToArray(); using (_serviceMock = new MockService() .SetupPostEntity(TargetEntity, keyValues)) { var collection = _serviceMock .GetDefaultContext(Model) .CreateCollection(CollectionType, ConcreteType, TargetEntity.Class.GetDefaultEntitySetPath()); var instance = Activator.CreateInstance(ConcreteType); var task = collection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new[] { instance, false }); task.Wait(); instance.ValidatePropertyValues(keyValues); } } [Fact] public void When_the_entity_is_not_null_then_AddAsync_POSTs_to_the_Entitys_canoncial_Uri_property_and_updates_the_added_instance() { var parentKeyValues = Class.GetSampleKeyArguments().ToArray(); var navPropertyName = Class.NavigationProperties().First(p => p.Type == Class && p.IsCollection).Name; var navPropertyPath = string.Format("{0}/{1}", TargetEntity.Class.GetDefaultEntityPath(parentKeyValues), navPropertyName); var childKeyValues = Class.GetSampleKeyArguments().ToArray(); using (_serviceMock = new MockService() .SetupPostEntity(TargetEntity, parentKeyValues) .OnPostEntityRequest(navPropertyPath) .RespondWithCreateEntity(Class.GetDefaultEntitySetName(), Class.GetSampleJObject(childKeyValues))) { var parentEntity = Activator.CreateInstance(ConcreteType); var childEntity = Activator.CreateInstance(ConcreteType); var entitySetCollection = _serviceMock .GetDefaultContext(Model) .CreateCollection(CollectionType, ConcreteType, TargetEntity.Class.GetDefaultEntitySetPath()); var navigationPropertyCollection = entitySetCollection .Context .CreateCollection(CollectionType, ConcreteType, navPropertyName, parentEntity); var parentTask = entitySetCollection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new[] { parentEntity, false }); parentTask.Wait(); var childTask = navigationPropertyCollection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new object[] { childEntity, false }); childTask.Wait(); childEntity.ValidatePropertyValues(childKeyValues); } } [Fact] public void When_the_entity_is_not_null_and_the_property_path_is_not_a_single_segment_then_AddAsync_POSTs_to_the_Entitys_canoncial_Uri_property_and_updates_the_added_instance() { var parentKeyValues = Class.GetSampleKeyArguments().ToArray(); var navPropertyName = Class.NavigationProperties().First(p => p.Type == Class && p.IsCollection).Name; var navPropertyPath = string.Format("{0}/{1}", TargetEntity.Class.GetDefaultEntityPath(parentKeyValues), navPropertyName); var childKeyValues = Class.GetSampleKeyArguments().ToArray(); using (_serviceMock = new MockService() .SetupPostEntity(TargetEntity, parentKeyValues) .OnPostEntityRequest(navPropertyPath) .RespondWithCreateEntity(TargetEntity.Class.GetDefaultEntitySetName(), Class.GetSampleJObject(childKeyValues))) { var parentEntity = Activator.CreateInstance(ConcreteType); var childEntity = Activator.CreateInstance(ConcreteType); var entitySetCollection = _serviceMock .GetDefaultContext(Model) .CreateCollection(CollectionType, ConcreteType, TargetEntity.Class.GetDefaultEntitySetPath()); var navigationPropertyCollection = entitySetCollection .Context .CreateCollection(CollectionType, ConcreteType, Any.String() + "/" + navPropertyName, parentEntity); var parentTask = entitySetCollection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new[] { parentEntity, false }); parentTask.Wait(); var childTask = navigationPropertyCollection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new object[] { childEntity, false }); childTask.Wait(); childEntity.ValidatePropertyValues(childKeyValues); } } [Fact] public void When_dont_save_is_true_then_the_server_is_not_called_until_Context_SaveChangesAsync_is_invoked() { var keyValues = Class.GetSampleKeyArguments().ToArray(); using (_serviceMock = new MockService() .SetupPostEntity(TargetEntity, keyValues)) { var collection = _serviceMock .GetDefaultContext(Model) .CreateCollection(CollectionType, ConcreteType, TargetEntity.Class.GetDefaultEntitySetPath()); var instance = Activator.CreateInstance(ConcreteType); var task = collection.InvokeMethod<Task>("Add" + Class.Name + "Async", args: new[] { instance, true }); task.Wait(); foreach (var keyValue in keyValues) { instance.GetPropertyValue(keyValue.Item1) .Should().Be(null); } task = collection.Context.SaveChangesAsync(); task.Wait(); instance.ValidatePropertyValues(keyValues); } } } }
43.276316
184
0.633323
[ "MIT" ]
OfficeDev/Vipr
test/CSharpWriterUnitTests/Given_an_OdcmClass_Entity_Collection_AddAsync_Method.cs
6,580
C#
// WARNING // // This file has been generated automatically by Xamarin Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace ApiDemoIos { [Register ("ApiDemoIosViewController")] partial class ApiDemoIosViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton batteryButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton commissionButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton configureButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel connectionStateLabel { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton InfoButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UISwitch inventorySwitch { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton readButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UITableView tableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton writeButton { get; set; } [Action ("batteryButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void batteryButton_TouchUpInside (UIButton sender); [Action ("commissionButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void commissionButton_TouchUpInside (UIButton sender); [Action ("configureButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void configureButton_TouchUpInside (UIButton sender); [Action ("InfoButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void InfoButton_TouchUpInside (UIButton sender); [Action ("inventorySwitch_ValueChanged:")] [GeneratedCode ("iOS Designer", "1.0")] partial void inventorySwitch_ValueChanged (UISwitch sender); [Action ("readButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void readButton_TouchUpInside (UIButton sender); [Action ("writeButton_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void writeButton_TouchUpInside (UIButton sender); void ReleaseDesignerOutlets () { if (batteryButton != null) { batteryButton.Dispose (); batteryButton = null; } if (commissionButton != null) { commissionButton.Dispose (); commissionButton = null; } if (configureButton != null) { configureButton.Dispose (); configureButton = null; } if (connectionStateLabel != null) { connectionStateLabel.Dispose (); connectionStateLabel = null; } if (InfoButton != null) { InfoButton.Dispose (); InfoButton = null; } if (inventorySwitch != null) { inventorySwitch.Dispose (); inventorySwitch = null; } if (readButton != null) { readButton.Dispose (); readButton = null; } if (tableView != null) { tableView.Dispose (); tableView = null; } if (writeButton != null) { writeButton.Dispose (); writeButton = null; } } } }
25.860656
84
0.68019
[ "MIT" ]
eclipsed4utoo/GrokBinding
Components/ugrokitapi-1.7.3/samples/ApiDemoIos/ApiDemoIosViewController.designer.cs
3,155
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticleSpawner : MonoBehaviour { public GameObject particle; public int spawnSize; public float spawnDistance; public float rotateSpeed, moveSpeed; private List<Transform> particles = new List<Transform>(); void Start() { spawnSize = HuygensPrinciple.instance.size; spawnDistance = HuygensPrinciple.instance.distance; RespawnParticles(false); } public void RespawnParticles(bool destroyOldOnes) { this.transform.rotation = Quaternion.identity; if(destroyOldOnes) { foreach(Transform particle in particles) { Destroy(particle.gameObject); } } particles = new List<Transform>(); for(int i=0; i<spawnSize; i++) { GameObject clone = Instantiate(particle, this.transform.position+new Vector3(i*spawnDistance, 0f, 0f)+new Vector3(-spawnSize*spawnDistance/2f, 0f, 0f), Quaternion.identity); clone.name = "Temporary particle " + (i+1); clone.transform.parent = this.transform; clone.GetComponent<TrailRenderer>().time = 0f; particles.Add(clone.transform); } } public void SpawnParticles() { this.transform.DetachChildren(); for(int i=0; i<particles.Count; i++) { particles[i].name = "Particle " + (i+1); if(HuygensPrinciple.instance.linesVisible) particles[i].GetComponent<TrailRenderer>().time = 15f; particles[i].GetComponent<Particle>().velocity = HuygensPrinciple.instance.particleSpeed*this.transform.up; HuygensPrinciple.instance.particles.Add(particles[i]); } RespawnParticles(false); } void Update() { Debug.DrawLine(this.transform.position, this.transform.position+this.transform.up, Color.blue); if(Input.GetKey(KeyCode.Keypad7)) { this.transform.rotation = this.transform.rotation*Quaternion.Euler(0f, 0f, -rotateSpeed*Time.deltaTime); } if(Input.GetKey(KeyCode.Keypad9)) { this.transform.rotation = this.transform.rotation*Quaternion.Euler(0f, 0f, rotateSpeed*Time.deltaTime); } if(Input.GetKey(KeyCode.Keypad8)) { this.transform.position += Vector3.up*moveSpeed*Time.deltaTime; } if(Input.GetKey(KeyCode.Keypad5)) { this.transform.position += -Vector3.up*moveSpeed*Time.deltaTime; } if(Input.GetKey(KeyCode.Keypad4)) { this.transform.position += -Vector3.right*moveSpeed*Time.deltaTime; } if(Input.GetKey(KeyCode.Keypad6)) { this.transform.position += Vector3.right*moveSpeed*Time.deltaTime; } if(Input.GetKeyDown(KeyCode.Space)) { SpawnParticles(); } } }
37.323529
176
0.724586
[ "Unlicense" ]
TheNumber5/huygens-principle-unity
ParticleSpawner.cs
2,538
C#
namespace IoT.Web.Areas.HelpPage.ModelDescriptions { public class SimpleTypeModelDescription : ModelDescription { } }
21.5
62
0.75969
[ "MIT" ]
msmcdx/iotworkshop
IoT.Web/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs
129
C#
using System; using System.Collections.Generic; using System.Text; namespace IdentityServer4.Models.ViewModels { public class RolesDto { public RolesDto(Roles roles,List<PermissionRecord> permission) { if (roles != null) { this.Id = roles.Id.ToString(); this.RoleName = roles.RoleName; this.RoleType = roles.RoleType; this.Description = roles.Description; this.Permissions = permission; } } public string Id { get; set; } public string RoleName { get; set; } public int? RoleType { get; set; } public string Description { get; set; } public List<PermissionRecord> Permissions { get; set; } } }
29.148148
70
0.56798
[ "Apache-2.0" ]
radyatamaa/identity-server-4-bknri
src/Models/ViewModels/RolesDto.cs
787
C#
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.Common; using System.Data.SqlClient; using System.Text; using System.Collections.Generic; namespace EBA.Desktop.HRA { /// <summary> /// Summary description for QueryBuilder /// </summary> public class QueryBuilder { static string connStr = ConfigurationManager.ConnectionStrings["EBADB"].ConnectionString; static SqlConnection conn = new SqlConnection(connStr); static SqlCommand command = null; public QueryBuilder() { } /// <summary> /// Creates a general SQL query string for given columns, tables. /// </summary> /// <param name="_tcList">List of Columns and tables of type ColumnsAndTables</param> /// <returns>SQL query string</returns> public static string GenerateSqlQuery(List<ColumnsAndTables> _tcList) { string _strSql = string.Empty; DataTable _IJTable = new DataTable(); DataTable _CJTable = new DataTable(); _strSql = "SELECT " + CreateSelectString(_tcList) + Environment.NewLine + " FROM Employee" + " "; List<string> _tablesList = new List<string>(); foreach (ColumnsAndTables ct in _tcList) { _tablesList.Add(ct.Tbls); } string _tablesStr = CreateTableString(_tablesList); _IJTable = GetInnerJoin(_tablesStr); //Build the Inner Join if (_IJTable.Rows.Count > 0) { for (int i = 0; i < _IJTable.Rows.Count; i++) { string _foreignTbl = _IJTable.Rows[i][0].ToString(); string _primaryTbl = _IJTable.Rows[i][1].ToString(); string _foreignID = _IJTable.Rows[i][2].ToString(); string _primaryID = _IJTable.Rows[i][3].ToString(); _strSql += " INNER JOIN " + Environment.NewLine + "[" + _foreignTbl + "]" + " ON " + "[" + _foreignTbl + "]." + _foreignID + " = " + "[" + _primaryTbl + "]." + _primaryID; } } return _strSql; } /// <summary> /// Creates SQL query for Ownership type letters /// </summary> /// <param name="_tcList">List of Columns and tables of type ColumnsAndTables</param> /// <returns>SQL query string</returns> public static string GenerateOwnershipSqlQuery(List<ColumnsAndTables> _tcList) { string _strSql = string.Empty; DataTable _IJTable = new DataTable(); DataTable _CJTable = new DataTable(); _strSql = "SELECT " + CreateSelectString(_tcList) + Environment.NewLine + " FROM Employee" + " "; List<string> _tablesList = new List<string>(); foreach (ColumnsAndTables ct in _tcList) { _tablesList.Add(ct.Tbls); } string _tablesStr = CreateTableString(_tablesList); _IJTable = GetInnerJoin(_tablesStr); //Build the Inner Join if (_IJTable.Rows.Count > 0) { for (int i = 0; i < _IJTable.Rows.Count; i++) { string _foreignTbl = _IJTable.Rows[i][0].ToString(); string _primaryTbl = _IJTable.Rows[i][1].ToString(); string _foreignID = _IJTable.Rows[i][2].ToString(); string _primaryID = _IJTable.Rows[i][3].ToString(); _strSql += " INNER JOIN " + Environment.NewLine + "[" + _foreignTbl + "]" + " ON " + "[" + _foreignTbl + "]." + _foreignID + " = " + "[" + _primaryTbl + "]." + _primaryID; } } //add this string to get address of dependents based on address type StringBuilder sb = new StringBuilder(_strSql); sb.Append(" WHERE Address.addr_type <> '004' "); sb.Append(" AND Dependant.dpnd_add_diff = 0 "); sb.Append(" UNION "); sb.Append(_strSql); sb.Append(" AND Address.addr_dpnd_ssn = Dependant.dpnd_ssn "); sb.Append(" AND Dependant.dpnd_add_diff = 0 "); return sb.ToString(); } /// <summary> /// Creates SQL query for Confirmation letters /// </summary> /// <param name="_tcList">List of Columns and tables of type ColumnsAndTables</param> /// <returns>SQL query string</returns> public static string GenerateConfirmationSqlQuery(List<ColumnsAndTables> _tcList) { string _strSql = string.Empty; DataTable _IJTable = new DataTable(); DataTable _CJTable = new DataTable(); string _selectStr = CreateSelectString(_tcList); // Get top 3 dependants StringBuilder sb = new StringBuilder(_selectStr); sb.Append(" , MAX(CASE [dpnd_order] WHEN 1 THEN Dependant.dpnd_fname + ' ' + Dependant.dpnd_lname END) Dependent1, "); sb.Append(" MAX(CASE [dpnd_order] WHEN 2 THEN Dependant.dpnd_fname + ' ' + Dependant.dpnd_lname END) Dependent2, "); sb.Append(" MAX(CASE [dpnd_order] WHEN 3 THEN Dependant.dpnd_fname + ' ' + Dependant.dpnd_lname END) Dependent3 "); _strSql = "SELECT " + sb.ToString() + Environment.NewLine + " FROM Employee" + " "; List<string> _tablesList = new List<string>(); foreach (ColumnsAndTables ct in _tcList) { _tablesList.Add(ct.Tbls); } string _tablesStr = CreateTableString(_tablesList); _IJTable = GetInnerJoin(_tablesStr); //Build the Inner Join if (_IJTable.Rows.Count > 0) { for (int i = 0; i < _IJTable.Rows.Count; i++) { string _foreignTbl = _IJTable.Rows[i][0].ToString(); string _primaryTbl = _IJTable.Rows[i][1].ToString(); string _foreignID = _IJTable.Rows[i][2].ToString(); string _primaryID = _IJTable.Rows[i][3].ToString(); _strSql += " INNER JOIN " + Environment.NewLine + "[" + _foreignTbl + "]" + " ON " + "[" + _foreignTbl + "]." + _foreignID + " = " + "[" + _primaryTbl + "]." + _primaryID; } } //add dependant table to sql string if it does not exists if (!_strSql.Contains("INNER JOIN [Dependant] ON [Employee].empl_empno = [Dependant].dpnd_empno")) { _strSql = _strSql + "INNER JOIN [Dependant] ON [Employee].empl_empno = [Dependant].dpnd_empno"; } _strSql = _strSql + " GROUP BY " + _selectStr; return _strSql; } private static string CreateTableString(List<string> _tblStr) { string _finalTbl = ""; foreach (string _tb in _tblStr) { _finalTbl += "'" + _tb + "',"; } _finalTbl = _finalTbl.Remove(_finalTbl.Length - 1); return _finalTbl; } private static string CreateSelectString(List<ColumnsAndTables> _coltables) { string _var = ""; bool _fnd = false; foreach (ColumnsAndTables ct1 in _coltables) { _fnd = false; switch (ct1.Schm) { //case "Dependent1": // _var += ct1.Tbls + "." + "dpnd_fname" + " + " + ct1.Tbls + "." + "dpnd_fname AS [" + ct1.Schm + "],"; // _fnd = true; // break; //case "Dependent2": // _var += ct1.Tbls + "." + "dpnd_fname" + " + " + ct1.Tbls + "." + "dpnd_fname AS [" + ct1.Schm + "],"; // _fnd = true; // break; //case "Dependent3": // _var += ct1.Tbls + "." + "dpnd_fname" + " + " + ct1.Tbls + "." + "dpnd_fname AS [" + ct1.Schm + "],"; // _fnd = true; // break; case "Dependent_Name": _var += ct1.Tbls + "." + "dpnd_fname" + " + " + ct1.Tbls + "." + "dpnd_fname AS [" + ct1.Schm + "],"; _fnd = true; break; case "Pilot_Name": _var += ct1.Tbls + "." + "empl_fname" + " + " + ct1.Tbls + "." + "empl_minit " + " + " + ct1.Tbls + "." + "empl_lname AS [" + ct1.Schm + "],"; _fnd = true; break; case "Street_Address": _var += ct1.Tbls + "." + "addr_addr1" + " + " + ct1.Tbls + "." + "addr_addr2 AS [" + ct1.Schm + "],"; _fnd = true; break; case "City_State_Zip": _var += ct1.Tbls + "." + "addr_city" + " + " + ct1.Tbls + "." + "addr_state " + " + " + ct1.Tbls + "." + "addr_zip AS [" + ct1.Schm + "],"; _fnd = true; break; case "father_mother": _var += " CASE " + " WHEN " +ct1.Tbls + "." + "empl_sex = 'M' THEN 'father' " + " WHEN " +ct1.Tbls + "." + "empl_sex = 'F' THEN 'mother' " + " END" + " AS [" + ct1.Schm + "],"; break; case "fathers_mothers": _var += " CASE " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'M' THEN 'father''s' " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'F' THEN 'mother''s' " + " END" + " AS [" + ct1.Schm + "],"; _fnd = true; break; case "he_she": _var += " CASE " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'M' THEN 'he' " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'F' THEN 'she' " + " END" + " AS [" + ct1.Schm + "],"; _fnd = true; break; case "his_her": _var += " CASE " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'M' THEN 'his' " + " WHEN " + ct1.Tbls + "." + "empl_sex = 'F' THEN 'her' " + " END" + " AS [" + ct1.Schm + "],"; _fnd = true; break; } if (_fnd) { continue; } _var += ct1.Tbls + "." + ct1.Cols + " AS [" + ct1.Schm + "],"; } //if (!_var.Contains("Employee.empl_empno AS [EmployeeNo],")) //{ // _var += "Employee.empl_empno AS [EmployeeNo],"; //} //if (!_var.Contains("Employee.empl_fname AS [FirstName],")) //{ // _var += "Employee.empl_fname AS [FirstName],"; //} //if (!_var.Contains("Employee.empl_lname AS [LastName],")) //{ // _var += "Employee.empl_lname AS [LastName],"; //} //if (!_var.Contains("Employee.empl_ssn AS [EmployeeSSN],")) //{ // _var += "Employee.empl_ssn AS [EmployeeSSN],"; //} //if (!_var.Contains("Address.addr_addr1 AS [Address1],")) //{ // _var += "Address.addr_addr1 AS [Address1],"; //} //if (!_var.Contains("Address.addr_addr2 AS [Address2],")) //{ // _var += "Address.addr_addr2 AS [Address2],"; //} //if (!_var.Contains("Address.addr_city AS [City],")) //{ // _var += "Address.addr_city AS [City],"; //} //if (!_var.Contains("Address.addr_state AS [State],")) //{ // _var += "Address.addr_state AS [State],"; //} //if (!_var.Contains("Address.addr_zip AS [Zip],")) //{ // _var += "Address.addr_zip AS [Zip],"; //} _var = _var.Remove(_var.Length - 1); return _var; } private static DataTable GetInnerJoin(string _tablesString) { try { StringBuilder sqlString = new StringBuilder(); sqlString.Append("SELECT sof.name AS fTableName, sor.name AS rTableName, scf.name AS fColName, scr.name AS rColName "); sqlString.Append("FROM dbo.sysforeignkeys sfk INNER JOIN "); sqlString.Append("dbo.sysobjects sof ON sfk.fkeyid = sof.id INNER JOIN "); sqlString.Append("dbo.sysobjects sor ON sfk.rkeyid = sor.id INNER JOIN "); sqlString.Append("dbo.syscolumns scf ON sfk.fkey = scf.colid AND sof.id = scf.id INNER JOIN "); sqlString.Append("dbo.syscolumns scr ON sfk.rkey = scr.colid AND sor.id = scr.id "); sqlString.Append("AND sor.name in (" + _tablesString + ") "); sqlString.Append("AND sof.name in (" + _tablesString + ") "); sqlString.Append("AND sor.name <> sof.name"); if (conn != null && conn.State == ConnectionState.Closed) { conn.Open(); } command = new SqlCommand(sqlString.ToString(), conn); SqlDataAdapter da = new SqlDataAdapter(); DataTable _ijTable = new DataTable(); da.SelectCommand = command; da.Fill(_ijTable); return _ijTable; } catch (Exception ex) { throw ex; } finally { conn.Close(); } } private static DataTable getColumnName(string _tableName) { try { String sqlString = String.Empty; sqlString = "SELECT DISTINCT column_name FROM information_schema.columns WHERE table_name = '" + _tableName + "'"; command = new SqlCommand(sqlString.ToString(), conn); SqlDataAdapter da = new SqlDataAdapter(); DataTable _colTable = new DataTable(); da.SelectCommand = command; da.Fill(_colTable); return _colTable; } catch (Exception e) { throw e; } } public struct ColumnsAndTables { private string _cols; private string _tbls; private string _schemas; public string Schm { get { return _schemas; } set { _schemas = value; } } public string Cols { get { return _cols; } set { _cols = value; } } public string Tbls { get { return _tbls; } set { _tbls = value; } } } } }
40.340741
191
0.447117
[ "MIT" ]
jlpatton/AuditBenefits
App_Code/HRA/QueryBuilder.cs
16,338
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Pathfinding : MonoBehaviour { public Transform seeker, target; Grid grid; void Awake() { grid = GetComponent<Grid>(); } void Update() { FindPath(seeker.position,target.position); } void FindPath(Vector3 startPos, Vector3 targetPos) { Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetPos); //这里实现堆 Heap<Node> openSet = new Heap<Node>(grid.MaxSize); HashSet<Node> closedSet = new HashSet<Node>(); openSet.Add(startNode); while (openSet.Count > 0) { //这里就十分优雅的获取到最小f值的元素 RemoveFirst() //其他地方基本没变 Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { RetracePath(startNode,targetNode); return; } foreach (Node neighbour in grid.GetNeighbours(currentNode)) { if (!neighbour.walkable || closedSet.Contains(neighbour)) { continue; } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour); if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = GetDistance(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) openSet.Add(neighbour); else { //openSet.UpdateItem(neighbour); } } } } } void RetracePath(Node startNode, Node endNode) { List<Node> path = new List<Node>(); Node currentNode = endNode; while (currentNode != startNode) { path.Add(currentNode); currentNode = currentNode.parent; } path.Reverse(); grid.path = path; } int GetDistance(Node nodeA, Node nodeB) { int dstX = Mathf.Abs(nodeA.gridX - nodeB.gridX); int dstY = Mathf.Abs(nodeA.gridY - nodeB.gridY); if (dstX > dstY) return 14*dstY + 10* (dstX-dstY); return 14*dstX + 10 * (dstY-dstX); } }
23.376471
93
0.690488
[ "MIT" ]
Citem7/Pathfinding
Episode 04 - heap/Assets/Scripts/Pathfinding.cs
2,049
C#
using System; using System.Collections.Generic; using Rubeus.lib.Interop; namespace Rubeus.Commands { public class Purge : ICommand { public static string CommandName => "purge"; public void Execute(Dictionary<string, string> arguments) { Console.WriteLine("\r\n[*] Action: Purge Tickets"); LUID luid = new LUID(); if (arguments.ContainsKey("/luid")) { try { luid = new LUID(arguments["/luid"]); } catch { Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/luid"]); return; } } Console.WriteLine("Luid: {0}", luid); LSA.Purge(luid); } } }
24.472222
96
0.444949
[ "BSD-3-Clause" ]
0Nightsedge0/Rubeus
Rubeus/Commands/Purge.cs
883
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.DotNet.Cli.CommandLine; using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Restore.LocalizableStrings; namespace Microsoft.DotNet.Cli { internal static class ToolRestoreCommandParser { public static Command ToolRestore() { return Create.Command( "restore", LocalizableStrings.CommandDescription, Accept.NoArguments(), Create.Option( "--configfile", LocalizableStrings.ConfigFileOptionDescription, Accept.ExactlyOneArgument() .With(name: LocalizableStrings.ConfigFileOptionName)), Create.Option( "--add-source", LocalizableStrings.AddSourceOptionDescription, Accept.OneOrMoreArguments() .With(name: LocalizableStrings.AddSourceOptionName)), Create.Option( "--tool-manifest", LocalizableStrings.ManifestPathOptionDescription, Accept.ZeroOrOneArgument() .With(name: LocalizableStrings.ManifestPathOptionName)), ToolCommandRestorePassThroughOptions.DisableParallelOption(), ToolCommandRestorePassThroughOptions.IgnoreFailedSourcesOption(), ToolCommandRestorePassThroughOptions.NoCacheOption(), ToolCommandRestorePassThroughOptions.InteractiveRestoreOption(), CommonOptions.HelpOption(), CommonOptions.VerbosityOption()); } } }
44.219512
101
0.613348
[ "MIT" ]
5l1v3r1/sdk-1
src/Cli/dotnet/commands/dotnet-tool/restore/ToolRestoreCommandParser.cs
1,813
C#
namespace BaristaLabs.Skrapr.Schedules { using Newtonsoft.Json; /// <summary> /// Represents a schedule defined as a Cron Expression. /// </summary> public class CronSchedule : SkraprSchedule { public override string Type { get { return "cron"; } } [JsonProperty("cronExpression", Required = Required.Always)] public string CronExpression { get; set; } } }
20.869565
68
0.552083
[ "MIT" ]
BaristaLabs/BaristaLabs.Skrapr
src/BaristaLabs.Skrapr.Core/Schedules/CronSchedule.cs
482
C#
using Nuke.Common.Tooling; using Nuke.Common.Utilities.Collections; using System; using System.Collections.Generic; using System.Text; using Tool.Deploy.Utilities; namespace Tool.Deploy.AwsCdk { [Serializable] public class AwsCdkSynthSettings : ToolSettings { public override string ProcessToolPath => base.ProcessToolPath ?? AwsCdkTasks.CdkPath; public override Action<OutputType, string> ProcessCustomLogger => AwsCdkTasks.CustomLogger; public virtual IReadOnlyDictionary<string, string> ContextPairs => ContextPairsInternal.AsReadOnly(); internal Dictionary<string, string> ContextPairsInternal { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public virtual IEnumerable<string> Stacks => StacksInternal.AsReadOnly(); internal List<string> StacksInternal { get; set; } = new List<string>(); protected override Arguments ConfigureProcessArguments(Arguments arguments) { arguments .Add("synth") .Add(StacksInternal) .AddKeyValuePairs("--context [<key>=\"<value>\"]", ContextPairsInternal); return base.ConfigureProcessArguments(arguments); } } public static class AwsCdkSynthSettingsExtensions { public static T SetContext<T>(this T toolSettings, string contextKey, string contextValue) where T : AwsCdkSynthSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ContextPairsInternal.Add(contextKey, contextValue); return toolSettings; } /// <summary> /// Current cdk synth structure creates templates for all, then deletes unused. If there are systemic dependencies between stacks, do not use. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="toolSettings"></param> /// <param name="stackName"></param> /// <returns></returns> public static T AddStack<T>(this T toolSettings, string stackName) where T : AwsCdkSynthSettings { toolSettings = toolSettings.NewInstance(); toolSettings.StacksInternal.Add(stackName); return toolSettings; } } }
40.392857
150
0.668435
[ "MIT" ]
bulsatar/nukacola
Deploy/AwsCdk/AwsCdkSynthSettings.cs
2,264
C#
using Quartz; using Quartz.Impl; using TrueOrFalse.Infrastructure; namespace TrueOrFalse.Utilities.ScheduledJobs { public static class JobScheduler { static readonly IScheduler _scheduler; static JobScheduler() { var container = AutofacWebInitializer.Run(); _scheduler = StdSchedulerFactory.GetDefaultScheduler(); _scheduler.JobFactory = new AutofacJobFactory(container); _scheduler.Start(); } public static void EmptyMethodToCallConstructor() { } public static void Shutdown() { _scheduler.Shutdown(waitForJobsToComplete:true); } public static void Start() { Sl.R<RunningJobRepo>().TruncateTable(); Schedule_CleanupWorkInProgressQuestions(); Schedule_RecalcKnowledgeStati(); Schedule_RecalcKnowledgeSummariesForCategory(); Schedule_RecalcReputation(); Schedule_RecalcReputationForAll(); Schedule_EditCategoryInWishKnowledge(); Schedule_KnowledgeReportCheck(); Schedule_LOM_Export(); Schedule_RecalcTotalWishInOthersPeople(); } private static void Schedule_CleanupWorkInProgressQuestions() { _scheduler.ScheduleJob(JobBuilder.Create<CleanUpWorkInProgressQuestions>().Build(), TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInHours(6) .RepeatForever()).Build()); } private static void Schedule_RecalcKnowledgeStati() { _scheduler.ScheduleJob(JobBuilder.Create<RecalcKnowledgeStati>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(2, 00)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_RecalcKnowledgeSummariesForCategory() { _scheduler.ScheduleJob(JobBuilder.Create<RecalcKnowledgeSummariesForCategory>().Build(), TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(RecalcReputation.IntervalInSeconds) .RepeatForever()).Build()); } private static void Schedule_RecalcReputation() { //recalculates reputation for users specified in table jobqueue, which is filled when relevant actions are taken that affect users reputation _scheduler.ScheduleJob(JobBuilder.Create<RecalcReputation>().Build(), TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(RecalcReputation.IntervalInSeconds) .RepeatForever()).Build()); } private static void Schedule_RecalcReputationForAll() { //once a day, recalculate reputation for all users _scheduler.ScheduleJob(JobBuilder.Create<RecalcReputationForAll>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(3, 00)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_RecalcTotalWishInOthersPeople() { //once a day, recalculate reputation for all users _scheduler.ScheduleJob(JobBuilder.Create<RecalcTotalWishInOthersPeople>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(4, 00)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_KnowledgeReportCheck() { _scheduler.ScheduleJob(JobBuilder.Create<KnowledgeReportCheck>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(10, 00)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_LOM_Export() { _scheduler.ScheduleJob(JobBuilder.Create<LomExportJob>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(3, 30)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_RefreshEntityCache() { _scheduler.ScheduleJob(JobBuilder.Create<RefreshEntityCache>().Build(), TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.StartingDailyAt(new TimeOfDay(3, 30)) .OnEveryDay() .EndingDailyAfterCount(1)).Build()); } private static void Schedule_EditCategoryInWishKnowledge() { _scheduler.ScheduleJob(JobBuilder.Create<EditCategoryInWishKnowledge>().Build(), TriggerBuilder.Create(). WithSimpleSchedule(x => x .WithIntervalInSeconds(EditCategoryInWishKnowledge.IntervalInSeconds) .RepeatForever()).Build()); } //public static void StartImmediately_TrainingReminderCheck() { StartImmediately<TrainingReminderCheck>(); } //public static void StartImmediately_TrainingPlanUpdateCheck() { StartImmediately<TrainingPlanUpdateCheck>(); } public static void StartImmediately_CleanUpWorkInProgressQuestions() { StartImmediately<CleanUpWorkInProgressQuestions>(); } public static void StartImmediately_RecalcKnowledgeStati() { StartImmediately<RecalcKnowledgeStati>(); } public static void StartImmediately_RefreshEntityCache() { StartImmediately<RefreshEntityCache>(); } public static void StartImmediately_RecalcTotalWishInOthersPeople() { StartImmediately<RecalcTotalWishInOthersPeople>(); } public static void StartImmediately<TypeToStart>() where TypeToStart : IJob { _scheduler.ScheduleJob( JobBuilder.Create<TypeToStart>().Build(), TriggerBuilder.Create().StartNow().Build()); } public static void StartImmediately_InitUserValuationCache(int userId) { _scheduler.ScheduleJob( JobBuilder.Create<InitUserValuationCache>() .UsingJobData("userId", userId) .Build(), TriggerBuilder.Create().StartNow().Build()); } } }
42.891566
154
0.583989
[ "MIT" ]
memucho/webapp
src/TrueOrFalse/Tools/ScheduledJobs/JobScheduler.cs
7,122
C#
using System; using Super.Compose; using Super.Model.Selection; using Super.Model.Selection.Conditions; using Super.Reflection; namespace Super.Runtime { public class AssignedGuard<T> : AssignedGuard<T, InvalidOperationException> { protected AssignedGuard(Func<Type, string> message) : base(message) {} public AssignedGuard(ISelect<T, string> message) : base(message) {} } public class AssignedGuard<T, TException> : Guard<T, TException> where TException : Exception { readonly static ICondition<T> Condition = IsAssigned<T>.Default.Then().Inverse().Out(); protected AssignedGuard(Func<Type, string> message) : this(message.ToSelect() .In(A.Type<T>()) .ToSelect(I.A<T>())) {} public AssignedGuard(ISelect<T, string> message) : base(Condition, message) {} } }
35.230769
94
0.631004
[ "MIT" ]
SuperDotNet/Super.NET
Super/Runtime/AssignedGuard.cs
918
C#
#region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; using System.Collections.Generic; using System.Text; namespace Newtonsoft.Json { /// <summary> /// Specifies reference loop handling options for the <see cref="JsonSerializer"/>. /// </summary> public enum ReferenceLoopHandling { /// <summary> /// Throw a <see cref="JsonSerializationException"/> when a loop is encountered. /// </summary> Error = 0, /// <summary> /// Ignore loop references and do not serialize. /// </summary> Ignore = 1, /// <summary> /// Serialize loop references. /// </summary> Serialize = 2 } }
35.235294
86
0.695604
[ "Apache-2.0" ]
bewood/OpenAdStack
External/Json45r7/Source/Src/Newtonsoft.Json/ReferenceLoopHandling.cs
1,799
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614 { using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions; /// <summary>Class representing an update to a Kusto cluster.</summary> public partial class ClusterUpdate { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject into a new instance of <see cref="ClusterUpdate" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject instance to deserialize from.</param> internal ClusterUpdate(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __resource = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api10.Resource(json); {_identity = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject>("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.Identity.FromJson(__jsonIdentity) : Identity;} {_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ClusterProperties.FromJson(__jsonProperties) : Property;} {_sku = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject>("sku"), out var __jsonSku) ? Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.AzureSku.FromJson(__jsonSku) : Sku;} {_location = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString>("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} {_tag = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject>("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.ClusterUpdateTags.FromJson(__jsonTags) : Tag;} AfterFromJson(json); } /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IClusterUpdate. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IClusterUpdate. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200614.IClusterUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject json ? new ClusterUpdate(json) : null; } /// <summary> /// Serializes this instance of <see cref="ClusterUpdate" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="ClusterUpdate" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __resource?.ToJson(container, serializationMode); AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); AfterToJson(ref container); return container; } } }
76.504505
272
0.690886
[ "MIT" ]
Click4PV/azure-powershell
src/Kusto/generated/api/Models/Api20200614/ClusterUpdate.json.cs
8,382
C#
namespace BeautySalon.Data.Repositories { using System; using System.Linq; using System.Threading.Tasks; using BeautySalon.Data.Common.Models; using BeautySalon.Data.Common.Repositories; using Microsoft.EntityFrameworkCore; public class EfDeletableEntityRepository<TEntity> : EfRepository<TEntity>, IDeletableEntityRepository<TEntity> where TEntity : class, IDeletableEntity { public EfDeletableEntityRepository(ApplicationDbContext context) : base(context) { } public override IQueryable<TEntity> All() => base.All().Where(x => !x.IsDeleted); public override IQueryable<TEntity> AllAsNoTracking() => base.AllAsNoTracking().Where(x => !x.IsDeleted); public IQueryable<TEntity> AllWithDeleted() => base.All().IgnoreQueryFilters(); public IQueryable<TEntity> AllAsNoTrackingWithDeleted() => base.AllAsNoTracking().IgnoreQueryFilters(); public Task<TEntity> GetByIdWithDeletedAsync(params object[] id) { var getByIdPredicate = EfExpressionHelper.BuildByIdPredicate<TEntity>(this.Context, id); return this.AllWithDeleted().FirstOrDefaultAsync(getByIdPredicate); } public void HardDelete(TEntity entity) => base.Delete(entity); public void Undelete(TEntity entity) { entity.IsDeleted = false; entity.DeletedOn = null; this.Update(entity); } public override void Delete(TEntity entity) { entity.IsDeleted = true; entity.DeletedOn = DateTime.UtcNow; this.Update(entity); } } }
32.745098
114
0.659281
[ "MIT" ]
ChristinaNikolova/BeautySalon
Data/BeautySalon.Data/Repositories/EfDeletableEntityRepository.cs
1,672
C#
using System; namespace CacheRepository.Configuration { public class EntityPropertiesForFile { public enum FileMode { Overwrite, Append } public EntityPropertiesForFile(Type entityType) { if (entityType == null) throw new ArgumentNullException("entityType"); EntityType = entityType; } public Type EntityType { get; private set; } public string FileName { private get; set; } public FileMode? FileModeSetter { private get; set; } public string GetFileName() { return string.IsNullOrEmpty(this.FileName) ? EntityType.Name : this.FileName; } public System.IO.FileMode GetFileMode() { if (this.FileModeSetter == null || this.FileModeSetter == FileMode.Append) return System.IO.FileMode.Append; return System.IO.FileMode.OpenOrCreate; } } }
23.694444
112
0.676436
[ "Apache-2.0" ]
gbrunton/CacheRepository
CacheRepository/Configuration/EntityPropertiesForFile.cs
855
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Azure.Core.Cryptography; using Azure.Storage.Cryptography.Models; namespace Azure.Storage.Cryptography { internal class ClientSideEncryptor { private readonly IKeyEncryptionKey _keyEncryptionKey; private readonly string _keyWrapAlgorithm; public ClientSideEncryptor(ClientSideEncryptionOptions options) { _keyEncryptionKey = options.KeyEncryptionKey; _keyWrapAlgorithm = options.KeyWrapAlgorithm; } public static long ExpectedCiphertextLength(long plaintextLength) { const int aesBlockSizeBytes = 16; // pkcs7 padding output length algorithm return plaintextLength + (aesBlockSizeBytes - (plaintextLength % aesBlockSizeBytes)); } /// <summary> /// Wraps the given read-stream in a CryptoStream and provides the metadata used to create /// that stream. /// </summary> /// <param name="plaintext">Stream to wrap.</param> /// <param name="async">Whether to wrap the content encryption key asynchronously.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The wrapped stream to read from and the encryption metadata for the wrapped stream.</returns> public async Task<(Stream Ciphertext, EncryptionData EncryptionData)> EncryptInternal( Stream plaintext, bool async, CancellationToken cancellationToken) { if (_keyEncryptionKey == default || _keyWrapAlgorithm == default) { throw Errors.ClientSideEncryption.MissingRequiredEncryptionResources(nameof(_keyEncryptionKey), nameof(_keyWrapAlgorithm)); } var generatedKey = CreateKey(Constants.ClientSideEncryption.EncryptionKeySizeBits); EncryptionData encryptionData = default; Stream ciphertext = default; using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider() { Key = generatedKey }) { encryptionData = await EncryptionData.CreateInternalV1_0( contentEncryptionIv: aesProvider.IV, keyWrapAlgorithm: _keyWrapAlgorithm, contentEncryptionKey: generatedKey, keyEncryptionKey: _keyEncryptionKey, async: async, cancellationToken: cancellationToken).ConfigureAwait(false); ciphertext = new CryptoStream( plaintext, aesProvider.CreateEncryptor(), CryptoStreamMode.Read); } return (ciphertext, encryptionData); } /// <summary> /// Encrypts the given stream and provides the metadata used to encrypt. This method writes to a memory stream, /// optimized for known-size data that will already be buffered in memory. /// </summary> /// <param name="plaintext">Stream to encrypt.</param> /// <param name="async">Whether to wrap the content encryption key asynchronously.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The encrypted data and the encryption metadata for the wrapped stream.</returns> public async Task<(byte[] Ciphertext, EncryptionData EncryptionData)> BufferedEncryptInternal( Stream plaintext, bool async, CancellationToken cancellationToken) { if (_keyEncryptionKey == default || _keyWrapAlgorithm == default) { throw Errors.ClientSideEncryption.MissingRequiredEncryptionResources(nameof(_keyEncryptionKey), nameof(_keyWrapAlgorithm)); } var generatedKey = CreateKey(Constants.ClientSideEncryption.EncryptionKeySizeBits); EncryptionData encryptionData = default; var ciphertext = new MemoryStream(); byte[] bufferedCiphertext = default; using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider() { Key = generatedKey }) { encryptionData = await EncryptionData.CreateInternalV1_0( contentEncryptionIv: aesProvider.IV, keyWrapAlgorithm: _keyWrapAlgorithm, contentEncryptionKey: generatedKey, keyEncryptionKey: _keyEncryptionKey, async: async, cancellationToken: cancellationToken).ConfigureAwait(false); var transformStream = new CryptoStream( ciphertext, aesProvider.CreateEncryptor(), CryptoStreamMode.Write); if (async) { await plaintext.CopyToAsync(transformStream).ConfigureAwait(false); } else { plaintext.CopyTo(transformStream); } transformStream.FlushFinalBlock(); bufferedCiphertext = ciphertext.ToArray(); } return (bufferedCiphertext, encryptionData); } /// <summary> /// Securely generate a key. /// </summary> /// <param name="numBits">Key size.</param> /// <returns>The generated key bytes.</returns> private static byte[] CreateKey(int numBits) { using (var secureRng = new RNGCryptoServiceProvider()) { var buff = new byte[numBits / 8]; secureRng.GetBytes(buff); return buff; } } } }
40.965278
139
0.609595
[ "MIT" ]
DiskRP-Swagger/azure-sdk-for-net
sdk/storage/Azure.Storage.Common/src/Shared/ClientsideEncryption/ClientSideEncryptor.cs
5,899
C#
 using Xamarin.Forms; namespace XamarinEvolve.Clients.UI { public class EvolveNavigationPage : NavigationPage { public EvolveNavigationPage(Page root) : base(root) { Init(); Title = root.Title; Icon = root.Icon; } public EvolveNavigationPage() { Init(); } void Init() { if (Device.OS == TargetPlatform.iOS) { BarBackgroundColor = Color.FromHex("FAFAFA"); } else { BarBackgroundColor = (Color)Application.Current.Resources["Primary"]; BarTextColor = (Color)Application.Current.Resources["NavigationText"]; } } } }
23.057143
87
0.477076
[ "MIT" ]
BeeLabs/app-evolve
src/XamarinEvolve.Clients.UI/Controls/EvolveNavigationPage.cs
809
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("Variable-Length-Coding")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Variable-Length-Coding")] [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("2e13094f-f222-44f4-895c-294945d0d748")] // 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")]
39.27027
85
0.72746
[ "MIT" ]
Gyokay/Telerik-Academy-Exam-Solutions
C_Sharp_2_Exam_Solutions/Variable-Length-Coding/Properties/AssemblyInfo.cs
1,456
C#
using System; using System.Linq; using System.Threading.Tasks; using Edelstein.Core; using Edelstein.Core.Extensions; using Edelstein.Core.Gameplay.Constants; using Edelstein.Core.Gameplay.Inventories; using Edelstein.Core.Gameplay.Inventories.Operations; using Edelstein.Core.Gameplay.Skills; using Edelstein.Core.Gameplay.Social.Messages; using Edelstein.Database.Entities.Inventories; using Edelstein.Network.Packets; using Edelstein.Service.Game.Fields.Objects.Dragon; using Edelstein.Service.Game.Fields.Objects.User.Effects; using Edelstein.Service.Game.Fields.Objects.User.Quests; using Edelstein.Service.Game.Fields.Objects.User.Stats; using Edelstein.Service.Game.Fields.Objects.User.Stats.Modify; namespace Edelstein.Service.Game.Fields.Objects.User { public partial class FieldUser { private bool _directionMode; private bool _standAloneMode; public bool DirectionMode { get => _directionMode; set { _directionMode = value; using var p = new Packet(SendPacketOperations.SetDirectionMode); p.Encode<bool>(value); p.Encode<int>(0); // tAfterLeaveDirectionMode SendPacket(p); } } public bool StandAloneMode { get => _standAloneMode; set { _standAloneMode = value; using var p = new Packet(SendPacketOperations.SetStandAloneMode); p.Encode<bool>(value); SendPacket(p); } } public async Task ValidateStat() { BasicStat.Calculate(); if (Character.HP > BasicStat.MaxHP) await ModifyStats(s => s.HP = BasicStat.MaxHP); if (Character.MP > BasicStat.MaxMP) await ModifyStats(s => s.MP = BasicStat.MaxMP); } public async Task AvatarModified() { using var p = new Packet(SendPacketOperations.UserAvatarModified); p.Encode<int>(ID); p.Encode<byte>(0x1); // Flag Character.EncodeLook(p); p.Encode<bool>(false); p.Encode<bool>(false); p.Encode<bool>(false); p.Encode<int>(BasicStat.CompletedSetItemID); // Completed Set ID await Field.BroadcastPacket(this, p); } public async Task ModifyStats(Action<ModifyStatContext> action = null, bool exclRequest = false) { var context = new ModifyStatContext(Character); action?.Invoke(context); await ValidateStat(); if (!IsInstantiated) return; using (var p = new Packet(SendPacketOperations.StatChanged)) { p.Encode<bool>(exclRequest); context.Encode(p); p.Encode<bool>(false); p.Encode<bool>(false); await SendPacket(p); } if (context.Flag.HasFlag(ModifyStatType.Skin) || context.Flag.HasFlag(ModifyStatType.Face) || context.Flag.HasFlag(ModifyStatType.Hair)) await AvatarModified(); if (context.Flag.HasFlag(ModifyStatType.Job)) { await Effect(new Effect(EffectType.JobChanged), false, true); if (SkillConstants.HasEvanDragon(Character.Job)) { if (!Owned.OfType<FieldDragon>().Any()) { var dragon = new FieldDragon(this); Owned.Add(dragon); await Field.Enter(dragon); } else await Field.Enter(Owned.OfType<FieldDragon>().First()); } else { var dragon = Owned.OfType<FieldDragon>().FirstOrDefault(); if (dragon != null) { Owned.Remove(dragon); await Field.Leave(dragon); } } } if (context.Flag.HasFlag(ModifyStatType.Level)) await Effect(new Effect(EffectType.LevelUp), false, true); if (Socket.SocialService != null) { if (context.Flag.HasFlag(ModifyStatType.Level)) await Socket.Service.SendMessage(Socket.SocialService, new SocialLevelMessage { CharacterID = Character.ID, Level = Character.Level }); if (context.Flag.HasFlag(ModifyStatType.Job)) await Socket.Service.SendMessage(Socket.SocialService, new SocialJobMessage() { CharacterID = Character.ID, Job = Character.Job }); } } public async Task ModifyForcedStats(Action<ModifyForcedStatContext> action = null) { var context = new ModifyForcedStatContext(ForcedStat); action?.Invoke(context); await ValidateStat(); if (!IsInstantiated) return; using var p = new Packet(SendPacketOperations.ForcedStatSet); context.Encode(p); await SendPacket(p); } public async Task ModifyTemporaryStats(Action<ModifyTemporaryStatContext> action = null) { var context = new ModifyTemporaryStatContext(this); action?.Invoke(context); await ValidateStat(); if (context.ResetOperations.Count > 0) { using (var p = new Packet(SendPacketOperations.TemporaryStatReset)) { context.ResetOperations.EncodeMask(p); p.Encode<byte>(0); // IsMovementAffectingStat await SendPacket(p); } using (var p = new Packet(SendPacketOperations.UserTemporaryStatReset)) { p.Encode<int>(ID); context.ResetOperations.EncodeMask(p); await Field.BroadcastPacket(this, p); } } if (context.SetOperations.Count > 0) { using (var p = new Packet(SendPacketOperations.TemporaryStatSet)) { context.SetOperations.EncodeLocal(p); p.Encode<short>(0); // tDelay p.Encode<byte>(0); // IsMovementAffectingStat await SendPacket(p); } using (var p = new Packet(SendPacketOperations.UserTemporaryStatSet)) { p.Encode<int>(ID); context.SetOperations.EncodeRemote(p); p.Encode<short>(0); // tDelay await Field.BroadcastPacket(this, p); } } } public async Task ModifyInventory(Action<IModifyInventoriesContext> action = null, bool exclRequest = false) { var context = new ModifyInventoriesContext(Character.Inventories); action?.Invoke(context); using (var p = new Packet(SendPacketOperations.InventoryOperation)) { p.Encode<bool>(exclRequest); context.Encode(p); p.Encode<bool>(false); await SendPacket(p); } if (context.Operations.Any(o => o.Slot < 0) || context.Operations.OfType<MoveInventoryOperation>().Any(o => o.ToSlot < 0)) { await ValidateStat(); await AvatarModified(); } } public async Task ModifyInventoryLimit(ItemInventoryType type, byte slotMax) { slotMax = (byte) (slotMax / 4 * 4); slotMax = Math.Max((byte) 4, slotMax); slotMax = Math.Min((byte) sbyte.MaxValue, slotMax); Character.Inventories[type].SlotMax = slotMax; using var p = new Packet(SendPacketOperations.InventoryGrow); p.Encode<byte>((byte) type); p.Encode<byte>(slotMax); await SendPacket(p); } public async Task ModifySkills(Action<ModifySkillContext> action = null, bool exclRequest = false) { var context = new ModifySkillContext(Character); action?.Invoke(context); await ValidateStat(); using var p = new Packet(SendPacketOperations.ChangeSkillRecordResult); p.Encode<bool>(exclRequest); context.Encode(p); p.Encode<bool>(true); await SendPacket(p); } public async Task ModifyQuests(Action<ModifyQuestContext> action = null) { var context = new ModifyQuestContext(Character); action?.Invoke(context); await Task.WhenAll(context.Messages.Select(Message)); } } }
34.85
116
0.539124
[ "MIT" ]
Bia10/Edelstein
src/Edelstein.Service.Game/Fields/Objects/User/FieldUserModify.cs
9,061
C#
namespace maskx.ARMOrchestration.Activities { public class AsyncRequestActivityInput { public string InstanceId { get; set; } public string ExecutionId { get; set; } public ProvisioningStage ProvisioningStage { get; set; } } }
29.222222
64
0.680608
[ "MIT" ]
maskx/ARMOrchestration
src/ARMOrchestration/Activities/AsyncRequestActivityInput.cs
265
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms.Internal; using System.Windows.Forms.Layout; using Microsoft.Win32; using static Interop; namespace System.Windows.Forms { /// <summary> /// ToolStrip control. /// </summary> [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDispatch)] [DesignerSerializer("System.Windows.Forms.Design.ToolStripCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)] [Designer("System.Windows.Forms.Design.ToolStripDesigner, " + AssemblyRef.SystemDesign)] [DefaultProperty(nameof(Items))] [SRDescription(nameof(SR.DescriptionToolStrip))] [DefaultEvent(nameof(ItemClicked))] public class ToolStrip : ScrollableControl, IArrangedElement, ISupportToolStripPanel { private static Size onePixel = new Size(1, 1); internal static Point InvalidMouseEnter = new Point(int.MaxValue, int.MaxValue); private ToolStripItemCollection toolStripItemCollection = null; private ToolStripOverflowButton toolStripOverflowButton = null; private ToolStripGrip toolStripGrip = null; private ToolStripItemCollection displayedItems = null; private ToolStripItemCollection overflowItems = null; private ToolStripDropTargetManager dropTargetManager = null; private IntPtr hwndThatLostFocus = IntPtr.Zero; private ToolStripItem lastMouseActiveItem = null; private ToolStripItem lastMouseDownedItem = null; private LayoutEngine layoutEngine = null; private ToolStripLayoutStyle layoutStyle = ToolStripLayoutStyle.StackWithOverflow; private LayoutSettings layoutSettings = null; private Rectangle lastInsertionMarkRect = Rectangle.Empty; private ImageList imageList = null; private ToolStripGripStyle toolStripGripStyle = ToolStripGripStyle.Visible; private ISupportOleDropSource itemReorderDropSource = null; private IDropTarget itemReorderDropTarget = null; private int toolStripState = 0; private bool showItemToolTips = false; private MouseHoverTimer mouseHoverTimer = null; private ToolStripItem currentlyActiveTooltipItem; private NativeWindow dropDownOwnerWindow; private byte mouseDownID = 0; // NEVER use this directly from another class, 0 should never be returned to another class. private Orientation orientation = Orientation.Horizontal; private readonly ArrayList activeDropDowns = new ArrayList(1); private ToolStripRenderer renderer = null; private Type currentRendererType = typeof(Type); private Hashtable shortcuts = null; private Stack<MergeHistory> mergeHistoryStack = null; private ToolStripDropDownDirection toolStripDropDownDirection = ToolStripDropDownDirection.Default; private Size largestDisplayedItemSize = Size.Empty; private CachedItemHdcInfo cachedItemHdcInfo = null; private bool alreadyHooked = false; private Size imageScalingSize; private const int ICON_DIMENSION = 16; private static int iconWidth = ICON_DIMENSION; private static int iconHeight = ICON_DIMENSION; private Font defaultFont = null; private RestoreFocusMessageFilter restoreFocusFilter; private bool layoutRequired = false; private static readonly Padding defaultPadding = new Padding(0, 0, 1, 0); private static readonly Padding defaultGripMargin = new Padding(2); private Padding scaledDefaultPadding = defaultPadding; private Padding scaledDefaultGripMargin = defaultGripMargin; private Point mouseEnterWhenShown = InvalidMouseEnter; private const int INSERTION_BEAM_WIDTH = 6; internal static int insertionBeamWidth = INSERTION_BEAM_WIDTH; private static readonly object EventPaintGrip = new object(); private static readonly object EventLayoutCompleted = new object(); private static readonly object EventItemAdded = new object(); private static readonly object EventItemRemoved = new object(); private static readonly object EventLayoutStyleChanged = new object(); private static readonly object EventRendererChanged = new object(); private static readonly object EventItemClicked = new object(); private static readonly object EventLocationChanging = new object(); private static readonly object EventBeginDrag = new object(); private static readonly object EventEndDrag = new object(); private static readonly int PropBindingContext = PropertyStore.CreateKey(); private static readonly int PropTextDirection = PropertyStore.CreateKey(); private static readonly int PropToolTip = PropertyStore.CreateKey(); private static readonly int PropToolStripPanelCell = PropertyStore.CreateKey(); internal const int STATE_CANOVERFLOW = 0x00000001; internal const int STATE_ALLOWITEMREORDER = 0x00000002; internal const int STATE_DISPOSINGITEMS = 0x00000004; internal const int STATE_MENUAUTOEXPAND = 0x00000008; internal const int STATE_MENUAUTOEXPANDDEFAULT = 0x00000010; internal const int STATE_SCROLLBUTTONS = 0x00000020; internal const int STATE_USEDEFAULTRENDERER = 0x00000040; internal const int STATE_ALLOWMERGE = 0x00000080; internal const int STATE_RAFTING = 0x00000100; internal const int STATE_STRETCH = 0x00000200; internal const int STATE_LOCATIONCHANGING = 0x00000400; internal const int STATE_DRAGGING = 0x00000800; internal const int STATE_HASVISIBLEITEMS = 0x00001000; internal const int STATE_SUSPENDCAPTURE = 0x00002000; internal const int STATE_LASTMOUSEDOWNEDITEMCAPTURE = 0x00004000; internal const int STATE_MENUACTIVE = 0x00008000; #if DEBUG internal static readonly TraceSwitch SelectionDebug = new TraceSwitch("SelectionDebug", "Debug ToolStrip Selection code"); internal static readonly TraceSwitch DropTargetDebug = new TraceSwitch("DropTargetDebug", "Debug ToolStrip Drop code"); internal static readonly TraceSwitch LayoutDebugSwitch = new TraceSwitch("Layout debug", "Debug ToolStrip layout code"); internal static readonly TraceSwitch MouseActivateDebug = new TraceSwitch("ToolStripMouseActivate", "Debug ToolStrip WM_MOUSEACTIVATE code"); internal static readonly TraceSwitch MergeDebug = new TraceSwitch("ToolStripMergeDebug", "Debug toolstrip merging"); internal static readonly TraceSwitch SnapFocusDebug = new TraceSwitch("SnapFocus", "Debug snapping/restoration of focus"); internal static readonly TraceSwitch FlickerDebug = new TraceSwitch("FlickerDebug", "Debug excessive calls to Invalidate()"); internal static readonly TraceSwitch ItemReorderDebug = new TraceSwitch("ItemReorderDebug", "Debug excessive calls to Invalidate()"); internal static readonly TraceSwitch MDIMergeDebug = new TraceSwitch("MDIMergeDebug", "Debug toolstrip MDI merging"); internal static readonly TraceSwitch MenuAutoExpandDebug = new TraceSwitch("MenuAutoExpand", "Debug menu auto expand"); internal static readonly TraceSwitch ControlTabDebug = new TraceSwitch("ControlTab", "Debug ToolStrip Control+Tab selection"); #else internal static readonly TraceSwitch SelectionDebug; internal static readonly TraceSwitch DropTargetDebug; internal static readonly TraceSwitch LayoutDebugSwitch; internal static readonly TraceSwitch MouseActivateDebug; internal static readonly TraceSwitch MergeDebug; internal static readonly TraceSwitch SnapFocusDebug; internal static readonly TraceSwitch FlickerDebug; internal static readonly TraceSwitch ItemReorderDebug; internal static readonly TraceSwitch MDIMergeDebug; internal static readonly TraceSwitch MenuAutoExpandDebug; internal static readonly TraceSwitch ControlTabDebug; #endif private delegate void BooleanMethodInvoker(bool arg); internal Action<int, int> rescaleConstsCallbackDelegate; public ToolStrip() { if (DpiHelper.IsPerMonitorV2Awareness) { ToolStripManager.CurrentDpi = DeviceDpi; defaultFont = ToolStripManager.DefaultFont; iconWidth = DpiHelper.LogicalToDeviceUnits(ICON_DIMENSION, DeviceDpi); iconHeight = DpiHelper.LogicalToDeviceUnits(ICON_DIMENSION, DeviceDpi); insertionBeamWidth = DpiHelper.LogicalToDeviceUnits(INSERTION_BEAM_WIDTH, DeviceDpi); scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding, DeviceDpi); scaledDefaultGripMargin = DpiHelper.LogicalToDeviceUnits(defaultGripMargin, DeviceDpi); } else if (DpiHelper.IsScalingRequired) { iconWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_DIMENSION); iconHeight = DpiHelper.LogicalToDeviceUnitsY(ICON_DIMENSION); insertionBeamWidth = DpiHelper.LogicalToDeviceUnitsX(INSERTION_BEAM_WIDTH); scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding); scaledDefaultGripMargin = DpiHelper.LogicalToDeviceUnits(defaultGripMargin); } imageScalingSize = new Size(iconWidth, iconHeight); SuspendLayout(); CanOverflow = true; TabStop = false; MenuAutoExpand = false; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Selectable, false); SetToolStripState(STATE_USEDEFAULTRENDERER | STATE_ALLOWMERGE, true); SetExtendedState(ExtendedStates.MaintainsOwnCaptureMode // A toolstrip does not take capture on MouseDown. | ExtendedStates.UserPreferredSizeCache, // this class overrides GetPreferredSizeCore, let Control automatically cache the result true); //add a weak ref link in ToolstripManager ToolStripManager.ToolStrips.Add(this); layoutEngine = new ToolStripSplitStackLayout(this); Dock = DefaultDock; AutoSize = true; CausesValidation = false; Size defaultSize = DefaultSize; SetAutoSizeMode(AutoSizeMode.GrowAndShrink); ShowItemToolTips = DefaultShowItemToolTips; ResumeLayout(true); } public ToolStrip(params ToolStripItem[] items) : this() { Items.AddRange(items); } internal ArrayList ActiveDropDowns { get { return activeDropDowns; } } // returns true when entered into menu mode through this toolstrip/menustrip // this is only really supported for menustrip active event, but to prevent casting everywhere... internal virtual bool KeyboardActive { get { return GetToolStripState(STATE_MENUACTIVE); } set { SetToolStripState(STATE_MENUACTIVE, value); } } // This is only for use in determining whether to show scroll bars on // ToolStripDropDownMenus. No one else should be using it for anything. internal virtual bool AllItemsVisible { get { return true; } set { // we do nothing in repsonse to a set, since we calculate the value above. } } [DefaultValue(true)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override bool AutoSize { get => base.AutoSize; set { if (IsInToolStripPanel && base.AutoSize && !value) { // Restoring the bounds can change the location of the toolstrip - // which would join it to a new row. Set the specified bounds to the new location to // prevent this. Rectangle bounds = CommonProperties.GetSpecifiedBounds(this); bounds.Location = Location; CommonProperties.UpdateSpecifiedBounds(this, bounds.X, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.Location); } base.AutoSize = value; } } [SRCategory(nameof(SR.CatPropertyChanged))] [SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] new public event EventHandler AutoSizeChanged { add => base.AutoSizeChanged += value; remove => base.AutoSizeChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool AutoScroll { get => base.AutoScroll; set { throw new NotSupportedException(SR.ToolStripDoesntSupportAutoScroll); } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Size AutoScrollMargin { get => base.AutoScrollMargin; set => base.AutoScrollMargin = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Size AutoScrollMinSize { get => base.AutoScrollMinSize; set => base.AutoScrollMinSize = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Point AutoScrollPosition { get => base.AutoScrollPosition; set => base.AutoScrollPosition = value; } public override bool AllowDrop { get => base.AllowDrop; set { if (value && AllowItemReorder) { throw new ArgumentException(SR.ToolStripAllowItemReorderAndAllowDropCannotBeSetToTrue); } base.AllowDrop = value; // if (value) { DropTargetManager.EnsureRegistered(this); } else { DropTargetManager.EnsureUnRegistered(this); } } } /// <summary> /// </summary> [DefaultValue(false)] [SRDescription(nameof(SR.ToolStripAllowItemReorderDescr))] [SRCategory(nameof(SR.CatBehavior))] public bool AllowItemReorder { get { return GetToolStripState(STATE_ALLOWITEMREORDER); } set { if (GetToolStripState(STATE_ALLOWITEMREORDER) != value) { if (AllowDrop && value) { throw new ArgumentException(SR.ToolStripAllowItemReorderAndAllowDropCannotBeSetToTrue); } SetToolStripState(STATE_ALLOWITEMREORDER, value); // if (value) { ToolStripSplitStackDragDropHandler dragDropHandler = new ToolStripSplitStackDragDropHandler(this); ItemReorderDropSource = dragDropHandler; ItemReorderDropTarget = dragDropHandler; DropTargetManager.EnsureRegistered(this); } else { DropTargetManager.EnsureUnRegistered(this); } } } } /// <summary> /// </summary> [DefaultValue(true)] [SRDescription(nameof(SR.ToolStripAllowMergeDescr))] [SRCategory(nameof(SR.CatBehavior))] public bool AllowMerge { get { return GetToolStripState(STATE_ALLOWMERGE); } set { if (GetToolStripState(STATE_ALLOWMERGE) != value) { SetToolStripState(STATE_ALLOWMERGE, value); } } } public override AnchorStyles Anchor { get => base.Anchor; set { // the base calls SetDock, which causes an OnDockChanged to be called // which forces two layouts of the parent. using (new LayoutTransaction(this, this, PropertyNames.Anchor)) { base.Anchor = value; } } } /// <summary> /// Just here so we can implement ShouldSerializeBackColor /// </summary> [SRDescription(nameof(SR.ToolStripBackColorDescr))] [SRCategory(nameof(SR.CatAppearance))] public new Color BackColor { get => base.BackColor; set => base.BackColor = value; } [SRCategory(nameof(SR.CatBehavior))] [SRDescription(nameof(SR.ToolStripOnBeginDrag))] public event EventHandler BeginDrag { add => Events.AddHandler(EventBeginDrag, value); remove => Events.RemoveHandler(EventBeginDrag, value); } public override BindingContext BindingContext { get { BindingContext bc = (BindingContext)Properties.GetObject(PropBindingContext); if (bc != null) { return bc; } // try the parent // Control p = ParentInternal; if (p != null && p.CanAccessProperties) { return p.BindingContext; } // we don't have a binding context return null; } set { if (Properties.GetObject(PropBindingContext) != value) { Properties.SetObject(PropBindingContext, value); // re-wire the bindings OnBindingContextChanged(EventArgs.Empty); } } } [DefaultValue(true)] [SRDescription(nameof(SR.ToolStripCanOverflowDescr))] [SRCategory(nameof(SR.CatLayout))] public bool CanOverflow { get { return GetToolStripState(STATE_CANOVERFLOW); } set { if (GetToolStripState(STATE_CANOVERFLOW) != value) { SetToolStripState(STATE_CANOVERFLOW, value); InvalidateLayout(); } } } /// <summary> we can only shift selection when we're not focused (someone mousing over us) /// or we are focused and one of our toolstripcontrolhosts do not have focus. /// SCENARIO: put focus in combo box, move the mouse over another item... selectioni /// should not shift until the combobox relinquishes its focus. /// </summary> internal bool CanHotTrack { get { if (!Focused) { // if ContainsFocus in one of the children = false, someone is just mousing by, we can hot track return (ContainsFocus == false); } else { // if the toolstrip itself contains focus we can definately hottrack. return true; } } } [Browsable(false)] [DefaultValue(false)] public new bool CausesValidation { get { // By default: CausesValidation is false for a ToolStrip // we want people to be able to use menus without validating // their controls. return base.CausesValidation; } set => base.CausesValidation = value; } [Browsable(false)] public new event EventHandler CausesValidationChanged { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new ControlCollection Controls { get => base.Controls; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event ControlEventHandler ControlAdded { add => base.ControlAdded += value; remove => base.ControlAdded -= value; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Cursor Cursor { get => base.Cursor; set => base.Cursor = value; } /// <summary> /// Hide browsable property /// </summary> [Browsable(false)] public new event EventHandler CursorChanged { add => base.CursorChanged += value; remove => base.CursorChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event ControlEventHandler ControlRemoved { add => base.ControlRemoved += value; remove => base.ControlRemoved -= value; } [SRCategory(nameof(SR.CatBehavior))] [SRDescription(nameof(SR.ToolStripOnEndDrag))] public event EventHandler EndDrag { add => Events.AddHandler(EventEndDrag, value); remove => Events.RemoveHandler(EventEndDrag, value); } public override Font Font { get { if (IsFontSet()) { return base.Font; } if (defaultFont == null) { // since toolstrip manager default font is thread static, hold onto a copy of the // pointer in an instance variable for perf so we dont have to keep fishing into // thread local storage for it. defaultFont = ToolStripManager.DefaultFont; } return defaultFont; } set => base.Font = value; } /// <summary> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </summary> protected override Size DefaultSize => DpiHelper.IsPerMonitorV2Awareness ? DpiHelper.LogicalToDeviceUnits(new Size(100, 25), DeviceDpi) : new Size(100, 25); protected override Padding DefaultPadding { get { // one pixel from the right edge to prevent the right border from painting over the // aligned-right toolstrip item. return scaledDefaultPadding; } } protected override Padding DefaultMargin { get { return Padding.Empty; } } protected virtual DockStyle DefaultDock { get { return DockStyle.Top; } } protected virtual Padding DefaultGripMargin { get { if (toolStripGrip != null) { return toolStripGrip.DefaultMargin; } else { return scaledDefaultGripMargin; } } } protected virtual bool DefaultShowItemToolTips { get { return true; } } [Browsable(false)] [SRDescription(nameof(SR.ToolStripDefaultDropDownDirectionDescr))] [SRCategory(nameof(SR.CatBehavior))] public virtual ToolStripDropDownDirection DefaultDropDownDirection { get { ToolStripDropDownDirection direction = toolStripDropDownDirection; if (direction == ToolStripDropDownDirection.Default) { if (Orientation == Orientation.Vertical) { if (IsInToolStripPanel) { // parent can be null when we're swapping between ToolStripPanels. DockStyle actualDock = (ParentInternal != null) ? ParentInternal.Dock : DockStyle.Left; direction = (actualDock == DockStyle.Right) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; if (DesignMode && actualDock == DockStyle.Left) { direction = ToolStripDropDownDirection.Right; } } else { direction = ((Dock == DockStyle.Right) && (RightToLeft == RightToLeft.No)) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; if (DesignMode && Dock == DockStyle.Left) { direction = ToolStripDropDownDirection.Right; } } } else { // horizontal DockStyle dock = Dock; if (IsInToolStripPanel && ParentInternal != null) { dock = ParentInternal.Dock; // we want the orientation of the ToolStripPanel; } if (dock == DockStyle.Bottom) { direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.AboveLeft : ToolStripDropDownDirection.AboveRight; } else { // assume Dock.Top direction = (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; } } } return direction; } set { // cant use Enum.IsValid as its not sequential switch (value) { case ToolStripDropDownDirection.AboveLeft: case ToolStripDropDownDirection.AboveRight: case ToolStripDropDownDirection.BelowLeft: case ToolStripDropDownDirection.BelowRight: case ToolStripDropDownDirection.Left: case ToolStripDropDownDirection.Right: case ToolStripDropDownDirection.Default: break; default: throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripDropDownDirection)); } toolStripDropDownDirection = value; } } /// <summary> /// Just here so we can add the default value attribute /// </summary> [DefaultValue(DockStyle.Top)] public override DockStyle Dock { get => base.Dock; set { if (value != Dock) { using (new LayoutTransaction(this, this, PropertyNames.Dock)) using (new LayoutTransaction(ParentInternal, this, PropertyNames.Dock)) { // We don't call base.Dock = value, because that would cause us to get 2 LocationChanged events. // The first is when the parent gets a Layout due to the DockChange, and the second comes from when we // change the orientation. Instead we've duplicated the logic of Control.Dock.set here, but with a // LayoutTransaction on the Parent as well. DefaultLayout.SetDock(this, value); UpdateLayoutStyle(Dock); } // This will cause the DockChanged event to fire. OnDockChanged(EventArgs.Empty); } } } /// <summary> /// Returns an owner window that can be used to /// own a drop down. /// </summary> internal virtual NativeWindow DropDownOwnerWindow { get { if (dropDownOwnerWindow == null) { dropDownOwnerWindow = new NativeWindow(); } if (dropDownOwnerWindow.Handle == IntPtr.Zero) { CreateParams cp = new CreateParams { ExStyle = (int)User32.WS_EX.TOOLWINDOW }; dropDownOwnerWindow.CreateHandle(cp); } return dropDownOwnerWindow; } } /// <summary> /// Returns the drop target manager that all the hwndless /// items and this ToolStrip share. this is necessary as /// RegisterDragDrop requires an HWND. /// </summary> internal ToolStripDropTargetManager DropTargetManager { get { if (dropTargetManager == null) { dropTargetManager = new ToolStripDropTargetManager(this); } return dropTargetManager; } set { dropTargetManager = value; } } /// <summary> /// Just here so we can add the default value attribute /// </summary> protected internal virtual ToolStripItemCollection DisplayedItems { get { if (displayedItems == null) { displayedItems = new ToolStripItemCollection(this, false); } return displayedItems; } } /// <summary> /// Retreives the current display rectangle. The display rectangle /// is the virtual display area that is used to layout components. /// The position and dimensions of the Form's display rectangle /// change during autoScroll. /// </summary> public override Rectangle DisplayRectangle { get { Rectangle rect = base.DisplayRectangle; if ((LayoutEngine is ToolStripSplitStackLayout) && (GripStyle == ToolStripGripStyle.Visible)) { if (Orientation == Orientation.Horizontal) { int gripwidth = Grip.GripThickness + Grip.Margin.Horizontal; rect.Width -= gripwidth; // in RTL.No we need to shift the rectangle rect.X += (RightToLeft == RightToLeft.No) ? gripwidth : 0; } else { // Vertical Grip placement int gripheight = Grip.GripThickness + Grip.Margin.Vertical; rect.Y += gripheight; rect.Height -= gripheight; } } return rect; } } /// <summary> /// Forecolor really has no meaning for ToolStrips - so lets hide it /// </summary> [Browsable(false)] public new Color ForeColor { get => base.ForeColor; set => base.ForeColor = value; } /// <summary> /// [ToolStrip ForeColorChanged event, overriden to turn browsing off.] /// </summary> [Browsable(false)] public new event EventHandler ForeColorChanged { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } private bool HasKeyboardInput { get { return (ContainsFocus || (ToolStripManager.ModalMenuFilter.InMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this)); } } internal ToolStripGrip Grip { get { if (toolStripGrip == null) { toolStripGrip = new ToolStripGrip { Overflow = ToolStripItemOverflow.Never, Visible = toolStripGripStyle == ToolStripGripStyle.Visible, AutoSize = false, ParentInternal = this, Margin = DefaultGripMargin }; } return toolStripGrip; } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripGripStyleDescr))] [DefaultValue(ToolStripGripStyle.Visible)] public ToolStripGripStyle GripStyle { get { return toolStripGripStyle; } set { //valid values are 0x0 to 0x1 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripGripStyle.Hidden, (int)ToolStripGripStyle.Visible)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripGripStyle)); } if (toolStripGripStyle != value) { toolStripGripStyle = value; Grip.Visible = toolStripGripStyle == ToolStripGripStyle.Visible; LayoutTransaction.DoLayout(this, this, PropertyNames.GripStyle); } } } [Browsable(false)] public ToolStripGripDisplayStyle GripDisplayStyle { get { return (LayoutStyle == ToolStripLayoutStyle.HorizontalStackWithOverflow) ? ToolStripGripDisplayStyle.Vertical : ToolStripGripDisplayStyle.Horizontal; } } /// <summary> /// The external spacing between the grip and the padding of the ToolStrip and the first item in the collection /// </summary> [SRCategory(nameof(SR.CatLayout))] [SRDescription(nameof(SR.ToolStripGripDisplayStyleDescr))] public Padding GripMargin { get { return Grip.Margin; } set { Grip.Margin = value; } } /// <summary> /// The boundaries of the grip on the ToolStrip. If it is invisible - returns Rectangle.Empty. /// </summary> [Browsable(false)] public Rectangle GripRectangle { get { return (GripStyle == ToolStripGripStyle.Visible) ? Grip.Bounds : Rectangle.Empty; } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool HasChildren { get => base.HasChildren; } internal bool HasVisibleItems { get { if (!IsHandleCreated) { foreach (ToolStripItem item in Items) { if (((IArrangedElement)item).ParticipatesInLayout) { // set in the state so that when the handle is created, we're accurate. SetToolStripState(STATE_HASVISIBLEITEMS, true); return true; } } SetToolStripState(STATE_HASVISIBLEITEMS, false); return false; } // after the handle is created, we start layout... so this state is cached. return GetToolStripState(STATE_HASVISIBLEITEMS); } set { SetToolStripState(STATE_HASVISIBLEITEMS, value); } } /// <summary> /// Gets the Horizontal Scroll bar for this ScrollableControl. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] new public HScrollProperties HorizontalScroll { get => base.HorizontalScroll; } [DefaultValue(typeof(Size), "16,16")] [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripImageScalingSizeDescr))] public Size ImageScalingSize { get { return ImageScalingSizeInternal; } set { ImageScalingSizeInternal = value; } } internal virtual Size ImageScalingSizeInternal { get { return imageScalingSize; } set { if (imageScalingSize != value) { imageScalingSize = value; LayoutTransaction.DoLayoutIf((Items.Count > 0), this, this, PropertyNames.ImageScalingSize); foreach (ToolStripItem item in Items) { item.OnImageScalingSizeChanged(EventArgs.Empty); } } } } /// <summary> /// Gets or sets the <see cref='Forms.ImageList'/> that contains the <see cref='Image'/> displayed on a label control. /// </summary> [DefaultValue(null)] [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripImageListDescr))] [Browsable(false)] public ImageList ImageList { get { return imageList; } set { if (imageList != value) { EventHandler handler = new EventHandler(ImageListRecreateHandle); // Remove the previous imagelist handle recreate handler // if (imageList != null) { imageList.RecreateHandle -= handler; } imageList = value; // Add the new imagelist handle recreate handler // if (value != null) { value.RecreateHandle += handler; } foreach (ToolStripItem item in Items) { item.InvalidateImageListImage(); } Invalidate(); } } } /// <summary> /// Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing). /// </summary> internal override bool IsMnemonicsListenerAxSourced { get { return true; } } internal bool IsInToolStripPanel { get { return ToolStripPanelRow != null; } } /// <summary> indicates whether the user is currently /// moving the toolstrip from one toolstrip container /// to another /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] public bool IsCurrentlyDragging { get { return GetToolStripState(STATE_DRAGGING); } } /// <summary> /// indicates if the SetBoundsCore is called thru Locationchanging. /// </summary> private bool IsLocationChanging { get { return GetToolStripState(STATE_LOCATIONCHANGING); } } /// <summary> /// The items that belong to this ToolStrip. /// Note - depending on space and layout preferences, not all items /// in this collection will be displayed. They may not even be displayed /// on this ToolStrip (say in the case where we're overflowing the item). /// The collection of _Displayed_ items is the DisplayedItems collection. /// The displayed items collection also includes things like the OverflowButton /// and the Grip. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [SRCategory(nameof(SR.CatData))] [SRDescription(nameof(SR.ToolStripItemsDescr))] [MergableProperty(false)] public virtual ToolStripItemCollection Items { get { if (toolStripItemCollection == null) { toolStripItemCollection = new ToolStripItemCollection(this, true); } return toolStripItemCollection; } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripItemAddedDescr))] public event ToolStripItemEventHandler ItemAdded { add => Events.AddHandler(EventItemAdded, value); remove => Events.RemoveHandler(EventItemAdded, value); } /// <summary> /// Occurs when the control is clicked. /// </summary> [SRCategory(nameof(SR.CatAction))] [SRDescription(nameof(SR.ToolStripItemOnClickDescr))] public event ToolStripItemClickedEventHandler ItemClicked { add => Events.AddHandler(EventItemClicked, value); remove => Events.RemoveHandler(EventItemClicked, value); } /// <summary> /// we have a backbuffer for painting items... this is cached to be the size of the largest /// item in the collection - and is cached in OnPaint, and disposed when the toolstrip /// is no longer visible. /// /// [: toolstrip - main hdc ] ← visible to user /// [ toolstrip double buffer hdc ] ← onpaint hands us this buffer, after we're done DBuf is copied to "main hdc"/ /// [tsi dc] ← we copy the background from the DBuf, then paint the item into this DC, then BitBlt back up to DBuf /// /// This is done because GDI wont honor GDI+ TranslateTransform. We used to use DCMapping to change the viewport /// origin and clipping rect of the toolstrip double buffer hdc to paint each item, but this proves costly /// because you need to allocate GDI+ Graphics objects for every single item. This method allows us to only /// allocate 1 Graphics object and share it between all the items in OnPaint. /// </summary> private CachedItemHdcInfo ItemHdcInfo { get { if (cachedItemHdcInfo == null) { cachedItemHdcInfo = new CachedItemHdcInfo(); } return cachedItemHdcInfo; } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripItemRemovedDescr))] public event ToolStripItemEventHandler ItemRemoved { add => Events.AddHandler(EventItemRemoved, value); remove => Events.RemoveHandler(EventItemRemoved, value); } /// <summary> handy check for painting and sizing </summary> [Browsable(false)] public bool IsDropDown { get { return (this is ToolStripDropDown); } } internal bool IsDisposingItems { get { return GetToolStripState(STATE_DISPOSINGITEMS); } } /// <summary> /// The OnDrag[blah] methods that will be called if AllowItemReorder is true. /// /// This allows us to have methods that handle drag/drop of the ToolStrip items /// without calling back on the user's code /// </summary> internal IDropTarget ItemReorderDropTarget { get { return itemReorderDropTarget; } set { itemReorderDropTarget = value; } } /// <summary> /// The OnQueryContinueDrag and OnGiveFeedback methods that will be called if /// AllowItemReorder is true. /// /// This allows us to have methods that handle drag/drop of the ToolStrip items /// without calling back on the user's code /// </summary> internal ISupportOleDropSource ItemReorderDropSource { get { return itemReorderDropSource; } set { itemReorderDropSource = value; } } internal bool IsInDesignMode { get { return DesignMode; } } internal bool IsSelectionSuspended { get { return GetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE); } } internal ToolStripItem LastMouseDownedItem { get { if (lastMouseDownedItem != null && (lastMouseDownedItem.IsDisposed || lastMouseDownedItem.ParentInternal != this)) { // handle disposal, parent changed since we last mouse downed. lastMouseDownedItem = null; } return lastMouseDownedItem; } } [DefaultValue(null)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public LayoutSettings LayoutSettings { get { return layoutSettings; } set { layoutSettings = value; } } /// <summary> /// Specifies whether we're horizontal or vertical /// </summary> [SRDescription(nameof(SR.ToolStripLayoutStyle))] [SRCategory(nameof(SR.CatLayout))] [AmbientValue(ToolStripLayoutStyle.StackWithOverflow)] public ToolStripLayoutStyle LayoutStyle { get { if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { switch (Orientation) { case Orientation.Horizontal: return ToolStripLayoutStyle.HorizontalStackWithOverflow; case Orientation.Vertical: return ToolStripLayoutStyle.VerticalStackWithOverflow; } } return layoutStyle; } set { //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripLayoutStyle.StackWithOverflow, (int)ToolStripLayoutStyle.Table)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripLayoutStyle)); } if (layoutStyle != value) { layoutStyle = value; switch (value) { case ToolStripLayoutStyle.Flow: if (!(layoutEngine is FlowLayout)) { layoutEngine = FlowLayout.Instance; } // Orientation really only applies to split stack layout (which swaps based on Dock, ToolStripPanel location) UpdateOrientation(Orientation.Horizontal); break; case ToolStripLayoutStyle.Table: if (!(layoutEngine is TableLayout)) { layoutEngine = TableLayout.Instance; } // Orientation really only applies to split stack layout (which swaps based on Dock, ToolStripPanel location) UpdateOrientation(Orientation.Horizontal); break; case ToolStripLayoutStyle.StackWithOverflow: case ToolStripLayoutStyle.HorizontalStackWithOverflow: case ToolStripLayoutStyle.VerticalStackWithOverflow: default: if (value != ToolStripLayoutStyle.StackWithOverflow) { UpdateOrientation((value == ToolStripLayoutStyle.VerticalStackWithOverflow) ? Orientation.Vertical : Orientation.Horizontal); } else { if (IsInToolStripPanel) { UpdateLayoutStyle(ToolStripPanelRow.Orientation); } else { UpdateLayoutStyle(Dock); } } if (!(layoutEngine is ToolStripSplitStackLayout)) { layoutEngine = new ToolStripSplitStackLayout(this); } break; } using (LayoutTransaction.CreateTransactionIf(IsHandleCreated, this, this, PropertyNames.LayoutStyle)) { LayoutSettings = CreateLayoutSettings(layoutStyle); } OnLayoutStyleChanged(EventArgs.Empty); } } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripLayoutCompleteDescr))] public event EventHandler LayoutCompleted { add => Events.AddHandler(EventLayoutCompleted, value); remove => Events.RemoveHandler(EventLayoutCompleted, value); } internal bool LayoutRequired { get { return layoutRequired; } set { layoutRequired = value; } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripLayoutStyleChangedDescr))] public event EventHandler LayoutStyleChanged { add => Events.AddHandler(EventLayoutStyleChanged, value); remove => Events.RemoveHandler(EventLayoutStyleChanged, value); } public override LayoutEngine LayoutEngine { get { // return layoutEngine; } } internal event ToolStripLocationCancelEventHandler LocationChanging { add => Events.AddHandler(EventLocationChanging, value); remove => Events.RemoveHandler(EventLocationChanging, value); } protected internal virtual Size MaxItemSize { get { return DisplayRectangle.Size; } } internal bool MenuAutoExpand { get { if (!DesignMode) { if (GetToolStripState(STATE_MENUAUTOEXPAND)) { if (!IsDropDown && !ToolStripManager.ModalMenuFilter.InMenuMode) { SetToolStripState(STATE_MENUAUTOEXPAND, false); return false; } return true; } } return false; } set { if (!DesignMode) { SetToolStripState(STATE_MENUAUTOEXPAND, value); } } } internal Stack<MergeHistory> MergeHistoryStack { get { if (mergeHistoryStack == null) { mergeHistoryStack = new Stack<MergeHistory>(); } return mergeHistoryStack; } } private MouseHoverTimer MouseHoverTimer { get { if (mouseHoverTimer == null) { mouseHoverTimer = new MouseHoverTimer(); } return mouseHoverTimer; } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] public ToolStripOverflowButton OverflowButton { get { if (toolStripOverflowButton == null) { toolStripOverflowButton = new ToolStripOverflowButton(this) { Overflow = ToolStripItemOverflow.Never, ParentInternal = this, Alignment = ToolStripItemAlignment.Right }; toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(DisplayRectangle.Size - Padding.Size); } return toolStripOverflowButton; } } // // internal ToolStripItemCollection OverflowItems { get { if (overflowItems == null) { overflowItems = new ToolStripItemCollection(this, false); } return overflowItems; } } [Browsable(false)] public Orientation Orientation { get { return orientation; } } [SRCategory(nameof(SR.CatAppearance))] [SRDescription(nameof(SR.ToolStripPaintGripDescr))] public event PaintEventHandler PaintGrip { add => Events.AddHandler(EventPaintGrip, value); remove => Events.RemoveHandler(EventPaintGrip, value); } internal RestoreFocusMessageFilter RestoreFocusFilter { get { if (restoreFocusFilter == null) { restoreFocusFilter = new RestoreFocusMessageFilter(this); } return restoreFocusFilter; } } internal ToolStripPanelCell ToolStripPanelCell { get { return ((ISupportToolStripPanel)this).ToolStripPanelCell; } } internal ToolStripPanelRow ToolStripPanelRow { get { return ((ISupportToolStripPanel)this).ToolStripPanelRow; } } // fetches the Cell associated with this toolstrip. ToolStripPanelCell ISupportToolStripPanel.ToolStripPanelCell { get { ToolStripPanelCell toolStripPanelCell = null; if (!IsDropDown && !IsDisposed) { if (Properties.ContainsObject(ToolStrip.PropToolStripPanelCell)) { toolStripPanelCell = (ToolStripPanelCell)Properties.GetObject(ToolStrip.PropToolStripPanelCell); } else { toolStripPanelCell = new ToolStripPanelCell(this); Properties.SetObject(ToolStrip.PropToolStripPanelCell, toolStripPanelCell); } } return toolStripPanelCell; } } ToolStripPanelRow ISupportToolStripPanel.ToolStripPanelRow { get { ToolStripPanelCell cell = ToolStripPanelCell; if (cell == null) { return null; } return ToolStripPanelCell.ToolStripPanelRow; } set { ToolStripPanelRow oldToolStripPanelRow = ToolStripPanelRow; if (oldToolStripPanelRow != value) { ToolStripPanelCell cell = ToolStripPanelCell; if (cell == null) { return; } cell.ToolStripPanelRow = value; if (value != null) { if (oldToolStripPanelRow == null || oldToolStripPanelRow.Orientation != value.Orientation) { if (layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { UpdateLayoutStyle(value.Orientation); } else { UpdateOrientation(value.Orientation); } } } else { if (oldToolStripPanelRow != null && oldToolStripPanelRow.ControlsInternal.Contains(this)) { oldToolStripPanelRow.ControlsInternal.Remove(this); } UpdateLayoutStyle(Dock); } } } } [DefaultValue(false)] [SRCategory(nameof(SR.CatLayout))] [SRDescription(nameof(SR.ToolStripStretchDescr))] public bool Stretch { get { return GetToolStripState(STATE_STRETCH); } set { if (Stretch != value) { SetToolStripState(STATE_STRETCH, value); } } } internal override bool SupportsUiaProviders => true; /// <summary> /// The renderer is used to paint the hwndless ToolStrip items. If someone wanted to /// change the "Hot" look of all of their buttons to be a green triangle, they should /// create a class that derives from ToolStripRenderer, assign it to this property and call /// invalidate. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ToolStripRenderer Renderer { get { if (IsDropDown) { // PERF: since this is called a lot we dont want to make it virtual ToolStripDropDown dropDown = this as ToolStripDropDown; if (dropDown is ToolStripOverflow || dropDown.IsAutoGenerated) { if (dropDown.OwnerToolStrip != null) { return dropDown.OwnerToolStrip.Renderer; } } } if (RenderMode == ToolStripRenderMode.ManagerRenderMode) { return ToolStripManager.Renderer; } // always return a valid renderer so our paint code // doesn't have to be bogged down by checks for null. SetToolStripState(STATE_USEDEFAULTRENDERER, false); if (renderer == null) { Renderer = ToolStripManager.CreateRenderer(RenderMode); } return renderer; } set { // if the value happens to be null, the next get // will autogenerate a new ToolStripRenderer. if (renderer != value) { SetToolStripState(STATE_USEDEFAULTRENDERER, (value == null)); renderer = value; currentRendererType = (renderer != null) ? renderer.GetType() : typeof(Type); OnRendererChanged(EventArgs.Empty); } } } public event EventHandler RendererChanged { add => Events.AddHandler(EventRendererChanged, value); remove => Events.RemoveHandler(EventRendererChanged, value); } [SRDescription(nameof(SR.ToolStripRenderModeDescr))] [SRCategory(nameof(SR.CatAppearance))] public ToolStripRenderMode RenderMode { get { if (GetToolStripState(STATE_USEDEFAULTRENDERER)) { return ToolStripRenderMode.ManagerRenderMode; } if (renderer != null && !renderer.IsAutoGenerated) { return ToolStripRenderMode.Custom; } // check the type of the currently set renderer. // types are cached as this may be called frequently. if (currentRendererType == ToolStripManager.s_professionalRendererType) { return ToolStripRenderMode.Professional; } if (currentRendererType == ToolStripManager.s_systemRendererType) { return ToolStripRenderMode.System; } return ToolStripRenderMode.Custom; } set { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripRenderMode.Custom, (int)ToolStripRenderMode.ManagerRenderMode)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripRenderMode)); } if (value == ToolStripRenderMode.Custom) { throw new NotSupportedException(SR.ToolStripRenderModeUseRendererPropertyInstead); } if (value == ToolStripRenderMode.ManagerRenderMode) { if (!GetToolStripState(STATE_USEDEFAULTRENDERER)) { SetToolStripState(STATE_USEDEFAULTRENDERER, true); OnRendererChanged(EventArgs.Empty); } } else { SetToolStripState(STATE_USEDEFAULTRENDERER, false); Renderer = ToolStripManager.CreateRenderer(value); } } } /// <summary> /// ToolStripItems need to access this to determine if they should be showing underlines /// for their accelerators. Since they are not HWNDs, and this method is protected on control /// we need a way for them to get at it. /// </summary> internal bool ShowKeyboardCuesInternal { get { return ShowKeyboardCues; } } [DefaultValue(true)] [SRDescription(nameof(SR.ToolStripShowItemToolTipsDescr))] [SRCategory(nameof(SR.CatBehavior))] public bool ShowItemToolTips { get { return showItemToolTips; } set { if (showItemToolTips != value) { showItemToolTips = value; if (!showItemToolTips) { UpdateToolTip(null); } ToolTip internalToolTip = ToolTip; foreach (ToolStripItem item in Items) { if (showItemToolTips) { KeyboardToolTipStateMachine.Instance.Hook(item, internalToolTip); } else { KeyboardToolTipStateMachine.Instance.Unhook(item, internalToolTip); } } // If the overflow button has not been created, don't check its properties // since this will force its creating and cause a re-layout of the control if (toolStripOverflowButton != null && OverflowButton.HasDropDownItems) { OverflowButton.DropDown.ShowItemToolTips = value; } } } } /// <summary> internal lookup table for shortcuts... intended to speed search time </summary> internal Hashtable Shortcuts { get { if (shortcuts == null) { shortcuts = new Hashtable(1); } return shortcuts; } } /// <summary> /// Indicates whether the user can give the focus to this control using the TAB /// key. This property is read-only. /// </summary> [SRCategory(nameof(SR.CatBehavior))] [DefaultValue(false)] [DispId((int)Ole32.DispatchID.TABSTOP)] [SRDescription(nameof(SR.ControlTabStopDescr))] public new bool TabStop { get => base.TabStop; set => base.TabStop = value; } /// <summary> this is the ToolTip used for the individual items /// it only works if ShowItemToolTips = true /// </summary> internal ToolTip ToolTip { get { ToolTip toolTip; if (!Properties.ContainsObject(ToolStrip.PropToolTip)) { toolTip = new ToolTip(); Properties.SetObject(ToolStrip.PropToolTip, toolTip); } else { toolTip = (ToolTip)Properties.GetObject(ToolStrip.PropToolTip); } return toolTip; } } [DefaultValue(ToolStripTextDirection.Horizontal)] [SRDescription(nameof(SR.ToolStripTextDirectionDescr))] [SRCategory(nameof(SR.CatAppearance))] public virtual ToolStripTextDirection TextDirection { get { ToolStripTextDirection textDirection = ToolStripTextDirection.Inherit; if (Properties.ContainsObject(ToolStrip.PropTextDirection)) { textDirection = (ToolStripTextDirection)Properties.GetObject(ToolStrip.PropTextDirection); } if (textDirection == ToolStripTextDirection.Inherit) { textDirection = ToolStripTextDirection.Horizontal; } return textDirection; } set { //valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolStripTextDirection.Inherit, (int)ToolStripTextDirection.Vertical270)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ToolStripTextDirection)); } Properties.SetObject(ToolStrip.PropTextDirection, value); using (new LayoutTransaction(this, this, "TextDirection")) { for (int i = 0; i < Items.Count; i++) { Items[i].OnOwnerTextDirectionChanged(); } } } } /// <summary> /// Gets the Vertical Scroll bar for this ScrollableControl. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] new public VScrollProperties VerticalScroll { get => base.VerticalScroll; } void ISupportToolStripPanel.BeginDrag() { OnBeginDrag(EventArgs.Empty); } // Internal so that it's not a public API. internal virtual void ChangeSelection(ToolStripItem nextItem) { if (nextItem != null) { ToolStripControlHost controlHost = nextItem as ToolStripControlHost; // if we contain focus, we should set focus to ourselves // so we get the focus off the thing that's currently focused // e.g. go from a text box to a toolstrip button if (ContainsFocus && !Focused) { Focus(); if (controlHost == null) { // if nextItem IS a toolstripcontrolhost, we're going to focus it anyways // we only fire KeyboardActive when "focusing" a non-hwnd backed item KeyboardActive = true; } } if (controlHost != null) { if (hwndThatLostFocus == IntPtr.Zero) { SnapFocus(User32.GetFocus()); } controlHost.Control.Select(); controlHost.Control.Focus(); } nextItem.Select(); if (nextItem is ToolStripMenuItem tsNextItem && !IsDropDown) { // only toplevel menus auto expand when the selection changes. tsNextItem.HandleAutoExpansion(); } } } protected virtual LayoutSettings CreateLayoutSettings(ToolStripLayoutStyle layoutStyle) { switch (layoutStyle) { case ToolStripLayoutStyle.Flow: return new FlowLayoutSettings(this); case ToolStripLayoutStyle.Table: return new TableLayoutSettings(this); default: return null; } } protected internal virtual ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) { if (text == "-") { return new ToolStripSeparator(); } else { return new ToolStripButton(text, image, onClick); } } private void ClearAllSelections() { ClearAllSelectionsExcept(null); } private void ClearAllSelectionsExcept(ToolStripItem item) { Rectangle regionRect = (item == null) ? Rectangle.Empty : item.Bounds; Region region = null; try { for (int i = 0; i < DisplayedItems.Count; i++) { if (DisplayedItems[i] == item) { continue; } else if (item != null && DisplayedItems[i].Pressed) { // if (DisplayedItems[i] is ToolStripDropDownItem dropDownItem && dropDownItem.HasDropDownItems) { dropDownItem.AutoHide(item); } } bool invalidate = false; if (DisplayedItems[i].Selected) { DisplayedItems[i].Unselect(); Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG ClearAllSelectionsExcept] Unselecting " + DisplayedItems[i].Text); invalidate = true; } if (invalidate) { // since regions are heavy weight - only use if we need it. if (region == null) { region = new Region(regionRect); } region.Union(DisplayedItems[i].Bounds); } } // force an WM_PAINT to happen now to instantly reflect the selection change. if (region != null) { Invalidate(region, true); Update(); } else if (regionRect != Rectangle.Empty) { Invalidate(regionRect, true); Update(); } } finally { if (region != null) { region.Dispose(); } } // fire accessibility if (IsHandleCreated && item != null) { int focusIndex = DisplayedItems.IndexOf(item); AccessibilityNotifyClients(AccessibleEvents.Focus, focusIndex); } } internal void ClearInsertionMark() { if (lastInsertionMarkRect != Rectangle.Empty) { // stuff away the lastInsertionMarkRect // and clear it out _before_ we call paint OW // the call to invalidate wont help as it will get // repainted. Rectangle invalidate = lastInsertionMarkRect; lastInsertionMarkRect = Rectangle.Empty; Invalidate(invalidate); } } private void ClearLastMouseDownedItem() { ToolStripItem lastItem = lastMouseDownedItem; lastMouseDownedItem = null; if (IsSelectionSuspended) { SetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE, false); if (lastItem != null) { lastItem.Invalidate(); } } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { ToolStripOverflow overflow = GetOverflow(); try { SuspendLayout(); if (overflow != null) { overflow.SuspendLayout(); } // if there's a problem in config, dont be a leaker. SetToolStripState(STATE_DISPOSINGITEMS, true); lastMouseDownedItem = null; HookStaticEvents(/*hook=*/false); if (Properties.GetObject(ToolStrip.PropToolStripPanelCell) is ToolStripPanelCell toolStripPanelCell) { toolStripPanelCell.Dispose(); } if (cachedItemHdcInfo != null) { cachedItemHdcInfo.Dispose(); } if (mouseHoverTimer != null) { mouseHoverTimer.Dispose(); } ToolTip toolTip = (ToolTip)Properties.GetObject(ToolStrip.PropToolTip); if (toolTip != null) { toolTip.Dispose(); } if (!Items.IsReadOnly) { // only dispose the items we actually own. for (int i = Items.Count - 1; i >= 0; i--) { Items[i].Dispose(); } Items.Clear(); } // clean up items not in the Items list if (toolStripGrip != null) { toolStripGrip.Dispose(); } if (toolStripOverflowButton != null) { toolStripOverflowButton.Dispose(); } // remove the restore focus filter if (restoreFocusFilter != null) { // PERF, Application.ThreadContext.FromCurrent().RemoveMessageFilter(restoreFocusFilter); restoreFocusFilter = null; } // exit menu mode if necessary. bool exitMenuMode = false; if (ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) { exitMenuMode = true; } ToolStripManager.ModalMenuFilter.RemoveActiveToolStrip(this); // if we were the last toolstrip in the queue, exit menu mode. if (exitMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == null) { Debug.WriteLineIf(ToolStrip.SnapFocusDebug.TraceVerbose, "Exiting menu mode because we're the last toolstrip in the queue, and we've disposed."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); } ToolStripManager.ToolStrips.Remove(this); } finally { ResumeLayout(false); if (overflow != null) { overflow.ResumeLayout(false); } SetToolStripState(STATE_DISPOSINGITEMS, false); } } base.Dispose(disposing); } internal void DoLayoutIfHandleCreated(ToolStripItemEventArgs e) { if (IsHandleCreated) { LayoutTransaction.DoLayout(this, e.Item, PropertyNames.Items); Invalidate(); // Adding this item may have added it to the overflow // However, we can't check if it's in OverflowItems, because // it gets added there in Layout, and layout might be suspended. if (CanOverflow && OverflowButton.HasDropDown) { if (DeferOverflowDropDownLayout()) { CommonProperties.xClearPreferredSizeCache(OverflowButton.DropDown); OverflowButton.DropDown.LayoutRequired = true; } else { LayoutTransaction.DoLayout(OverflowButton.DropDown, e.Item, PropertyNames.Items); OverflowButton.DropDown.Invalidate(); } } } else { // next time we fetch the preferred size, recalc it. CommonProperties.xClearPreferredSizeCache(this); LayoutRequired = true; if (CanOverflow && OverflowButton.HasDropDown) { OverflowButton.DropDown.LayoutRequired = true; } } } private bool DeferOverflowDropDownLayout() { return IsLayoutSuspended || !OverflowButton.DropDown.Visible || !OverflowButton.DropDown.IsHandleCreated; } void ISupportToolStripPanel.EndDrag() { ToolStripPanel.ClearDragFeedback(); OnEndDrag(EventArgs.Empty); } internal ToolStripOverflow GetOverflow() { return (toolStripOverflowButton == null || !toolStripOverflowButton.HasDropDown) ? null : toolStripOverflowButton.DropDown as ToolStripOverflow; } internal byte GetMouseId() { // never return 0 as the mousedown ID, this is the "reset" value. if (mouseDownID == 0) { mouseDownID++; } return mouseDownID; } internal virtual ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) { if (rtlAware && RightToLeft == RightToLeft.Yes) { if (direction == ArrowDirection.Right) { direction = ArrowDirection.Left; } else if (direction == ArrowDirection.Left) { direction = ArrowDirection.Right; } } return GetNextItem(start, direction); } /// <summary> /// Gets the next item from the given start item in the direction specified. /// - This function wraps if at the end /// - This function will only surf the items in the current container /// - Overriding this function will change the tab ordering and accessible child ordering. /// </summary> public virtual ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction) { switch (direction) { case ArrowDirection.Right: return GetNextItemHorizontal(start, forward: true); case ArrowDirection.Left: bool isRtl = RightToLeft == RightToLeft.Yes; bool forward = (LastKeyData == (Keys.Shift | Keys.Tab) && !isRtl) || (LastKeyData == Keys.Tab && isRtl); return GetNextItemHorizontal(start, forward); case ArrowDirection.Down: return GetNextItemVertical(start, down: true); case ArrowDirection.Up: return GetNextItemVertical(start, down: false); default: throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(ArrowDirection)); } } /// <remarks> /// Helper function for GetNextItem - do not directly call this. /// </remarks> private ToolStripItem GetNextItemHorizontal(ToolStripItem start, bool forward) { if (DisplayedItems.Count <= 0) { return null; } ToolStripDropDown dropDown = this as ToolStripDropDown; if (start == null) { // The navigation should be consistent when navigating in forward and // backward direction entering the toolstrip, it means that the first // toolstrip item should be selected irrespectively TAB or SHIFT+TAB // is pressed. start = GetStartItem(forward, dropDown != null); } int current = DisplayedItems.IndexOf(start); if (current == -1) { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "Started from a visible = false item"); return null; } Debug.WriteLineIf(SelectionDebug.TraceVerbose && (current != -1), "[SelectDBG GetNextToolStripItem] Last selected item was " + ((current != -1) ? DisplayedItems[current].Text : "")); Debug.WriteLineIf(SelectionDebug.TraceVerbose && (current == -1), "[SelectDBG GetNextToolStripItem] Last selected item was null"); int count = DisplayedItems.Count; do { if (forward) { current = ++current % count; } else { // provide negative wrap if necessary current = (--current < 0) ? count + current : current; } if (dropDown?.OwnerItem != null && dropDown.OwnerItem.IsInDesignMode) { return DisplayedItems[current]; } if (DisplayedItems[current].CanKeyboardSelect) { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG GetNextToolStripItem] selecting " + DisplayedItems[current].Text); //ClearAllSelectionsExcept(Items[current]); return DisplayedItems[current]; } } while (DisplayedItems[current] != start); return null; } private ToolStripItem GetStartItem(bool forward, bool isDropDown) { if (forward) { return DisplayedItems[DisplayedItems.Count - 1]; } if (!isDropDown) { // For the drop-down up-directed loop should be preserved. // So if the current item is topmost, then the bottom item should be selected on up-key press. return DisplayedItems[DisplayedItems.Count > 1 ? 1 : 0]; } return DisplayedItems[0]; } /// <remarks> /// Helper function for GetNextItem - do not directly call this. /// </remarks> private ToolStripItem GetNextItemVertical(ToolStripItem selectedItem, bool down) { ToolStripItem tanWinner = null; ToolStripItem hypotenuseWinner = null; double minHypotenuse = double.MaxValue; double minTan = double.MaxValue; double hypotenuseOfTanWinner = double.MaxValue; double tanOfHypotenuseWinner = double.MaxValue; if (selectedItem == null) { ToolStripItem item = GetNextItemHorizontal(selectedItem, down); return item; } if (this is ToolStripDropDown dropDown && dropDown.OwnerItem != null && (dropDown.OwnerItem.IsInDesignMode || (dropDown.OwnerItem.Owner != null && dropDown.OwnerItem.Owner.IsInDesignMode))) { ToolStripItem item = GetNextItemHorizontal(selectedItem, down); return item; } Point midPointOfCurrent = new Point(selectedItem.Bounds.X + selectedItem.Width / 2, selectedItem.Bounds.Y + selectedItem.Height / 2); for (int i = 0; i < DisplayedItems.Count; i++) { ToolStripItem otherItem = DisplayedItems[i]; if (otherItem == selectedItem || !otherItem.CanKeyboardSelect) { continue; } if (!down && otherItem.Bounds.Bottom > selectedItem.Bounds.Top) { // if we are going up the other control has to be above continue; } else if (down && otherItem.Bounds.Top < selectedItem.Bounds.Bottom) { // if we are going down the other control has to be below continue; } //[ otherControl ] // * Point otherItemMidLocation = new Point(otherItem.Bounds.X + otherItem.Width / 2, (down) ? otherItem.Bounds.Top : otherItem.Bounds.Bottom); int oppositeSide = otherItemMidLocation.X - midPointOfCurrent.X; int adjacentSide = otherItemMidLocation.Y - midPointOfCurrent.Y; // use pythagrian theorem to calculate the length of the distance // between the middle of the current control in question and it's adjacent // objects. double hypotenuse = Math.Sqrt(adjacentSide * adjacentSide + oppositeSide * oppositeSide); if (adjacentSide != 0) { // avoid divide by zero - we dont do layered controls // _[o] // |/ // [s] // get the angle between s and o by taking the arctan. // PERF consider using approximation instead double tan = Math.Abs(Math.Atan(oppositeSide / adjacentSide)); // we want the thing with the smallest angle and smallest distance between midpoints minTan = Math.Min(minTan, tan); minHypotenuse = Math.Min(minHypotenuse, hypotenuse); if (minTan == tan && !double.IsNaN(minTan)) { tanWinner = otherItem; hypotenuseOfTanWinner = hypotenuse; } if (minHypotenuse == hypotenuse) { hypotenuseWinner = otherItem; tanOfHypotenuseWinner = tan; } } } if ((tanWinner == null) || (hypotenuseWinner == null)) { return (GetNextItemHorizontal(null, down)); } // often times the guy with the best angle will be the guy with the closest hypotenuse. // however in layouts where things are more randomly spaced, this is not necessarily the case. if (tanOfHypotenuseWinner == minTan) { // if the angles match up, such as in the case of items of the same width in vertical flow // then pick the closest one. return hypotenuseWinner; } if ((!down && tanWinner.Bounds.Bottom <= hypotenuseWinner.Bounds.Top) || (down && tanWinner.Bounds.Top > hypotenuseWinner.Bounds.Bottom)) { // we prefer the case where the angle is smaller than // the case where the hypotenuse is smaller. The only // scenarios where that is not the case is when the hypoteneuse // winner is clearly closer than the angle winner. // [a.winner] | [s] // | [h.winner] // [h.winner] | // [s] | [a.winner] return hypotenuseWinner; } return tanWinner; } internal override Size GetPreferredSizeCore(Size proposedSize) { // We act like a container control // Translating 0,0 from ClientSize to actual Size tells us how much space // is required for the borders. if (proposedSize.Width == 1) { proposedSize.Width = int.MaxValue; } if (proposedSize.Height == 1) { proposedSize.Height = int.MaxValue; } Padding padding = Padding; Size prefSize = LayoutEngine.GetPreferredSize(this, proposedSize - padding.Size); Padding newPadding = Padding; // as a side effect of some of the layouts, we can change the padding. // if this happens, we need to clear the cache. if (padding != newPadding) { CommonProperties.xClearPreferredSizeCache(this); } return prefSize + newPadding.Size; } #region GetPreferredSizeHelpers // // These are here so they can be shared between splitstack layout and StatusStrip // internal static Size GetPreferredSizeHorizontal(IArrangedElement container, Size proposedConstraints) { Size maxSize = Size.Empty; ToolStrip toolStrip = container as ToolStrip; // ensure preferred size respects default size as a minimum. Size defaultSize = toolStrip.DefaultSize - toolStrip.Padding.Size; maxSize.Height = Math.Max(0, defaultSize.Height); bool requiresOverflow = false; bool foundItemParticipatingInLayout = false; for (int j = 0; j < toolStrip.Items.Count; j++) { ToolStripItem item = toolStrip.Items[j]; if (((IArrangedElement)item).ParticipatesInLayout) { foundItemParticipatingInLayout = true; if (item.Overflow != ToolStripItemOverflow.Always) { Padding itemMargin = item.Margin; Size prefItemSize = GetPreferredItemSize(item); maxSize.Width += itemMargin.Horizontal + prefItemSize.Width; maxSize.Height = Math.Max(maxSize.Height, itemMargin.Vertical + prefItemSize.Height); } else { requiresOverflow = true; } } } if (toolStrip.Items.Count == 0 || (!foundItemParticipatingInLayout)) { // if there are no items there, create something anyways. maxSize = defaultSize; } if (requiresOverflow) { // add in the width of the overflow button ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; Padding overflowItemMargin = overflowItem.Margin; maxSize.Width += overflowItemMargin.Horizontal + overflowItem.Bounds.Width; } else { maxSize.Width += 2; //add Padding of 2 Pixels to the right if not Overflow. } if (toolStrip.GripStyle == ToolStripGripStyle.Visible) { // add in the grip width Padding gripMargin = toolStrip.GripMargin; maxSize.Width += gripMargin.Horizontal + toolStrip.Grip.GripThickness; } maxSize = LayoutUtils.IntersectSizes(maxSize, proposedConstraints); return maxSize; } internal static Size GetPreferredSizeVertical(IArrangedElement container, Size proposedConstraints) { Size maxSize = Size.Empty; bool requiresOverflow = false; ToolStrip toolStrip = container as ToolStrip; bool foundItemParticipatingInLayout = false; for (int j = 0; j < toolStrip.Items.Count; j++) { ToolStripItem item = toolStrip.Items[j]; if (((IArrangedElement)item).ParticipatesInLayout) { foundItemParticipatingInLayout = true; if (item.Overflow != ToolStripItemOverflow.Always) { Size preferredSize = GetPreferredItemSize(item); Padding itemMargin = item.Margin; maxSize.Height += itemMargin.Vertical + preferredSize.Height; maxSize.Width = Math.Max(maxSize.Width, itemMargin.Horizontal + preferredSize.Width); } else { requiresOverflow = true; } } } if (toolStrip.Items.Count == 0 || !foundItemParticipatingInLayout) { // if there are no items there, create something anyways. maxSize = LayoutUtils.FlipSize(toolStrip.DefaultSize); } if (requiresOverflow) { // add in the width of the overflow button ToolStripOverflowButton overflowItem = toolStrip.OverflowButton; Padding overflowItemMargin = overflowItem.Margin; maxSize.Height += overflowItemMargin.Vertical + overflowItem.Bounds.Height; } else { maxSize.Height += 2; //add Padding to the bottom if not Overflow. } if (toolStrip.GripStyle == ToolStripGripStyle.Visible) { // add in the grip width Padding gripMargin = toolStrip.GripMargin; maxSize.Height += gripMargin.Vertical + toolStrip.Grip.GripThickness; } // note here the difference in vertical - we want the strings to fit perfectly so we're not going to constrain by the specified size. if (toolStrip.Size != maxSize) { CommonProperties.xClearPreferredSizeCache(toolStrip); } return maxSize; } private static Size GetPreferredItemSize(ToolStripItem item) { return item.AutoSize ? item.GetPreferredSize(Size.Empty) : item.Size; } #endregion internal static Graphics GetMeasurementGraphics() { return WindowsFormsUtils.CreateMeasurementGraphics(); } internal ToolStripItem GetSelectedItem() { ToolStripItem selectedItem = null; for (int i = 0; i < DisplayedItems.Count; i++) { if (DisplayedItems[i].Selected) { selectedItem = DisplayedItems[i]; } } return selectedItem; } /// <summary> /// Retrieves the current value of the specified bit in the control's state. /// </summary> internal bool GetToolStripState(int flag) { return (toolStripState & flag) != 0; } internal virtual ToolStrip GetToplevelOwnerToolStrip() { return this; } /// In the case of a /// toolstrip -> toolstrip /// contextmenustrip -> the control that is showing it /// toolstripdropdown -> top most toolstrip internal virtual Control GetOwnerControl() { return this; } private void HandleMouseLeave() { // If we had a particular item that was "entered" // notify it that we have left. if (lastMouseActiveItem != null) { if (!DesignMode) { MouseHoverTimer.Cancel(lastMouseActiveItem); } try { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "firing mouse leave on " + lastMouseActiveItem.ToString()); lastMouseActiveItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseLeave); } finally { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "setting last active item to null"); lastMouseActiveItem = null; } } ToolStripMenuItem.MenuTimer.HandleToolStripMouseLeave(this); } internal void HandleItemClick(ToolStripItem dismissingItem) { ToolStripItemClickedEventArgs e = new ToolStripItemClickedEventArgs(dismissingItem); OnItemClicked(e); // Ensure both the overflow and the main toolstrip fire ItemClick event // otherwise the overflow wont dismiss. if (!IsDropDown && dismissingItem.IsOnOverflow) { OverflowButton.DropDown.HandleItemClick(dismissingItem); } } internal virtual void HandleItemClicked(ToolStripItem dismissingItem) { // post processing after the click has happened. if (dismissingItem is ToolStripDropDownItem item && !item.HasDropDownItems) { KeyboardActive = false; } } private void HookStaticEvents(bool hook) { if (hook) { if (!alreadyHooked) { try { ToolStripManager.RendererChanged += new EventHandler(OnDefaultRendererChanged); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } finally { alreadyHooked = true; } } } else if (alreadyHooked) { try { ToolStripManager.RendererChanged -= new EventHandler(OnDefaultRendererChanged); SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); } finally { alreadyHooked = false; } } } //initialize ToolStrip private void InitializeRenderer(ToolStripRenderer renderer) { // wrap this in a LayoutTransaction so that if they change sizes // in this method we've suspended layout. using (LayoutTransaction.CreateTransactionIf(AutoSize, this, this, PropertyNames.Renderer)) { renderer.Initialize(this); for (int i = 0; i < Items.Count; i++) { renderer.InitializeItem(Items[i]); } } Invalidate(Controls.Count > 0); } // sometimes you only want to force a layout if the ToolStrip is visible. private void InvalidateLayout() { if (IsHandleCreated) { LayoutTransaction.DoLayout(this, this, null); } } internal void InvalidateTextItems() { using (new LayoutTransaction(this, this, "ShowKeyboardFocusCues", /*PerformLayout=*/Visible)) { for (int j = 0; j < DisplayedItems.Count; j++) { if (((DisplayedItems[j].DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text)) { DisplayedItems[j].InvalidateItemLayout("ShowKeyboardFocusCues"); } } } } protected override bool IsInputKey(Keys keyData) { ToolStripItem item = GetSelectedItem(); if ((item != null) && item.IsInputKey(keyData)) { return true; } return base.IsInputKey(keyData); } protected override bool IsInputChar(char charCode) { ToolStripItem item = GetSelectedItem(); if ((item != null) && item.IsInputChar(charCode)) { return true; } return base.IsInputChar(charCode); } private static bool IsPseudoMnemonic(char charCode, string text) { if (!string.IsNullOrEmpty(text)) { if (!WindowsFormsUtils.ContainsMnemonic(text)) { char charToCompare = char.ToUpper(charCode, CultureInfo.CurrentCulture); char firstLetter = char.ToUpper(text[0], CultureInfo.CurrentCulture); if (firstLetter == charToCompare || (char.ToLower(charCode, CultureInfo.CurrentCulture) == char.ToLower(text[0], CultureInfo.CurrentCulture))) { return true; } } } return false; } /// <summary> Force an item to be painted immediately, rather than waiting for WM_PAINT to occur. </summary> internal void InvokePaintItem(ToolStripItem item) { // Force a WM_PAINT to happen NOW. Invalidate(item.Bounds); Update(); } /// <summary> /// Gets or sets the <see cref='Forms.ImageList'/> that contains the <see cref='Image'/> displayed on a label control /// </summary> private void ImageListRecreateHandle(object sender, EventArgs e) { Invalidate(); } /// <summary> /// This override fires the LocationChanging event if /// 1) We are not currently Rafting .. since this cause this infinite times... /// 2) If we havent been called once .. Since the "LocationChanging" is listened to by the RaftingCell and calls "JOIN" which may call us back. /// </summary> protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { Point location = Location; if (!IsCurrentlyDragging && !IsLocationChanging && IsInToolStripPanel) { ToolStripLocationCancelEventArgs cae = new ToolStripLocationCancelEventArgs(new Point(x, y), false); try { if (location.X != x || location.Y != y) { SetToolStripState(STATE_LOCATIONCHANGING, true); OnLocationChanging(cae); } if (!cae.Cancel) { base.SetBoundsCore(x, y, width, height, specified); } } finally { SetToolStripState(STATE_LOCATIONCHANGING, false); } } else { if (IsCurrentlyDragging) { Region transparentRegion = Renderer.GetTransparentRegion(this); if (transparentRegion != null && (location.X != x || location.Y != y)) { try { Invalidate(transparentRegion); Update(); } finally { transparentRegion.Dispose(); } } } SetToolStripState(STATE_LOCATIONCHANGING, false); base.SetBoundsCore(x, y, width, height, specified); } } internal void PaintParentRegion(Graphics g, Region region) { } internal bool ProcessCmdKeyInternal(ref Message m, Keys keyData) { return ProcessCmdKey(ref m, keyData); } // This function will print to the PrinterDC. ToolStrip have there own buffered painting and doesnt play very well // with the DC translations done by base Control class. Hence we do our own Painting and the BitBLT the DC into the printerDc. private protected override void PrintToMetaFileRecursive(IntPtr hDC, IntPtr lParam, Rectangle bounds) { using (Bitmap image = new Bitmap(bounds.Width, bounds.Height)) using (Graphics g = Graphics.FromImage(image)) { IntPtr imageHdc = g.GetHdc(); try { //send the actual wm_print message User32.SendMessageW( this, User32.WM.PRINT, (IntPtr)imageHdc, (IntPtr)(User32.PRF.CHILDREN | User32.PRF.CLIENT | User32.PRF.ERASEBKGND | User32.PRF.NONCLIENT)); // Now BLT the result to the destination bitmap. Gdi32.BitBlt( new HandleRef(this, hDC), bounds.X, bounds.Y, bounds.Width, bounds.Height, new HandleRef(g, imageHdc), 0, 0, Gdi32.ROP.SRCCOPY); } finally { g.ReleaseHdcInternal(imageHdc); } } } protected override bool ProcessCmdKey(ref Message m, Keys keyData) { if (ToolStripManager.IsMenuKey(keyData)) { if (!IsDropDown && ToolStripManager.ModalMenuFilter.InMenuMode) { ClearAllSelections(); ToolStripManager.ModalMenuFilter.MenuKeyToggle = true; Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.ProcessCmdKey] Detected a second ALT keypress while in Menu Mode."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); } } // Give the ToolStripItem very first chance at // processing keys (except for ALT handling) ToolStripItem selectedItem = GetSelectedItem(); if (selectedItem != null) { if (selectedItem.ProcessCmdKey(ref m, keyData)) { return true; } } foreach (ToolStripItem item in Items) { if (item == selectedItem) { continue; } if (item.ProcessCmdKey(ref m, keyData)) { return true; } } if (!IsDropDown) { bool isControlTab = (keyData & Keys.Control) == Keys.Control && (keyData & Keys.KeyCode) == Keys.Tab; if (isControlTab && !TabStop && HasKeyboardInput) { bool handled = false; if ((keyData & Keys.Shift) == Keys.None) { handled = ToolStripManager.SelectNextToolStrip(this, /*forward*/true); } else { handled = ToolStripManager.SelectNextToolStrip(this, /*forward*/false); } if (handled) { return true; } } } return base.ProcessCmdKey(ref m, keyData); } /// <summary> /// Processes a dialog key. Overrides Control.processDialogKey(). This /// method implements handling of the TAB, LEFT, RIGHT, UP, and DOWN /// keys in dialogs. /// The method performs no processing on keys that include the ALT or /// CONTROL modifiers. For the TAB key, the method selects the next control /// on the form. For the arrow keys, /// !!! /// </summary> protected override bool ProcessDialogKey(Keys keyData) { bool retVal = false; LastKeyData = keyData; // Give the ToolStripItem first dibs ToolStripItem item = GetSelectedItem(); if (item != null) { if (item.ProcessDialogKey(keyData)) { return true; } } // if the ToolStrip receives an escape, then we // should send the focus back to the last item that // had focus. bool hasModifiers = ((keyData & (Keys.Alt | Keys.Control)) != Keys.None); Keys keyCode = (Keys)keyData & Keys.KeyCode; switch (keyCode) { case Keys.Back: // if it's focused itself, process. if it's not focused, make sure a child control // doesnt have focus before processing if (!ContainsFocus) { // shift backspace/backspace work as backspace, which is the same as shift+tab retVal = ProcessTabKey(false); } break; case Keys.Tab: // ctrl+tab does nothing if (!hasModifiers) { retVal = ProcessTabKey((keyData & Keys.Shift) == Keys.None); } break; case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: retVal = ProcessArrowKey(keyCode); break; case Keys.Home: SelectNextToolStripItem(null, /*forward =*/ true); retVal = true; break; case Keys.End: SelectNextToolStripItem(null, /*forward =*/ false); retVal = true; break; case Keys.Escape: // escape and menu key should restore focus // ctrl+esc does nothing if (!hasModifiers && !TabStop) { RestoreFocusInternal(); retVal = true; } break; } if (retVal) { return retVal; } Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] calling base"); return base.ProcessDialogKey(keyData); } internal virtual void ProcessDuplicateMnemonic(ToolStripItem item, char charCode) { if (!CanProcessMnemonic()) { // Checking again for security... return; } // if (item != null) { // SetFocusUnsafe(); item.Select(); } } /// <summary> /// Rules for parsing mnemonics /// PASS 1: Real mnemonics /// Check items for the character after the &amp;. If it matches, perform the click event or open the dropdown (in the case that it has dropdown items) /// PASS 2: Fake mnemonics /// Begin with the current selection and parse through the first character in the items in the menu. /// If there is only one item that matches /// perform the click event or open the dropdown (in the case that it has dropdown items) /// Else /// change the selection from the current selected item to the first item that matched. /// </summary> protected internal override bool ProcessMnemonic(char charCode) { // menus and toolbars only take focus on ALT if (!CanProcessMnemonic()) { return false; } if (Focused || ContainsFocus) { return ProcessMnemonicInternal(charCode); } bool inMenuMode = ToolStripManager.ModalMenuFilter.InMenuMode; if (!inMenuMode && Control.ModifierKeys == Keys.Alt) { // This is the case where someone hasnt released the ALT key yet, but has pushed another letter. // In some cases we can activate the menu that is not the MainMenuStrip... return ProcessMnemonicInternal(charCode); } else if (inMenuMode && ToolStripManager.ModalMenuFilter.GetActiveToolStrip() == this) { return ProcessMnemonicInternal(charCode); } // do not call base, as we dont want to walk through the controls collection and reprocess everything // we should have processed in the displayed items collection. return false; } private bool ProcessMnemonicInternal(char charCode) { if (!CanProcessMnemonic()) { // Checking again for security... return false; } // at this point we assume we can process mnemonics as process mnemonic has filtered for use. ToolStripItem startingItem = GetSelectedItem(); int startIndex = 0; if (startingItem != null) { startIndex = DisplayedItems.IndexOf(startingItem); } startIndex = Math.Max(0, startIndex); ToolStripItem firstMatch = null; bool foundMenuItem = false; int index = startIndex; // PASS1, iterate through the real mnemonics for (int i = 0; i < DisplayedItems.Count; i++) { ToolStripItem currentItem = DisplayedItems[index]; index = (index + 1) % DisplayedItems.Count; if (string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) { continue; } // Only items which display text should be processed if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) { continue; } // keep track whether we've found a menu item - we'll have to do a // second pass for fake mnemonics in that case. foundMenuItem = (foundMenuItem || (currentItem is ToolStripMenuItem)); if (Control.IsMnemonic(charCode, currentItem.Text)) { if (firstMatch == null) { firstMatch = currentItem; } else { // we've found a second match - we should only change selection. if (firstMatch == startingItem) { // change the selection to be the second match as the first is already selected ProcessDuplicateMnemonic(currentItem, charCode); } else { ProcessDuplicateMnemonic(firstMatch, charCode); } // we've found two mnemonics, just return. return true; } } } // We've found a singular match. if (firstMatch != null) { return firstMatch.ProcessMnemonic(charCode); } if (!foundMenuItem) { return false; } index = startIndex; // MenuStrip parity: key presses should change selection if mnemonic not present // if we havent found a mnemonic, cycle through the menu items and // checbbbMk if we match. // PASS2, iterate through the pseudo mnemonics for (int i = 0; i < DisplayedItems.Count; i++) { ToolStripItem currentItem = DisplayedItems[index]; index = (index + 1) % DisplayedItems.Count; // Menu items only if (!(currentItem is ToolStripMenuItem) || string.IsNullOrEmpty(currentItem.Text) || !currentItem.Enabled) { continue; } // Only items which display text should be processed if ((currentItem.DisplayStyle & ToolStripItemDisplayStyle.Text) != ToolStripItemDisplayStyle.Text) { continue; } if (ToolStrip.IsPseudoMnemonic(charCode, currentItem.Text)) { if (firstMatch == null) { firstMatch = currentItem; } else { // we've found a second match - we should only change selection. if (firstMatch == startingItem) { // change the selection to be the second match as the first is already selected ProcessDuplicateMnemonic(currentItem, charCode); } else { ProcessDuplicateMnemonic(firstMatch, charCode); } // we've found two mnemonics, just return. return true; } } } if (firstMatch != null) { return firstMatch.ProcessMnemonic(charCode); } // do not call base, as we dont want to walk through the controls collection and reprocess everything // we should have processed in the displayed items collection. return false; } private bool ProcessTabKey(bool forward) { if (TabStop) { // ToolBar in tab-order parity // this means we want the toolstrip in the normal tab order - which means it shouldnt wrap. // First tab gets you into the toolstrip, second tab moves you on your way outside the container. // arrow keys would continue to wrap. return false; } else { // TabStop = false // this means we dont want the toolstrip in the normal tab order (default). // We got focus to the toolstrip by putting focus into a control contained on the toolstrip or // via a mnemonic e.g. Bold. In this case we want to wrap. // arrow keys would continue to wrap if (RightToLeft == RightToLeft.Yes) { forward = !forward; } SelectNextToolStripItem(GetSelectedItem(), forward); return true; } } /// <summary> /// This is more useful than overriding ProcessDialogKey because usually the difference /// between ToolStrip/ToolStripDropDown is arrow key handling. ProcessDialogKey first gives /// the selected ToolStripItem the chance to process the message... so really a proper /// inheritor would call down to the base first. Unfortunately doing this would cause the /// arrow keys would be eaten in the base class. /// Instead we're providing a separate place to override all arrow key handling. /// </summary> internal virtual bool ProcessArrowKey(Keys keyCode) { bool retVal = false; Debug.WriteLineIf(MenuAutoExpandDebug.TraceVerbose, "[ToolStrip.ProcessArrowKey] MenuTimer.Cancel called"); ToolStripMenuItem.MenuTimer.Cancel(); switch (keyCode) { case Keys.Left: case Keys.Right: retVal = ProcessLeftRightArrowKey(keyCode == Keys.Right); break; case Keys.Up: case Keys.Down: if (IsDropDown || Orientation != Orientation.Horizontal) { ToolStripItem currentSel = GetSelectedItem(); if (keyCode == Keys.Down) { ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Down); if (nextItem != null) { ChangeSelection(nextItem); retVal = true; } } else { ToolStripItem nextItem = GetNextItem(currentSel, ArrowDirection.Up); if (nextItem != null) { ChangeSelection(nextItem); retVal = true; } } } break; } return retVal; } /// <summary> /// Process an arrowKey press by selecting the next control in the group /// that the activeControl belongs to. /// </summary> private bool ProcessLeftRightArrowKey(bool right) { ToolStripItem selectedItem = GetSelectedItem(); ToolStripItem nextItem = SelectNextToolStripItem(GetSelectedItem(), right); return true; } internal void NotifySelectionChange(ToolStripItem item) { if (item == null) { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG NotifySelectionChange] none should be selected"); ClearAllSelections(); } else if (item.Selected) { Debug.WriteLineIf(SelectionDebug.TraceVerbose, "[SelectDBG NotifySelectionChange] Notify selection change: " + item.ToString() + ": " + item.Selected.ToString()); ClearAllSelectionsExcept(item); } } private void OnDefaultRendererChanged(object sender, EventArgs e) { // callback from static event if (GetToolStripState(STATE_USEDEFAULTRENDERER)) { OnRendererChanged(e); } } protected virtual void OnBeginDrag(EventArgs e) { SetToolStripState(STATE_DRAGGING, true); ClearAllSelections(); UpdateToolTip(null); // supress the tooltip. ((EventHandler)Events[EventBeginDrag])?.Invoke(this, e); } protected virtual void OnEndDrag(EventArgs e) { SetToolStripState(STATE_DRAGGING, false); ((EventHandler)Events[EventEndDrag])?.Invoke(this, e); } protected override void OnDockChanged(EventArgs e) { base.OnDockChanged(e); } protected virtual void OnRendererChanged(EventArgs e) { InitializeRenderer(Renderer); ((EventHandler)Events[EventRendererChanged])?.Invoke(this, e); } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); // notify items that the parent has changed for (int i = 0; i < Items.Count; i++) { if (Items[i] != null && Items[i].ParentInternal == this) { Items[i].OnParentEnabledChanged(e); } } } internal void OnDefaultFontChanged() { defaultFont = null; if (DpiHelper.IsPerMonitorV2Awareness) { ToolStripManager.CurrentDpi = DeviceDpi; defaultFont = ToolStripManager.DefaultFont; } if (!IsFontSet()) { OnFontChanged(EventArgs.Empty); } } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); for (int i = 0; i < Items.Count; i++) { Items[i].OnOwnerFontChanged(e); } } #if DEBUG #pragma warning disable RS0016 // Add public types and members to the declared API protected override void OnInvalidated(InvalidateEventArgs e) { base.OnInvalidated(e); // Debug code which is helpful for FlickerFest debugging. if (FlickerDebug.TraceVerbose) { string name = this.Name; if (string.IsNullOrEmpty(name)) { if (IsDropDown) { ToolStripItem item = ((ToolStripDropDown)this).OwnerItem; if (item != null && item.Name != null) { name = item.Name = ".DropDown"; } } if (string.IsNullOrEmpty(name)) { name = GetType().Name; } } // for debugging VS we want to filter out the propgrid toolstrip Debug.WriteLineIf(!(ParentInternal is PropertyGrid), "Invalidate called on: " + name + new StackTrace().ToString()); } } #pragma warning restore RS0016 // Add public types and members to the declared API #endif protected override void OnHandleCreated(EventArgs e) { if ((AllowDrop || AllowItemReorder) && (DropTargetManager != null)) { DropTargetManager.EnsureRegistered(this); } // calling control's (in base) version AFTER we register our DropTarget, so it will // listen to us instead of control's implementation base.OnHandleCreated(e); } protected override void OnHandleDestroyed(EventArgs e) { if (DropTargetManager != null) { // Make sure we unregister ourselves as a drop target DropTargetManager.EnsureUnRegistered(this); } base.OnHandleDestroyed(e); } protected internal virtual void OnItemAdded(ToolStripItemEventArgs e) { DoLayoutIfHandleCreated(e); if (!HasVisibleItems && e.Item != null && ((IArrangedElement)e.Item).ParticipatesInLayout) { // in certain cases, we may not have laid out yet (e.g. a dropdown may not layout until // it becomes visible.) We will recalculate this in SetDisplayedItems, but for the moment // if we find an item that ParticipatesInLayout, mark us as having visible items. HasVisibleItems = true; } ((ToolStripItemEventHandler)Events[EventItemAdded])?.Invoke(this, e); } /// <summary> /// Called when an item has been clicked on the ToolStrip. /// </summary> protected virtual void OnItemClicked(ToolStripItemClickedEventArgs e) { ((ToolStripItemClickedEventHandler)Events[EventItemClicked])?.Invoke(this, e); } protected internal virtual void OnItemRemoved(ToolStripItemEventArgs e) { // clear cached item states. OnItemVisibleChanged(e, /*performlayout*/true); ((ToolStripItemEventHandler)Events[EventItemRemoved])?.Invoke(this, e); } internal void OnItemVisibleChanged(ToolStripItemEventArgs e, bool performLayout) { // clear cached item states. if (e.Item == lastMouseActiveItem) { lastMouseActiveItem = null; } if (e.Item == LastMouseDownedItem) { lastMouseDownedItem = null; } if (e.Item == currentlyActiveTooltipItem) { UpdateToolTip(null); } if (performLayout) { DoLayoutIfHandleCreated(e); } } protected override void OnLayout(LayoutEventArgs e) { LayoutRequired = false; // we need to do this to prevent autosizing to happen while we're reparenting. ToolStripOverflow overflow = GetOverflow(); if (overflow != null) { overflow.SuspendLayout(); toolStripOverflowButton.Size = toolStripOverflowButton.GetPreferredSize(DisplayRectangle.Size - Padding.Size); } for (int j = 0; j < Items.Count; j++) { Items[j].OnLayout(e); } base.OnLayout(e); SetDisplayedItems(); OnLayoutCompleted(EventArgs.Empty); Invalidate(); if (overflow != null) { overflow.ResumeLayout(); } } protected virtual void OnLayoutCompleted(EventArgs e) { ((EventHandler)Events[EventLayoutCompleted])?.Invoke(this, e); } protected virtual void OnLayoutStyleChanged(EventArgs e) { ((EventHandler)Events[EventLayoutStyleChanged])?.Invoke(this, e); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); ClearAllSelections(); } protected override void OnLeave(EventArgs e) { base.OnLeave(e); if (!IsDropDown) { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "uninstalling RestoreFocusFilter"); // PERF, Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); } } internal virtual void OnLocationChanging(ToolStripLocationCancelEventArgs e) { ((ToolStripLocationCancelEventHandler)Events[EventLocationChanging])?.Invoke(this, e); } /// <summary> /// Delegate mouse down to the ToolStrip and its affected items /// </summary> protected override void OnMouseDown(MouseEventArgs mea) { // NEVER use this directly from another class. Always use GetMouseID so that // 0 is not returned to another class. mouseDownID++; ToolStripItem item = GetItemAt(mea.X, mea.Y); if (item != null) { if (!IsDropDown && (!(item is ToolStripDropDownItem))) { // set capture only when we know we're not on a dropdown (already effectively have capture due to modal menufilter) // and the item in question requires the mouse to be in the same item to be clicked. SetToolStripState(STATE_LASTMOUSEDOWNEDITEMCAPTURE, true); Capture = true; } MenuAutoExpand = true; if (mea != null) { // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); } lastMouseDownedItem = item; item.FireEvent(mea, ToolStripItemEventType.MouseDown); } else { base.OnMouseDown(mea); } } /// <summary> /// Delegate mouse moves to the ToolStrip and its affected items /// </summary> protected override void OnMouseMove(MouseEventArgs mea) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "OnMouseMove called"); ToolStripItem item = GetItemAt(mea.X, mea.Y); if (!Grip.MovingToolStrip) { // If we had a particular item that was "entered" // notify it that we have entered. It's fair to put // this in the MouseMove event, as MouseEnter is fired during // control's WM_MOUSEMOVE. Waiting until this event gives us // the actual coordinates. Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Item to get mouse move: {0}", (item == null) ? "null" : item.ToString())); if (item != lastMouseActiveItem) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "This is a new item - last item to get was {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); // notify the item that we've moved on HandleMouseLeave(); // track only items that dont get mouse events themselves. lastMouseActiveItem = (item is ToolStripControlHost) ? null : item; if (lastMouseActiveItem != null) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseEnter on: {0}", (lastMouseActiveItem == null) ? "null" : lastMouseActiveItem.ToString())); item.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseEnter); } // if (!DesignMode) { MouseHoverTimer.Start(lastMouseActiveItem); } } } else { item = Grip; } if (item != null) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (item == null) ? "null" : item.ToString())); // Fire mouse move on the item // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); item.FireEvent(mea, ToolStripItemEventType.MouseMove); } else { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, string.Format(CultureInfo.CurrentCulture, "Firing MouseMove on: {0}", (this == null) ? "null" : ToString())); base.OnMouseMove(mea); } } /// <summary> /// Delegate mouse leave to the ToolStrip and its affected items /// </summary> protected override void OnMouseLeave(EventArgs e) { HandleMouseLeave(); base.OnMouseLeave(e); } protected override void OnMouseCaptureChanged(EventArgs e) { if (!GetToolStripState(STATE_SUSPENDCAPTURE)) { // while we're showing a feedback rect, dont cancel moving the toolstrip. Grip.MovingToolStrip = false; } ClearLastMouseDownedItem(); base.OnMouseCaptureChanged(e); } /// <summary> /// Delegate mouse up to the ToolStrip and its affected items /// </summary> protected override void OnMouseUp(MouseEventArgs mea) { ToolStripItem item = (Grip.MovingToolStrip) ? Grip : GetItemAt(mea.X, mea.Y); if (item != null) { if (mea != null) { // Transpose this to "client coordinates" of the ToolStripItem. Point itemRelativePoint = item.TranslatePoint(new Point(mea.X, mea.Y), ToolStripPointType.ToolStripCoords, ToolStripPointType.ToolStripItemCoords); mea = new MouseEventArgs(mea.Button, mea.Clicks, itemRelativePoint.X, itemRelativePoint.Y, mea.Delta); } item.FireEvent(mea, ToolStripItemEventType.MouseUp); } else { base.OnMouseUp(mea); } ClearLastMouseDownedItem(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics toolstripGraphics = e.Graphics; Size bitmapSize = largestDisplayedItemSize; bool excludedTransparentRegion = false; Rectangle viewableArea = DisplayRectangle; Region transparentRegion = Renderer.GetTransparentRegion(this); try { // Paint the items // The idea here is to let items pretend they are controls. // they should get paint events at 0,0 and have proper clipping regions // set up for them. We cannot use g.TranslateTransform as that does // not translate the GDI world, and things like Visual Styles and the // TextRenderer only know how to speak GDI. // // The previous appropach was to set up the GDI clipping region and allocate a graphics // from that, but that meant we were allocating graphics objects left and right, which // turned out to be slow. // // So now we allocate an offscreen bitmap of size == MaxItemSize, copy the background // of the toolstrip into that bitmap, then paint the item on top of the bitmap, then copy // the contents of the bitmap back onto the toolstrip. This gives us our paint event starting // at 0,0. Combine this with double buffering of the toolstrip and the entire toolstrip is updated // after returning from this function. if (!LayoutUtils.IsZeroWidthOrHeight(bitmapSize)) { // cant create a 0x0 bmp. // Supporting RoundedEdges... // we've got a concept of a region that we shouldnt paint (the TransparentRegion as specified in the Renderer). // in order to support this we're going to intersect that region with the clipping region. // this new region will be excluded during the guts of OnPaint, and restored at the end of OnPaint. if (transparentRegion != null) { // only use the intersection so we can easily add back in the bits we took out at the end. transparentRegion.Intersect(toolstripGraphics.Clip); toolstripGraphics.ExcludeClip(transparentRegion); excludedTransparentRegion = true; } // Preparing for painting the individual items... // using WindowsGraphics here because we want to preserve the clipping information. // calling GetHdc by itself does not set up the clipping info. using (WindowsGraphics toolStripWindowsGraphics = WindowsGraphics.FromGraphics(toolstripGraphics, ApplyGraphicsProperties.Clipping)) { // get the cached item HDC. HandleRef toolStripHDC = new HandleRef(this, toolStripWindowsGraphics.GetHdc()); IntPtr itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); Graphics itemGraphics = Graphics.FromHdcInternal(itemHDC); try { // Painting the individual items... // iterate through all the items, painting them // one by one into the compatible offscreen DC, and then copying // them back onto the main toolstrip. for (int i = 0; i < DisplayedItems.Count; i++) { ToolStripItem item = DisplayedItems[i]; if (item != null) { // Rectangle clippingRect = e.ClipRectangle; Rectangle bounds = item.Bounds; if (!IsDropDown && item.Owner == this) { // owned items should not paint outside the client // area. (this is mainly to prevent obscuring the grip // and overflowbutton - ToolStripDropDownMenu places items // outside of the display rectangle - so we need to allow for this // in dropdoowns). clippingRect.Intersect(viewableArea); } // get the intersection of these two. clippingRect.Intersect(bounds); if (LayoutUtils.IsZeroWidthOrHeight(clippingRect)) { continue; // no point newing up a graphics object if there's nothing to paint. } Size itemSize = item.Size; // check if our item buffer is large enough to handle. if (!LayoutUtils.AreWidthAndHeightLarger(bitmapSize, itemSize)) { // the cached HDC isnt big enough for this item. make it bigger. largestDisplayedItemSize = itemSize; bitmapSize = itemSize; // dispose the old graphics - create a new, bigger one. itemGraphics.Dispose(); // calling this should take the existing DC and select in a bigger bitmap. itemHDC = ItemHdcInfo.GetCachedItemDC(toolStripHDC, bitmapSize); // allocate a new graphics. itemGraphics = Graphics.FromHdcInternal(itemHDC); } // since the item graphics object will have 0,0 at the // corner we need to actually shift the origin of the rect over // so it will be 0,0 too. clippingRect.Offset(-bounds.X, -bounds.Y); // PERF - consider - we only actually need to copy the clipping rect. // copy the background from the toolstrip onto the offscreen bitmap Gdi32.BitBlt( new HandleRef(ItemHdcInfo, itemHDC), 0, 0, item.Size.Width, item.Size.Height, toolStripHDC, item.Bounds.X, item.Bounds.Y, Gdi32.ROP.SRCCOPY); // paint the item into the offscreen bitmap using (PaintEventArgs itemPaintEventArgs = new PaintEventArgs(itemGraphics, clippingRect)) { item.FireEvent(itemPaintEventArgs, ToolStripItemEventType.Paint); } // copy the item back onto the toolstrip Gdi32.BitBlt( toolStripHDC, item.Bounds.X, item.Bounds.Y, item.Size.Width, item.Size.Height, new HandleRef(ItemHdcInfo, itemHDC), 0, 0, Gdi32.ROP.SRCCOPY); GC.KeepAlive(ItemHdcInfo); } } } finally { if (itemGraphics != null) { itemGraphics.Dispose(); } } } } // Painting the edge effects... // These would include things like (shadow line on the bottom, some overflow effects) Renderer.DrawToolStripBorder(new ToolStripRenderEventArgs(toolstripGraphics, this)); // Restoring the clip region to its original state... // the transparent region should be added back in as the insertion mark should paint over it. if (excludedTransparentRegion) { toolstripGraphics.SetClip(transparentRegion, CombineMode.Union); } // Paint the item re-order insertion mark... // This should ignore the transparent region and paint // over the entire area. PaintInsertionMark(toolstripGraphics); } finally { if (transparentRegion != null) { transparentRegion.Dispose(); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); // normally controls just need to do handle recreation, but ToolStrip does it based on layout of items. using (new LayoutTransaction(this, this, PropertyNames.RightToLeft)) { for (int i = 0; i < Items.Count; i++) { Items[i].OnParentRightToLeftChanged(e); } if (toolStripOverflowButton != null) { toolStripOverflowButton.OnParentRightToLeftChanged(e); } if (toolStripGrip != null) { toolStripGrip.OnParentRightToLeftChanged(e); } } } /// <summary> /// Inheriting classes should override this method to handle the erase /// background request from windows. It is not necessary to call /// base.onPaintBackground, however if you do not want the default /// Windows behavior you must set event.handled to true. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); Graphics g = e.Graphics; GraphicsState graphicsState = g.Save(); try { using (Region transparentRegion = Renderer.GetTransparentRegion(this)) { if (transparentRegion != null) { EraseCorners(e, transparentRegion); g.ExcludeClip(transparentRegion); } } Renderer.DrawToolStripBackground(new ToolStripRenderEventArgs(g, this)); } finally { if (graphicsState != null) { g.Restore(graphicsState); } } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); if (!Disposing && !IsDisposed) { HookStaticEvents(Visible); } } private void EraseCorners(PaintEventArgs e, Region transparentRegion) { if (transparentRegion != null) { PaintTransparentBackground(e, ClientRectangle, transparentRegion); } } internal protected virtual void OnPaintGrip(PaintEventArgs e) { Renderer.DrawGrip(new ToolStripGripRenderEventArgs(e.Graphics, this)); ((PaintEventHandler)Events[EventPaintGrip])?.Invoke(this, e); } protected override void OnScroll(ScrollEventArgs se) { if (se.Type != ScrollEventType.ThumbTrack && se.NewValue != se.OldValue) { ScrollInternal(se.OldValue - se.NewValue); } base.OnScroll(se); } private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { switch (e.Category) { case UserPreferenceCategory.Window: OnDefaultFontChanged(); break; case UserPreferenceCategory.General: InvalidateTextItems(); break; } } protected override void OnTabStopChanged(EventArgs e) { // SelectNextControl can select non-tabstop things. // we need to prevent this by changing the value of "CanSelect" SetStyle(ControlStyles.Selectable, TabStop); base.OnTabStopChanged(e); } /// <summary> /// When overridden in a derived class, handles rescaling of any magic numbers used in control painting. /// Must call the base class method to get the current DPI values. This method is invoked only when /// Application opts-in into the Per-monitor V2 support, targets .NETFX 4.7 and has /// EnableDpiChangedMessageHandling and EnableDpiChangedHighDpiImprovements config switches turned on. /// </summary> /// <param name="deviceDpiOld">Old DPI value</param> /// <param name="deviceDpiNew">New DPI value</param> protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) { base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); if (DpiHelper.IsPerMonitorV2Awareness) { if (deviceDpiOld != deviceDpiNew) { ToolStripManager.CurrentDpi = deviceDpiNew; defaultFont = ToolStripManager.DefaultFont; // We need to take care of this control. ResetScaling(deviceDpiNew); // We need to scale the one Grip per ToolStrip as well (if present). if (toolStripGrip != null) { toolStripGrip.ToolStrip_RescaleConstants(deviceDpiOld, deviceDpiNew); } // We need to delegate this "event" to the Controls/Components, which are // not directly affected by this, but need to consume. rescaleConstsCallbackDelegate?.Invoke(deviceDpiOld, deviceDpiNew); } } } /// <summary> /// Resets the scaling (only in PerMonitorV2 scenarios). /// </summary> /// <param name="newDpi">The new DPI passed by WmDpiChangedBeforeParent.</param> internal virtual void ResetScaling(int newDpi) { iconWidth = DpiHelper.LogicalToDeviceUnits(ICON_DIMENSION, newDpi); iconHeight = DpiHelper.LogicalToDeviceUnits(ICON_DIMENSION, newDpi); insertionBeamWidth = DpiHelper.LogicalToDeviceUnits(INSERTION_BEAM_WIDTH, newDpi); scaledDefaultPadding = DpiHelper.LogicalToDeviceUnits(defaultPadding, newDpi); scaledDefaultGripMargin = DpiHelper.LogicalToDeviceUnits(defaultGripMargin, newDpi); imageScalingSize = new Size(iconWidth, iconHeight); } /// <summary> /// Paints the I beam when items are being reordered /// </summary> internal void PaintInsertionMark(Graphics g) { if (lastInsertionMarkRect != Rectangle.Empty) { int widthOfBeam = insertionBeamWidth; if (Orientation == Orientation.Horizontal) { int start = lastInsertionMarkRect.X; int verticalBeamStart = start + 2; // draw two vertical lines g.DrawLines(SystemPens.ControlText, new Point[] { new Point(verticalBeamStart, lastInsertionMarkRect.Y), new Point(verticalBeamStart, lastInsertionMarkRect.Bottom-1), // first vertical line new Point(verticalBeamStart+1, lastInsertionMarkRect.Y), new Point(verticalBeamStart+1, lastInsertionMarkRect.Bottom-1), //second vertical line }); // then two top horizontal g.DrawLines(SystemPens.ControlText, new Point[] { new Point(start, lastInsertionMarkRect.Bottom-1), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Bottom-1), //bottom line new Point(start+1, lastInsertionMarkRect.Bottom -2), new Point(start + widthOfBeam-2, lastInsertionMarkRect.Bottom-2),//bottom second line }); // then two bottom horizontal g.DrawLines(SystemPens.ControlText, new Point[] { new Point(start, lastInsertionMarkRect.Y), new Point(start + widthOfBeam-1, lastInsertionMarkRect.Y), //top line new Point(start+1, lastInsertionMarkRect.Y+1), new Point(start + widthOfBeam-2, lastInsertionMarkRect.Y+1)//top second line }); } else { widthOfBeam = insertionBeamWidth; int start = lastInsertionMarkRect.Y; int horizontalBeamStart = start + 2; // draw two horizontal lines g.DrawLines(SystemPens.ControlText, new Point[] { new Point(lastInsertionMarkRect.X, horizontalBeamStart), new Point(lastInsertionMarkRect.Right-1, horizontalBeamStart), // first vertical line new Point(lastInsertionMarkRect.X, horizontalBeamStart+1), new Point(lastInsertionMarkRect.Right-1, horizontalBeamStart+1), //second vertical line }); // then two left vertical g.DrawLines(SystemPens.ControlText, new Point[] { new Point(lastInsertionMarkRect.X, start), new Point(lastInsertionMarkRect.X, start + widthOfBeam-1), //left line new Point(lastInsertionMarkRect.X+1, start+1), new Point(lastInsertionMarkRect.X+1, start + widthOfBeam-2), //second left line }); // then two right vertical g.DrawLines(SystemPens.ControlText, new Point[] { new Point(lastInsertionMarkRect.Right-1, start), new Point(lastInsertionMarkRect.Right-1, start + widthOfBeam-1), //right line new Point(lastInsertionMarkRect.Right-2, start+1), new Point(lastInsertionMarkRect.Right-2, start + widthOfBeam-2), //second right line }); } } } /// <summary> /// Paints the I beam when items are being reordered /// </summary> internal void PaintInsertionMark(Rectangle insertionRect) { if (lastInsertionMarkRect != insertionRect) { ClearInsertionMark(); lastInsertionMarkRect = insertionRect; Invalidate(insertionRect); } } [EditorBrowsable(EditorBrowsableState.Never)] public new Control GetChildAtPoint(Point point) { return base.GetChildAtPoint(point); } [EditorBrowsable(EditorBrowsableState.Never)] public new Control GetChildAtPoint(Point pt, GetChildAtPointSkip skipValue) { return base.GetChildAtPoint(pt, skipValue); } // GetNextControl for ToolStrip should always return null // we do our own tabbing/etc - this allows us to pretend // we dont have child controls. internal override Control GetFirstChildControlInTabOrder(bool forward) { return null; } /// <summary> /// Finds the ToolStripItem contained within a specified client coordinate point /// If item not found - returns null /// </summary> public ToolStripItem GetItemAt(int x, int y) { return GetItemAt(new Point(x, y)); } /// <summary> /// Finds the ToolStripItem contained within a specified client coordinate point /// If item not found - returns null /// </summary> public ToolStripItem GetItemAt(Point point) { Rectangle comparisonRect = new Rectangle(point, onePixel); Rectangle bounds; // Check the last item we had the mouse over if (lastMouseActiveItem != null) { bounds = lastMouseActiveItem.Bounds; if (bounds.IntersectsWith(comparisonRect) && lastMouseActiveItem.ParentInternal == this) { return lastMouseActiveItem; } } // Walk the ToolStripItem collection for (int i = 0; i < DisplayedItems.Count; i++) { if (DisplayedItems[i] == null || DisplayedItems[i].ParentInternal != this) { continue; } bounds = DisplayedItems[i].Bounds; // inflate the grip so it is easier to access if (toolStripGrip != null && DisplayedItems[i] == toolStripGrip) { bounds = LayoutUtils.InflateRect(bounds, GripMargin); } if (bounds.IntersectsWith(comparisonRect)) { return DisplayedItems[i]; } } return null; } private void RestoreFocusInternal(bool wasInMenuMode) { // This is called from the RestoreFocusFilter. If the state of MenuMode has changed // since we posted this message, we do not know enough information about whether // we should exit menu mode. if (wasInMenuMode == ToolStripManager.ModalMenuFilter.InMenuMode) { RestoreFocusInternal(); } } /// <summary> RestoreFocus - returns focus to the control who activated us /// See comment on SnapFocus /// </summary> internal void RestoreFocusInternal() { ToolStripManager.ModalMenuFilter.MenuKeyToggle = false; ClearAllSelections(); lastMouseDownedItem = null; Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] Someone has called RestoreFocus, exiting MenuMode."); ToolStripManager.ModalMenuFilter.ExitMenuMode(); if (!IsDropDown) { // reset menu auto expansion. Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] Setting menu auto expand to false"); Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocus] uninstalling RestoreFocusFilter"); // PERF, Application.ThreadContext.FromCurrent().RemoveMessageFilter(RestoreFocusFilter); MenuAutoExpand = false; if (!DesignMode && !TabStop && (Focused || ContainsFocus)) { RestoreFocus(); } } // this matches the case where you click on a toolstrip control host // then tab off of it, then hit ESC. ESC would "restore focus" and // we should cancel keyboard activation if this method has cancelled focus. if (KeyboardActive && !Focused && !ContainsFocus) { KeyboardActive = false; } } // override if you want to control (when TabStop = false) where the focus returns to [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void RestoreFocus() { bool focusSuccess = false; if ((hwndThatLostFocus != IntPtr.Zero) && (hwndThatLostFocus != Handle)) { Control c = Control.FromHandle(hwndThatLostFocus); Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip RestoreFocus]: Will Restore Focus to: " + WindowsFormsUtils.GetControlInformation(hwndThatLostFocus)); hwndThatLostFocus = IntPtr.Zero; if ((c != null) && c.Visible) { focusSuccess = c.Focus(); } } hwndThatLostFocus = IntPtr.Zero; if (!focusSuccess) { // clear out the focus, we have focus, we're not supposed to anymore. User32.SetFocus(IntPtr.Zero); } } internal virtual void ResetRenderMode() { RenderMode = ToolStripRenderMode.ManagerRenderMode; } [EditorBrowsable(EditorBrowsableState.Never)] public void ResetMinimumSize() { CommonProperties.SetMinimumSize(this, new Size(-1, -1)); } private void ResetGripMargin() { GripMargin = Grip.DefaultMargin; } internal void ResumeCaputureMode() { SetToolStripState(STATE_SUSPENDCAPTURE, false); } internal void SuspendCaputureMode() { SetToolStripState(STATE_SUSPENDCAPTURE, true); } internal virtual void ScrollInternal(int delta) { SuspendLayout(); foreach (ToolStripItem item in Items) { Point newLocation = item.Bounds.Location; newLocation.Y -= delta; SetItemLocation(item, newLocation); } ResumeLayout(false); Invalidate(); } protected internal void SetItemLocation(ToolStripItem item, Point location) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (item.Owner != this) { throw new NotSupportedException(SR.ToolStripCanOnlyPositionItsOwnItems); } item.SetBounds(new Rectangle(location, item.Size)); } /// <summary> /// This is needed so that people doing custom layout engines can change the "Parent" property of the item. /// </summary> protected static void SetItemParent(ToolStripItem item, ToolStrip parent) { item.Parent = parent; } protected override void SetVisibleCore(bool visible) { if (visible) { SnapMouseLocation(); } else { // make sure we reset selection - this is critical for close/reopen dropdowns. if (!Disposing && !IsDisposed) { ClearAllSelections(); } // when we're not visible, clear off old item HDC. CachedItemHdcInfo lastInfo = cachedItemHdcInfo; cachedItemHdcInfo = null; lastMouseDownedItem = null; if (lastInfo != null) { lastInfo.Dispose(); } } base.SetVisibleCore(visible); } internal bool ShouldSelectItem() { // we only want to select the item if the cursor position has // actually moved from when the window became visible. // We ALWAYS get a WM_MOUSEMOVE when the window is shown, // which could accidentally change selection. if (mouseEnterWhenShown == InvalidMouseEnter) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "[TS: ShouldSelectItem] MouseEnter already reset."); return true; } Point mousePosition = WindowsFormsUtils.LastCursorPoint; if (mouseEnterWhenShown != mousePosition) { Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "[TS: ShouldSelectItem] Mouse position has changed - call Select()."); mouseEnterWhenShown = InvalidMouseEnter; return true; } Debug.WriteLineIf(ToolStripItem.s_mouseDebugging.TraceVerbose, "[TS: ShouldSelectItem] Mouse hasnt actually moved yet."); return false; } protected override void Select(bool directed, bool forward) { bool correctParentActiveControl = true; if (ParentInternal != null) { IContainerControl c = ParentInternal.GetContainerControl(); if (c != null) { c.ActiveControl = this; correctParentActiveControl = (c.ActiveControl == this); } } if (directed && correctParentActiveControl) { SelectNextToolStripItem(null, forward); } } internal ToolStripItem SelectNextToolStripItem(ToolStripItem start, bool forward) { ToolStripItem nextItem = GetNextItem(start, (forward) ? ArrowDirection.Right : ArrowDirection.Left, /*RTLAware=*/true); ChangeSelection(nextItem); return nextItem; } internal void SetFocusUnsafe() { if (TabStop) { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.SetFocus] Focusing toolstrip."); Focus(); } else { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.SetFocus] Entering menu mode."); ToolStripManager.ModalMenuFilter.SetActiveToolStrip(this, /*menuKeyPressed=*/false); } } private void SetupGrip() { Rectangle gripRectangle = Rectangle.Empty; Rectangle displayRect = DisplayRectangle; if (Orientation == Orientation.Horizontal) { // the display rectangle already knows about the padding and the grip rectangle width // so place it relative to that. gripRectangle.X = Math.Max(0, displayRect.X - Grip.GripThickness); gripRectangle.Y = Math.Max(0, displayRect.Top - Grip.Margin.Top); gripRectangle.Width = Grip.GripThickness; gripRectangle.Height = displayRect.Height; if (RightToLeft == RightToLeft.Yes) { gripRectangle.X = ClientRectangle.Right - gripRectangle.Width - Grip.Margin.Horizontal; gripRectangle.X += Grip.Margin.Left; } else { gripRectangle.X -= Grip.Margin.Right; } } else { // vertical split stack mode gripRectangle.X = displayRect.Left; gripRectangle.Y = displayRect.Top - (Grip.GripThickness + Grip.Margin.Bottom); gripRectangle.Width = displayRect.Width; gripRectangle.Height = Grip.GripThickness; } if (Grip.Bounds != gripRectangle) { Grip.SetBounds(gripRectangle); } } /// <summary> /// Sets the size of the auto-scroll margins. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] new public void SetAutoScrollMargin(int x, int y) { base.SetAutoScrollMargin(x, y); } internal void SetLargestItemSize(Size size) { if (toolStripOverflowButton != null && toolStripOverflowButton.Visible) { size = LayoutUtils.UnionSizes(size, toolStripOverflowButton.Bounds.Size); } if (toolStripGrip != null && toolStripGrip.Visible) { size = LayoutUtils.UnionSizes(size, toolStripGrip.Bounds.Size); } largestDisplayedItemSize = size; } /// <summary> /// Afer we've performed a layout we need to reset the DisplayedItems and the OverflowItems collection. /// OverflowItems are not supported in layouts other than ToolStripSplitStack /// </summary> protected virtual void SetDisplayedItems() { DisplayedItems.Clear(); OverflowItems.Clear(); HasVisibleItems = false; Size biggestItemSize = Size.Empty; // used in determining OnPaint caching. if (LayoutEngine is ToolStripSplitStackLayout) { if (ToolStripGripStyle.Visible == GripStyle) { DisplayedItems.Add(Grip); SetupGrip(); } // For splitstack layout we re-arrange the items in the displayed items // collection so that we can easily tab through them in natural order Rectangle displayRect = DisplayRectangle; int lastRightAlignedItem = -1; for (int pass = 0; pass < 2; pass++) { int j = 0; if (pass == 1 /*add right aligned items*/) { j = lastRightAlignedItem; } // add items to the DisplayedItem collection. // in pass 0, we go forward adding the head (left) aligned items // in pass 1, we go backward starting from the last (right) aligned item we found for (; j >= 0 && j < Items.Count; j = (pass == 0) ? j + 1 : j - 1) { ToolStripItem item = Items[j]; ToolStripItemPlacement placement = item.Placement; if (((IArrangedElement)item).ParticipatesInLayout) { if (placement == ToolStripItemPlacement.Main) { bool addItem = false; if (pass == 0) { // Align.Left items addItem = (item.Alignment == ToolStripItemAlignment.Left); if (!addItem) { // stash away this index so we dont have to iterate through the whole list again. lastRightAlignedItem = j; } } else if (pass == 1) { // Align.Right items addItem = (item.Alignment == ToolStripItemAlignment.Right); } if (addItem) { HasVisibleItems = true; biggestItemSize = LayoutUtils.UnionSizes(biggestItemSize, item.Bounds.Size); DisplayedItems.Add(item); } } else if (placement == ToolStripItemPlacement.Overflow && !(item is ToolStripSeparator)) { OverflowItems.Add(item); } } else { item.SetPlacement(ToolStripItemPlacement.None); } } } ToolStripOverflow overflow = GetOverflow(); if (overflow != null) { overflow.LayoutRequired = true; } if (OverflowItems.Count == 0) { OverflowButton.Visible = false; } else if (CanOverflow) { DisplayedItems.Add(OverflowButton); } } else { // NOT a SplitStack layout. We dont change the order of the displayed items collection // for custom keyboard handling override GetNextItem. Debug.WriteLineIf(LayoutDebugSwitch.TraceVerbose, "Setting Displayed Items: Current bounds: " + Bounds.ToString()); Rectangle clientBounds = ClientRectangle; // for all other layout managers, we ignore overflow placement bool allContained = true; for (int j = 0; j < Items.Count; j++) { ToolStripItem item = Items[j]; if (((IArrangedElement)item).ParticipatesInLayout) { item.ParentInternal = this; bool boundsCheck = !IsDropDown; bool intersects = item.Bounds.IntersectsWith(clientBounds); bool verticallyContained = clientBounds.Contains(clientBounds.X, item.Bounds.Top) && clientBounds.Contains(clientBounds.X, item.Bounds.Bottom); if (!verticallyContained) { allContained = false; } if (!boundsCheck || intersects) { HasVisibleItems = true; biggestItemSize = LayoutUtils.UnionSizes(biggestItemSize, item.Bounds.Size); DisplayedItems.Add(item); item.SetPlacement(ToolStripItemPlacement.Main); } } else { item.SetPlacement(ToolStripItemPlacement.None); } Debug.WriteLineIf(LayoutDebugSwitch.TraceVerbose, item.ToString() + Items[j].Bounds); } // For performance we calculate this here, since we're already iterating over the items. // the only one who cares about it is ToolStripDropDownMenu (to see if it needs scroll buttons). AllItemsVisible = allContained; } SetLargestItemSize(biggestItemSize); } /// <summary> /// Sets the current value of the specified bit in the control's state. /// </summary> internal void SetToolStripState(int flag, bool value) { toolStripState = value ? toolStripState | flag : toolStripState & ~flag; } // remembers the current mouse location so we can determine // later if we need to shift selection. internal void SnapMouseLocation() { mouseEnterWhenShown = WindowsFormsUtils.LastCursorPoint; } /// <summary> SnapFocus /// When get focus to the toolstrip (and we're not participating in the tab order) /// it's probably cause someone hit the ALT key. We need to remember who that was /// so when we're done here we can RestoreFocus back to it. /// /// We're called from WM_SETFOCUS, and otherHwnd is the HWND losing focus. /// /// Required checks /// - make sure it's not a dropdown /// - make sure it's not a child control of this control. /// - make sure the control is on this window /// </summary> private void SnapFocus(IntPtr otherHwnd) { #if DEBUG if (SnapFocusDebug.TraceVerbose) { string stackTrace = new StackTrace().ToString(); Regex regex = new Regex("FocusInternal"); Debug.WriteLine(!regex.IsMatch(stackTrace), "who is setting focus to us?"); } #endif // we need to know who sent us focus so we know who to send it back to later. if (!TabStop && !IsDropDown) { bool snapFocus = false; if (Focused && (otherHwnd != Handle)) { // the case here is a label before a combo box calling FocusInternal in ProcessMnemonic. // we'll filter out children later. snapFocus = true; } else if (!ContainsFocus && !Focused) { snapFocus = true; } if (snapFocus) { // remember the current mouse position so that we can check later if it actually moved // otherwise we'd unexpectedly change selection to whatever the cursor was over at this moment. SnapMouseLocation(); // make sure the otherHandle is not a child of thisHandle if ((Handle != otherHwnd) && !User32.IsChild(new HandleRef(this, Handle), otherHwnd).IsTrue()) { // make sure the root window of the otherHwnd is the same as // the root window of thisHwnd. IntPtr thisHwndRoot = User32.GetAncestor(this, User32.GA.ROOT); IntPtr otherHwndRoot = User32.GetAncestor(otherHwnd, User32.GA.ROOT); if (thisHwndRoot == otherHwndRoot && (thisHwndRoot != IntPtr.Zero)) { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip SnapFocus]: Caching for return focus:" + WindowsFormsUtils.GetControlInformation(otherHwnd)); // we know we're in the same window heirarchy. hwndThatLostFocus = otherHwnd; } } } } } // when we're control tabbing around we need to remember the original // thing that lost focus. internal void SnapFocusChange(ToolStrip otherToolStrip) { otherToolStrip.hwndThatLostFocus = hwndThatLostFocus; } private bool ShouldSerializeDefaultDropDownDirection() { return (toolStripDropDownDirection != ToolStripDropDownDirection.Default); } internal virtual bool ShouldSerializeLayoutStyle() { return layoutStyle != ToolStripLayoutStyle.StackWithOverflow; } internal override bool ShouldSerializeMinimumSize() { Size invalidDefaultSize = new Size(-1, -1); return (CommonProperties.GetMinimumSize(this, invalidDefaultSize) != invalidDefaultSize); } private bool ShouldSerializeGripMargin() { return GripMargin != DefaultGripMargin; } internal virtual bool ShouldSerializeRenderMode() { // We should NEVER serialize custom. return (RenderMode != ToolStripRenderMode.ManagerRenderMode && RenderMode != ToolStripRenderMode.Custom); } public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(", Name: "); sb.Append(Name); sb.Append(", Items: ").Append(Items.Count); return sb.ToString(); } internal void UpdateToolTip(ToolStripItem item) { if (ShowItemToolTips) { if (item != currentlyActiveTooltipItem && ToolTip != null) { ToolTip.Hide(this); currentlyActiveTooltipItem = item; if (currentlyActiveTooltipItem != null && !GetToolStripState(STATE_DRAGGING)) { Cursor currentCursor = Cursor.Current; if (currentCursor != null) { Point cursorLocation = Cursor.Position; cursorLocation.Y += Cursor.Size.Height - currentCursor.HotSpot.Y; cursorLocation = WindowsFormsUtils.ConstrainToScreenBounds(new Rectangle(cursorLocation, onePixel)).Location; ToolTip.Show(currentlyActiveTooltipItem.ToolTipText, this, PointToClient(cursorLocation), ToolTip.AutoPopDelay); } } } } } private void UpdateLayoutStyle(DockStyle newDock) { if (!IsInToolStripPanel && layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) { using (new LayoutTransaction(this, this, PropertyNames.Orientation)) { // // We want the ToolStrip to size appropriately when the dock has switched. // if (newDock == DockStyle.Left || newDock == DockStyle.Right) { UpdateOrientation(Orientation.Vertical); } else { UpdateOrientation(Orientation.Horizontal); } } OnLayoutStyleChanged(EventArgs.Empty); if (ParentInternal != null) { LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Orientation); } } } private void UpdateLayoutStyle(Orientation newRaftingRowOrientation) { if (layoutStyle != ToolStripLayoutStyle.HorizontalStackWithOverflow && layoutStyle != ToolStripLayoutStyle.VerticalStackWithOverflow) { using (new LayoutTransaction(this, this, PropertyNames.Orientation)) { // We want the ToolStrip to size appropriately when the rafting container orientation has switched. UpdateOrientation(newRaftingRowOrientation); if (LayoutEngine is ToolStripSplitStackLayout && layoutStyle == ToolStripLayoutStyle.StackWithOverflow) { OnLayoutStyleChanged(EventArgs.Empty); } } } else { // update the orientation but dont force a layout. UpdateOrientation(newRaftingRowOrientation); } } private void UpdateOrientation(Orientation newOrientation) { if (newOrientation != orientation) { // snap our last dimensions before switching over. // use specifed bounds so that if something is docked or anchored we dont take the extra stretching // effects into account. Size size = CommonProperties.GetSpecifiedBounds(this).Size; orientation = newOrientation; // since the Grip affects the DisplayRectangle, we need to re-adjust the size SetupGrip(); } } protected override void WndProc(ref Message m) { if (m.Msg == (int)User32.WM.SETFOCUS) { SnapFocus(m.WParam); } if (m.Msg == (int)User32.WM.MOUSEACTIVATE) { // we want to prevent taking focus if someone clicks on the toolstrip dropdown // itself. the mouse message will still go through, but focus wont be taken. // if someone clicks on a child control (combobox, textbox, etc) focus will // be taken - but we'll handle that in WM_NCACTIVATE handler. Point pt = PointToClient(WindowsFormsUtils.LastCursorPoint); IntPtr hwndClicked = User32.ChildWindowFromPointEx(this, pt, User32.CWP.SKIPINVISIBLE | User32.CWP.SKIPDISABLED | User32.CWP.SKIPTRANSPARENT); // if we click on the toolstrip itself, eat the activation. // if we click on a child control, allow the toolstrip to activate. if (hwndClicked == Handle) { lastMouseDownedItem = null; m.Result = (IntPtr)User32.MA.NOACTIVATE; if (!IsDropDown && !IsInDesignMode) { // If our root HWND is not the active hwnd, // eat the mouse message and bring the form to the front. IntPtr rootHwnd = User32.GetAncestor(this, User32.GA.ROOT); if (rootHwnd != IntPtr.Zero) { // snap the active window and compare to our root window. IntPtr hwndActive = User32.GetActiveWindow(); if (hwndActive != rootHwnd) { // Activate the window, and discard the mouse message. // this appears to be the same behavior as office. m.Result = (IntPtr)User32.MA.ACTIVATEANDEAT; } } } return; } else { // we're setting focus to a child control - remember who gave it to us // so we can restore it on ESC. SnapFocus(User32.GetFocus()); if (!IsDropDown && !TabStop) { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "Installing restoreFocusFilter"); // PERF, Application.ThreadContext.FromCurrent().AddMessageFilter(RestoreFocusFilter); } } } base.WndProc(ref m); if (m.Msg == (int)User32.WM.NCDESTROY) { // Destroy the owner window, if we created one. We // cannot do this in OnHandleDestroyed, because at // that point our handle is not actually destroyed so // destroying our parent actually causes a recursive // WM_DESTROY. if (dropDownOwnerWindow != null) { dropDownOwnerWindow.DestroyHandle(); } } } // Overriden to return Items instead of Controls. ArrangedElementCollection IArrangedElement.Children { get { return Items; } } void IArrangedElement.SetBounds(Rectangle bounds, BoundsSpecified specified) { SetBoundsCore(bounds.X, bounds.Y, bounds.Width, bounds.Height, specified); } bool IArrangedElement.ParticipatesInLayout { get { return GetState(States.Visible); } } protected override AccessibleObject CreateAccessibilityInstance() { return new ToolStripAccessibleObject(this); } protected override ControlCollection CreateControlsInstance() { return new ReadOnlyControlCollection(this, /* isReadOnly = */ !DesignMode); } internal void OnItemAddedInternal(ToolStripItem item) { if (ShowItemToolTips) { KeyboardToolTipStateMachine.Instance.Hook(item, ToolTip); } } internal void OnItemRemovedInternal(ToolStripItem item) { KeyboardToolTipStateMachine.Instance.Unhook(item, ToolTip); } internal override bool AllowsChildrenToShowToolTips() { return base.AllowsChildrenToShowToolTips() && ShowItemToolTips; } [ComVisible(true)] public class ToolStripAccessibleObject : ControlAccessibleObject { private readonly ToolStrip owner; public ToolStripAccessibleObject(ToolStrip owner) : base(owner) { this.owner = owner; } internal override UiaCore.IRawElementProviderFragment ElementProviderFromPoint(double x, double y) { return HitTest((int)x, (int)y); } /// <summary> /// Return the child object at the given screen coordinates. /// </summary> public override AccessibleObject HitTest(int x, int y) { Point clientHit = owner.PointToClient(new Point(x, y)); ToolStripItem item = owner.GetItemAt(clientHit); return ((item != null) && (item.AccessibilityObject != null)) ? item.AccessibilityObject : base.HitTest(x, y); } /// <summary> /// When overridden in a derived class, gets the accessible child corresponding to the specified /// index. /// </summary> // public override AccessibleObject GetChild(int index) { if ((owner == null) || (owner.Items == null)) { return null; } if (index == 0 && owner.Grip.Visible) { return owner.Grip.AccessibilityObject; } else if (owner.Grip.Visible && index > 0) { index--; } if (index < owner.Items.Count) { ToolStripItem item = null; int myIndex = 0; // First we walk through the head aligned items. for (int i = 0; i < owner.Items.Count; ++i) { if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) { if (myIndex == index) { item = owner.Items[i]; break; } myIndex++; } } // If we didn't find it, then we walk through the tail aligned items. if (item == null) { for (int i = 0; i < owner.Items.Count; ++i) { if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) { if (myIndex == index) { item = owner.Items[i]; break; } myIndex++; } } } if (item == null) { Debug.Fail("No item matched the index??"); return null; } if (item.Placement == ToolStripItemPlacement.Overflow) { return new ToolStripAccessibleObjectWrapperForItemsOnOverflow(item); } return item.AccessibilityObject; } if (owner.CanOverflow && owner.OverflowButton.Visible && index == owner.Items.Count) { return owner.OverflowButton.AccessibilityObject; } return null; } /// <summary> /// When overridden in a derived class, gets the number of children /// belonging to an accessible object. /// </summary> public override int GetChildCount() { if ((owner == null) || (owner.Items == null)) { return -1; } int count = 0; for (int i = 0; i < owner.Items.Count; i++) { if (owner.Items[i].Available) { count++; } } if (owner.Grip.Visible) { count++; } if (owner.CanOverflow && owner.OverflowButton.Visible) { count++; } return count; } internal AccessibleObject GetChildFragment(int fragmentIndex, bool getOverflowItem = false) { ToolStripItemCollection items = getOverflowItem ? owner.OverflowItems : owner.DisplayedItems; int childFragmentCount = items.Count; if (!getOverflowItem && owner.CanOverflow && owner.OverflowButton.Visible && fragmentIndex == childFragmentCount - 1) { return owner.OverflowButton.AccessibilityObject; } for (int index = 0; index < childFragmentCount; index++) { ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Left && fragmentIndex == index) { if (item is ToolStripControlHost controlHostItem) { return controlHostItem.ControlAccessibilityObject; } return item.AccessibilityObject; } } for (int index = 0; index < childFragmentCount; index++) { ToolStripItem item = owner.Items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Right && fragmentIndex == index) { if (item is ToolStripControlHost controlHostItem) { return controlHostItem.ControlAccessibilityObject; } return item.AccessibilityObject; } } return null; } internal int GetChildOverflowFragmentCount() { if (owner == null || owner.OverflowItems == null) { return -1; } return owner.OverflowItems.Count; } internal int GetChildFragmentCount() { if (owner == null || owner.DisplayedItems == null) { return -1; } return owner.DisplayedItems.Count; } internal int GetChildFragmentIndex(ToolStripItem.ToolStripItemAccessibleObject child) { if (owner == null || owner.Items == null) { return -1; } if (child.Owner == owner.Grip) { return 0; } ToolStripItemCollection items; ToolStripItemPlacement placement = child.Owner.Placement; if (owner is ToolStripOverflow) { // Overflow items in ToolStripOverflow host are in DisplayedItems collection. items = owner.DisplayedItems; } else { if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) { return GetChildFragmentCount() - 1; } // Items can be either in DisplayedItems or in OverflowItems (if overflow) items = (placement == ToolStripItemPlacement.Main) ? owner.DisplayedItems : owner.OverflowItems; } // First we walk through the head aligned items. for (int index = 0; index < items.Count; index++) { ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Left && child.Owner == items[index]) { return index; } } // If we didn't find it, then we walk through the tail aligned items. for (int index = 0; index < items.Count; index++) { ToolStripItem item = items[index]; if (item.Available && item.Alignment == ToolStripItemAlignment.Right && child.Owner == items[index]) { return index; } } return -1; } internal int GetChildIndex(ToolStripItem.ToolStripItemAccessibleObject child) { if ((owner == null) || (owner.Items == null)) { return -1; } int index = 0; if (owner.Grip.Visible) { if (child.Owner == owner.Grip) { return 0; } index = 1; } if (owner.CanOverflow && owner.OverflowButton.Visible && child.Owner == owner.OverflowButton) { return owner.Items.Count + index; } // First we walk through the head aligned items. for (int i = 0; i < owner.Items.Count; ++i) { if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Left) { if (child.Owner == owner.Items[i]) { return index; } index++; } } // If we didn't find it, then we walk through the tail aligned items. for (int i = 0; i < owner.Items.Count; ++i) { if (owner.Items[i].Available && owner.Items[i].Alignment == ToolStripItemAlignment.Right) { if (child.Owner == owner.Items[i]) { return index; } index++; } } return -1; } public override AccessibleRole Role { get { AccessibleRole role = Owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } return AccessibleRole.ToolBar; } } internal override UiaCore.IRawElementProviderFragmentRoot FragmentRoot { get { return this; } } internal override UiaCore.IRawElementProviderFragment FragmentNavigate(UiaCore.NavigateDirection direction) { switch (direction) { case UiaCore.NavigateDirection.FirstChild: int childCount = GetChildFragmentCount(); if (childCount > 0) { return GetChildFragment(0); } break; case UiaCore.NavigateDirection.LastChild: childCount = GetChildFragmentCount(); if (childCount > 0) { return GetChildFragment(childCount - 1); } break; } return base.FragmentNavigate(direction); } internal override object GetPropertyValue(UiaCore.UIA propertyID) { if (propertyID == UiaCore.UIA.ControlTypePropertyId) { return UiaCore.UIA.ToolBarControlTypeId; } return base.GetPropertyValue(propertyID); } } private class ToolStripAccessibleObjectWrapperForItemsOnOverflow : ToolStripItem.ToolStripItemAccessibleObject { public ToolStripAccessibleObjectWrapperForItemsOnOverflow(ToolStripItem item) : base(item) { } public override AccessibleStates State { get { AccessibleStates state = base.State; state |= AccessibleStates.Offscreen; state |= AccessibleStates.Invisible; return state; } } } // When we click somewhere outside of the toolstrip it should be as if we hit esc. internal sealed class RestoreFocusMessageFilter : IMessageFilter { private readonly ToolStrip ownerToolStrip; public RestoreFocusMessageFilter(ToolStrip ownerToolStrip) { this.ownerToolStrip = ownerToolStrip; } public bool PreFilterMessage(ref Message m) { if (ownerToolStrip.Disposing || ownerToolStrip.IsDisposed || ownerToolStrip.IsDropDown) { return false; } // if the app has changed activation, restore focus switch ((User32.WM)m.Msg) { case User32.WM.LBUTTONDOWN: case User32.WM.RBUTTONDOWN: case User32.WM.MBUTTONDOWN: case User32.WM.NCLBUTTONDOWN: case User32.WM.NCRBUTTONDOWN: case User32.WM.NCMBUTTONDOWN: if (ownerToolStrip.ContainsFocus) { // if we've clicked on something that's not a child of the toolstrip and we // currently have focus, restore it. if (!User32.IsChild(new HandleRef(ownerToolStrip, ownerToolStrip.Handle), m.HWnd).IsTrue()) { IntPtr rootHwnd = User32.GetAncestor(ownerToolStrip, User32.GA.ROOT); if (rootHwnd == m.HWnd || User32.IsChild(rootHwnd, m.HWnd).IsTrue()) { // Only RestoreFocus if the hwnd is a child of the root window and isnt on the toolstrip. RestoreFocusInternal(); } } } return false; default: return false; } } private void RestoreFocusInternal() { Debug.WriteLineIf(SnapFocusDebug.TraceVerbose, "[ToolStrip.RestoreFocusFilter] Detected a click, restoring focus."); ownerToolStrip.BeginInvoke(new BooleanMethodInvoker(ownerToolStrip.RestoreFocusInternal), new object[] { ToolStripManager.ModalMenuFilter.InMenuMode }); // PERF, Application.ThreadContext.FromCurrent().RemoveMessageFilter(this); } } internal override bool ShowsOwnKeyboardToolTip() { bool hasVisibleSelectableItems = false; int i = Items.Count; while (i-- != 0 && !hasVisibleSelectableItems) { ToolStripItem item = Items[i]; if (item.CanKeyboardSelect && item.Visible) { hasVisibleSelectableItems = true; } } return !hasVisibleSelectableItems; } } internal class CachedItemHdcInfo : IDisposable { internal CachedItemHdcInfo() { } private IntPtr _cachedItemHDC = IntPtr.Zero; private Size _cachedHDCSize = Size.Empty; private IntPtr _cachedItemBitmap = IntPtr.Zero; // this DC is cached and should only be deleted on Dispose or when the size changes. public IntPtr GetCachedItemDC(HandleRef toolStripHDC, Size bitmapSize) { if (_cachedHDCSize.Width < bitmapSize.Width || _cachedHDCSize.Height < bitmapSize.Height) { if (_cachedItemHDC == IntPtr.Zero) { // create a new DC - we dont have one yet. IntPtr compatibleHDC = Gdi32.CreateCompatibleDC(toolStripHDC.Handle); _cachedItemHDC = compatibleHDC; } // create compatible bitmap with the correct size. _cachedItemBitmap = Gdi32.CreateCompatibleBitmap(toolStripHDC, bitmapSize.Width, bitmapSize.Height); IntPtr oldBitmap = Gdi32.SelectObject(_cachedItemHDC, _cachedItemBitmap); // delete the old bitmap if (oldBitmap != IntPtr.Zero) { Gdi32.DeleteObject(oldBitmap); } // remember what size we created. _cachedHDCSize = bitmapSize; } return _cachedItemHDC; } public void Dispose() { if (_cachedItemHDC != IntPtr.Zero) { // delete the bitmap if (_cachedItemBitmap != IntPtr.Zero) { Gdi32.DeleteObject(_cachedItemBitmap); _cachedItemBitmap = IntPtr.Zero; } // delete the DC itself. Gdi32.DeleteDC(_cachedItemHDC); } _cachedItemHDC = IntPtr.Zero; _cachedItemBitmap = IntPtr.Zero; _cachedHDCSize = Size.Empty; GC.SuppressFinalize(this); } ~CachedItemHdcInfo() { Dispose(); } } internal class MouseHoverTimer : IDisposable { private Timer mouseHoverTimer = new Timer(); // consider - weak reference? private ToolStripItem currentItem = null; public MouseHoverTimer() { mouseHoverTimer.Interval = SystemInformation.MouseHoverTime; mouseHoverTimer.Tick += new EventHandler(OnTick); } public void Start(ToolStripItem item) { if (item != currentItem) { Cancel(currentItem); } currentItem = item; if (currentItem != null) { mouseHoverTimer.Enabled = true; } } public void Cancel() { mouseHoverTimer.Enabled = false; currentItem = null; } /// <summary> cancels if and only if this item was the one that /// requested the timer /// </summary> public void Cancel(ToolStripItem item) { if (item == currentItem) { Cancel(); } } public void Dispose() { if (mouseHoverTimer != null) { Cancel(); mouseHoverTimer.Dispose(); mouseHoverTimer = null; } } private void OnTick(object sender, EventArgs e) { mouseHoverTimer.Enabled = false; if (currentItem != null && !currentItem.IsDisposed) { currentItem.FireEvent(EventArgs.Empty, ToolStripItemEventType.MouseHover); } } } /// <summary> /// This class supports the AllowItemReorder feature. /// When reordering items ToolStrip and ToolStripItem drag/drop events are routed here. /// </summary> internal sealed class ToolStripSplitStackDragDropHandler : IDropTarget, ISupportOleDropSource { private readonly ToolStrip owner; public ToolStripSplitStackDragDropHandler(ToolStrip owner) { this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); } public void OnDragEnter(DragEventArgs e) { Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragEnter: " + e.ToString()); if (e.Data.GetDataPresent(typeof(ToolStripItem))) { e.Effect = DragDropEffects.Move; ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y))); } } public void OnDragLeave(EventArgs e) { Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragLeave: " + e.ToString()); owner.ClearInsertionMark(); } public void OnDragDrop(DragEventArgs e) { Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragDrop: " + e.ToString()); if (e.Data.GetDataPresent(typeof(ToolStripItem))) { ToolStripItem item = (ToolStripItem)e.Data.GetData(typeof(ToolStripItem)); OnDropItem(item, owner.PointToClient(new Point(e.X, e.Y))); } } public void OnDragOver(DragEventArgs e) { Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "OnDragOver: " + e.ToString()); if (e.Data.GetDataPresent(typeof(ToolStripItem))) { if (ShowItemDropPoint(owner.PointToClient(new Point(e.X, e.Y)))) { e.Effect = DragDropEffects.Move; } else { if (owner != null) { owner.ClearInsertionMark(); } e.Effect = DragDropEffects.None; } } } public void OnGiveFeedback(GiveFeedbackEventArgs e) { } public void OnQueryContinueDrag(QueryContinueDragEventArgs e) { } private void OnDropItem(ToolStripItem droppedItem, Point ownerClientAreaRelativeDropPoint) { Point start = Point.Empty; int toolStripItemIndex = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); if (toolStripItemIndex >= 0) { ToolStripItem item = owner.Items[toolStripItemIndex]; if (item == droppedItem) { owner.ClearInsertionMark(); return; // optimization } RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); droppedItem.Alignment = item.Alignment; // Protect against negative indicies int insertIndex = Math.Max(0, toolStripItemIndex); if (relativeLocation == RelativeLocation.Above) { insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex + 1; } else if (relativeLocation == RelativeLocation.Below) { insertIndex = (item.Alignment == ToolStripItemAlignment.Left) ? insertIndex : insertIndex - 1; } else if (((item.Alignment == ToolStripItemAlignment.Left) && (relativeLocation == RelativeLocation.Left)) || ((item.Alignment == ToolStripItemAlignment.Right) && (relativeLocation == RelativeLocation.Right))) { // the item alignment is Tail & dropped to right of the center of the item // or the item alignment is Head & dropped to the left of the center of the item // Normally, insert the new item after the item, however in RTL insert before the item insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.Yes) ? insertIndex + 1 : insertIndex); } else { // the item alignment is Tail & dropped to left of the center of the item // or the item alignment is Head & dropped to the right of the center of the item // Normally, insert the new item before the item, however in RTL insert after the item insertIndex = Math.Max(0, (owner.RightToLeft == RightToLeft.No) ? insertIndex + 1 : insertIndex); } // If the control is moving from a lower to higher index, you actually want to set it one less than its position. // This is because it is being removed from its original position, which lowers the index of every control before // its new drop point by 1. if (owner.Items.IndexOf(droppedItem) < insertIndex) { insertIndex--; } owner.Items.MoveItem(Math.Max(0, insertIndex), droppedItem); owner.ClearInsertionMark(); } else if (toolStripItemIndex == -1 && owner.Items.Count == 0) { owner.Items.Add(droppedItem); owner.ClearInsertionMark(); } } private bool ShowItemDropPoint(Point ownerClientAreaRelativeDropPoint) { int i = GetItemInsertionIndex(ownerClientAreaRelativeDropPoint); if (i >= 0) { ToolStripItem item = owner.Items[i]; RelativeLocation relativeLocation = ComparePositions(item.Bounds, ownerClientAreaRelativeDropPoint); Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Drop relative loc " + relativeLocation); Debug.WriteLineIf(ToolStrip.ItemReorderDebug.TraceVerbose, "Index " + i); Rectangle insertionRect = Rectangle.Empty; switch (relativeLocation) { case RelativeLocation.Above: insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Top, owner.Width - (owner.Margin.Horizontal) - 1, ToolStrip.insertionBeamWidth); break; case RelativeLocation.Below: insertionRect = new Rectangle(owner.Margin.Left, item.Bounds.Bottom, owner.Width - (owner.Margin.Horizontal) - 1, ToolStrip.insertionBeamWidth); break; case RelativeLocation.Right: insertionRect = new Rectangle(item.Bounds.Right, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height - (owner.Margin.Vertical) - 1); break; case RelativeLocation.Left: insertionRect = new Rectangle(item.Bounds.Left, owner.Margin.Top, ToolStrip.insertionBeamWidth, owner.Height - (owner.Margin.Vertical) - 1); break; } owner.PaintInsertionMark(insertionRect); return true; } else if (owner.Items.Count == 0) { Rectangle insertionRect = owner.DisplayRectangle; insertionRect.Width = ToolStrip.insertionBeamWidth; owner.PaintInsertionMark(insertionRect); return true; } return false; } private int GetItemInsertionIndex(Point ownerClientAreaRelativeDropPoint) { for (int i = 0; i < owner.DisplayedItems.Count; i++) { Rectangle bounds = owner.DisplayedItems[i].Bounds; bounds.Inflate(owner.DisplayedItems[i].Margin.Size); if (bounds.Contains(ownerClientAreaRelativeDropPoint)) { Debug.WriteLineIf(ToolStrip.DropTargetDebug.TraceVerbose, "MATCH " + owner.DisplayedItems[i].Text + " Bounds: " + owner.DisplayedItems[i].Bounds.ToString()); // consider what to do about items not in the display return owner.Items.IndexOf(owner.DisplayedItems[i]); } } if (owner.DisplayedItems.Count > 0) { for (int i = 0; i < owner.DisplayedItems.Count; i++) { if (owner.DisplayedItems[i].Alignment == ToolStripItemAlignment.Right) { if (i > 0) { return owner.Items.IndexOf(owner.DisplayedItems[i - 1]); } return owner.Items.IndexOf(owner.DisplayedItems[i]); } } return owner.Items.IndexOf(owner.DisplayedItems[owner.DisplayedItems.Count - 1]); } return -1; } private enum RelativeLocation { Above, Below, Right, Left } private RelativeLocation ComparePositions(Rectangle orig, Point check) { if (owner.Orientation == Orientation.Horizontal) { int widthUnit = orig.Width / 2; RelativeLocation relativeLocation = RelativeLocation.Left; // we can return here if we are checking abovebelowleftright, because // the left right calculation is more picky than the above/below calculation // and the above below calculation will just override this one. if ((orig.Left + widthUnit) >= check.X) { relativeLocation = RelativeLocation.Left; return relativeLocation; } else if ((orig.Right - widthUnit) <= check.X) { relativeLocation = RelativeLocation.Right; return relativeLocation; } } if (owner.Orientation == Orientation.Vertical) { int heightUnit = orig.Height / 2; RelativeLocation relativeLocation = (check.Y <= (orig.Top + heightUnit)) ? RelativeLocation.Above : RelativeLocation.Below; return relativeLocation; } Debug.Fail("Could not calculate the relative position for AllowItemReorder"); return RelativeLocation.Left; } } }
38.915909
248
0.510313
[ "MIT" ]
SergeySmirnov-Akvelon/winforms
src/System.Windows.Forms/src/System/Windows/Forms/ToolStrip.cs
226,771
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 System.Runtime.Serialization; namespace OpenSearch.Client { /// <summary> /// An analyzer of type stop that is built using a Lower Case Tokenizer, with Stop Token Filter. /// </summary> public interface IStopAnalyzer : IAnalyzer { /// <summary> /// A list of stopword to initialize the stop filter with. Defaults to the english stop words. /// </summary> [DataMember(Name ="stopwords")] StopWords StopWords { get; set; } /// <summary> /// A path (either relative to config location, or absolute) to a stopwords file configuration. /// </summary> [DataMember(Name ="stopwords_path")] string StopwordsPath { get; set; } } /// <inheritdoc /> public class StopAnalyzer : AnalyzerBase, IStopAnalyzer { public StopAnalyzer() : base("stop") { } /// <inheritdoc /> public StopWords StopWords { get; set; } /// <inheritdoc /> public string StopwordsPath { get; set; } } /// <inheritdoc /> public class StopAnalyzerDescriptor : AnalyzerDescriptorBase<StopAnalyzerDescriptor, IStopAnalyzer>, IStopAnalyzer { protected override string Type => "stop"; StopWords IStopAnalyzer.StopWords { get; set; } string IStopAnalyzer.StopwordsPath { get; set; } public StopAnalyzerDescriptor StopWords(params string[] stopWords) => Assign(stopWords, (a, v) => a.StopWords = v); public StopAnalyzerDescriptor StopWords(IEnumerable<string> stopWords) => Assign(stopWords.ToListOrNullIfEmpty(), (a, v) => a.StopWords = v); public StopAnalyzerDescriptor StopWords(StopWords stopWords) => Assign(stopWords, (a, v) => a.StopWords = v); public StopAnalyzerDescriptor StopwordsPath(string path) => Assign(path, (a, v) => a.StopwordsPath = v); } }
34.54321
117
0.731951
[ "Apache-2.0" ]
opensearch-project/opensearch-net
src/OpenSearch.Client/Analysis/Analyzers/StopAnalyzer.cs
2,798
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.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryConvertTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertBoxingTest(bool useInterpreter) { foreach (var e in ConvertBoxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingTest(bool useInterpreter) { foreach (var e in ConvertUnboxing()) { VerifyUnaryConvert(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnboxingInvalidCastTest(bool useInterpreter) { foreach (var e in ConvertUnboxingInvalidCast()) { VerifyUnaryConvertThrows<InvalidCastException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryConvertBooleanToNumericTest(bool useInterpreter) { foreach (var kv in ConvertBooleanToNumeric()) { VerifyUnaryConvert(kv.Key, kv.Value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNonNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNonNullableValue()) { VerifyUnaryConvertThrows<NullReferenceException>(e, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertNullToNullableValueTest(bool useInterpreter) { foreach (var e in ConvertNullToNullableValue()) { VerifyUnaryConvert(e, null, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToEnumTypeTest(bool useInterpreter) { var enumValue = DayOfWeek.Monday; var value = (int)enumValue; foreach (var o in new[] { Expression.Constant(value, typeof(int)), Expression.Constant(value, typeof(ValueType)), Expression.Constant(value, typeof(object)) }) { VerifyUnaryConvert(Expression.Convert(o, typeof(DayOfWeek)), enumValue, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertUnderlyingTypeToNullableEnumTypeTest(bool useInterpreter) { var enumValue = DayOfWeek.Monday; var value = (int)enumValue; var cInt = Expression.Constant(value, typeof(int)); VerifyUnaryConvert(Expression.Convert(cInt, typeof(DayOfWeek?)), enumValue, useInterpreter); var cObj = Expression.Constant(value, typeof(object)); VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(cObj, typeof(DayOfWeek?)), useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void ConvertArrayToIncompatibleTypeTest(bool useInterpreter) { var arr = new object[] { "bar" }; foreach (var t in new[] { typeof(string[]), typeof(IEnumerable<char>[]) }) { VerifyUnaryConvertThrows<InvalidCastException>(Expression.Convert(Expression.Constant(arr), t), useInterpreter); } } private static IEnumerable<KeyValuePair<Expression, object>> ConvertBooleanToNumeric() { var boolF = Expression.Constant(false); var boolT = Expression.Constant(true); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(byte)), (byte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(sbyte)), (sbyte)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ushort)), (ushort)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(short)), (short)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(uint)), (uint)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(int)), (int)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(ulong)), (ulong)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(long)), (long)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(float)), (float)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(double)), (double)(b ? 1 : 0)); yield return new KeyValuePair<Expression, object>(factory(b ? boolT : boolF, typeof(char)), (char)(b ? 1 : 0)); } } } private static IEnumerable<Expression> ConvertNullToNonNullableValue() { var nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte)); yield return factory(nullC, typeof(sbyte)); yield return factory(nullC, typeof(ushort)); yield return factory(nullC, typeof(short)); yield return factory(nullC, typeof(uint)); yield return factory(nullC, typeof(int)); yield return factory(nullC, typeof(ulong)); yield return factory(nullC, typeof(long)); yield return factory(nullC, typeof(float)); yield return factory(nullC, typeof(double)); yield return factory(nullC, typeof(char)); yield return factory(nullC, typeof(TimeSpan)); yield return factory(nullC, typeof(DayOfWeek)); } } } private static IEnumerable<Expression> ConvertNullToNullableValue() { var nullC = Expression.Constant(null); var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { foreach (var b in new[] { false, true }) { yield return factory(nullC, typeof(byte?)); yield return factory(nullC, typeof(sbyte?)); yield return factory(nullC, typeof(ushort?)); yield return factory(nullC, typeof(short?)); yield return factory(nullC, typeof(uint?)); yield return factory(nullC, typeof(int?)); yield return factory(nullC, typeof(ulong?)); yield return factory(nullC, typeof(long?)); yield return factory(nullC, typeof(float?)); yield return factory(nullC, typeof(double?)); yield return factory(nullC, typeof(char?)); yield return factory(nullC, typeof(TimeSpan?)); yield return factory(nullC, typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertBoxing() { // C# Language Specification - 4.3.1 Boxing conversions // ---------------------------------------------------- var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From any value-type to the type object. // >>> From any value-type to the type System.ValueType. foreach (var t in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(1, typeof(int)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan)), t); yield return factory(Expression.Constant(1, typeof(int?)), t); yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(new TimeSpan(3, 14, 15), typeof(TimeSpan?)), t); yield return factory(Expression.Constant(null, typeof(int?)), t); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), t); yield return factory(Expression.Constant(null, typeof(TimeSpan?)), t); } // >>> From any non-nullable-value-type to any interface-type implemented by the value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { var t = o.GetType(); var c = Expression.Constant(o, t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } // >>> From any nullable-type to any interface-type implemented by the underlying type of the nullable-type. foreach (var o in new object[] { (int?)1, (DayOfWeek?)DayOfWeek.Monday, (TimeSpan?)new TimeSpan(3, 14, 15) }) { var t = o.GetType(); var n = typeof(Nullable<>).MakeGenericType(t); foreach (var c in new[] { Expression.Constant(o, n), Expression.Constant(null, n) }) { foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(c, i); } } } // >>> From any enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek)), typeof(Enum)); } // >>> From any nullable-type with an underlying enum-type to the type System.Enum. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(DayOfWeek?)), typeof(Enum)); yield return factory(Expression.Constant(null, typeof(DayOfWeek?)), typeof(Enum)); } } } private static IEnumerable<Expression> ConvertUnboxing() { // C# Language Specification - 4.3.2 Unboxing conversions // ---------------------------------------------------- var factories = new Func<Expression, Type, Expression>[] { Expression.Convert, Expression.ConvertChecked }; foreach (var factory in factories) { // >>> From the type object to any value-type. // >>> From the type System.ValueType to any value-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { var t = o.GetType(); var n = typeof(Nullable<>).MakeGenericType(t); foreach (var f in new[] { typeof(object), typeof(ValueType) }) { yield return factory(Expression.Constant(o, typeof(object)), t); yield return factory(Expression.Constant(o, typeof(object)), n); } } // >>> From any interface-type to any non-nullable-value-type that implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { var t = o.GetType(); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), t); } } // >>> From any interface-type to any nullable-type whose underlying type implements the interface-type. foreach (var o in new object[] { 1, DayOfWeek.Monday, new TimeSpan(3, 14, 15) }) { var t = o.GetType(); var n = typeof(Nullable<>).MakeGenericType(t); foreach (var i in t.GetTypeInfo().ImplementedInterfaces) { yield return factory(Expression.Constant(o, i), n); } } // >>> From the type System.Enum to any enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek)); } // >>> From the type System.Enum to any nullable-type with an underlying enum-type. { yield return factory(Expression.Constant(DayOfWeek.Monday, typeof(Enum)), typeof(DayOfWeek?)); yield return factory(Expression.Constant(null, typeof(Enum)), typeof(DayOfWeek?)); } } } private static IEnumerable<Expression> ConvertUnboxingInvalidCast() { var objs = new object[] { 1, 1L, 1.0f, 1.0, true, TimeSpan.FromSeconds(1), "bar" }; var types = objs.Select(o => o.GetType()).ToArray(); foreach (var o in objs) { var c = Expression.Constant(o, typeof(object)); foreach (var t in types) { if (t != o.GetType()) { yield return Expression.Convert(c, t); if (t.GetTypeInfo().IsValueType) { var n = typeof(Nullable<>).MakeGenericType(t); yield return Expression.Convert(c, n); } } } } } #endregion #region Test verifiers private static void VerifyUnaryConvert(Expression e, object o, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Equal(o, c()); } private static void VerifyUnaryConvertThrows<T>(Expression e, bool useInterpreter) where T : Exception { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Throws<T>(() => c()); } private static void VerifyUnaryConvert(Expression e, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); c(); // should not throw } #endregion } }
44.198391
171
0.539185
[ "MIT" ]
OceanYan/corefx
src/System.Linq.Expressions/tests/Unary/UnaryConvertTests.cs
16,488
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 rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for PendingMaintenanceAction Object /// </summary> public class PendingMaintenanceActionUnmarshaller : IUnmarshaller<PendingMaintenanceAction, XmlUnmarshallerContext>, IUnmarshaller<PendingMaintenanceAction, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public PendingMaintenanceAction Unmarshall(XmlUnmarshallerContext context) { PendingMaintenanceAction unmarshalledObject = new PendingMaintenanceAction(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Action", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Action = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AutoAppliedAfterDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.AutoAppliedAfterDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CurrentApplyDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CurrentApplyDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ForcedApplyDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.ForcedApplyDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OptInStatus", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.OptInStatus = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public PendingMaintenanceAction Unmarshall(JsonUnmarshallerContext context) { return null; } private static PendingMaintenanceActionUnmarshaller _instance = new PendingMaintenanceActionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static PendingMaintenanceActionUnmarshaller Instance { get { return _instance; } } } }
39.275591
185
0.579391
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/PendingMaintenanceActionUnmarshaller.cs
4,988
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using System.Collections; using UnityEngine.Events; using HoloToolkit.Unity.InputModule; namespace HoloToolkit.Examples.InteractiveElements { /// <summary> /// InteractiveToggleButton expands InteractiveToggle to expose a gaze, down and up state events in the inspector. /// /// Beyond the basic button functionality, Interactive also maintains the notion of selection and enabled, which allow for more robust UI features. /// InteractiveEffects are behaviors that listen for updates from Interactive, which allows for visual feedback to be customized and placed on /// individual elements of the Interactive GameObject /// </summary> public class InteractiveToggleButton : InteractiveToggle { public UnityEvent OnGazeEnterEvents; public UnityEvent OnGazeLeaveEvents; public UnityEvent OnDownEvents; public UnityEvent OnUpEvents; /// <summary> /// The gameObject received gaze /// </summary> public override void OnFocusEnter() { base.OnFocusEnter(); OnGazeEnterEvents.Invoke(); } /// <summary> /// The gameObject no longer has gaze /// </summary> public override void OnFocusExit() { base.OnFocusExit(); OnGazeLeaveEvents.Invoke(); } /// <summary> /// The user is initiating a tap or hold /// </summary> public override void OnInputDown(InputEventData eventData) { base.OnInputDown(eventData); OnDownEvents.Invoke(); } /// <summary> /// All tab, hold, and gesture events are completed /// </summary> public override void OnInputUp(InputEventData eventData) { bool ignoreRelease = mCheckRollOff; base.OnInputUp(eventData); if (!ignoreRelease) { OnUpEvents.Invoke(); } } } }
32.42029
152
0.60751
[ "MIT" ]
UBCHiveLab/SpectatorBrain
UnityProject/Assets/HoloToolkit-Examples/UX/Scripts/InteractiveToggleButton.cs
2,239
C#
using MediatR; using VideoCollection.Data; using VideoCollection.Data.Models; using VideoCollection.Utilities; using System.Threading.Tasks; using System.Data.Entity; namespace VideoCollection.Features.Blog { public class AddOrUpdateAuthorAvatarCommand { public class AddOrUpdateAuthorAvatarRequest : IRequest<AddOrUpdateAuthorAvatarResponse> { public AuthorAvatarApiModel AuthorAvatar { get; set; } } public class AddOrUpdateAuthorAvatarResponse { } public class AddOrUpdateAuthorAvatarHandler : IAsyncRequestHandler<AddOrUpdateAuthorAvatarRequest, AddOrUpdateAuthorAvatarResponse> { public AddOrUpdateAuthorAvatarHandler(VideoCollectionDataContext dataContext, ICache cache) { _dataContext = dataContext; _cache = cache; } public async Task<AddOrUpdateAuthorAvatarResponse> Handle(AddOrUpdateAuthorAvatarRequest request) { var entity = await _dataContext.AuthorAvatars .SingleOrDefaultAsync(x => x.Id == request.AuthorAvatar.Id && x.IsDeleted == false); if (entity == null) _dataContext.AuthorAvatars.Add(entity = new AuthorAvatar()); await _dataContext.SaveChangesAsync(); return new AddOrUpdateAuthorAvatarResponse() { }; } private readonly VideoCollectionDataContext _dataContext; private readonly ICache _cache; } } }
35.790698
139
0.666667
[ "MIT" ]
QuinntyneBrown/video-collection
src/Backend/VideoCollection/Features/Blog/AddOrUpdateAuthorAvatarCommand.cs
1,539
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Shopping_cart.Migrations { public partial class Added_Description_And_IsActive_To_Role : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Description", table: "AbpRoles", maxLength: 5000, nullable: true); migrationBuilder.AddColumn<bool>( name: "IsActive", table: "AbpRoles", nullable: false, defaultValue: false); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Description", table: "AbpRoles"); migrationBuilder.DropColumn( name: "IsActive", table: "AbpRoles"); } } }
28.205882
75
0.547445
[ "MIT" ]
vishnupriya55/Shopping_cart
aspnet-core/src/Shopping_cart.EntityFrameworkCore/Migrations/20170621153937_Added_Description_And_IsActive_To_Role.cs
961
C#
using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace LC_Tools { public sealed class BinaryMessage { private readonly List<byte[]> _sendList = new List<byte[]>(); private int _readOffset; private byte[] _receiveArray; public int SendMsgSize { get; private set; } public int ProtocolId { get; set; } public int ReceiveSize() { return _receiveArray?.Length ?? 0; } public static BinaryMessage CreateBinary(byte[] content) { var binary = new BinaryMessage(); const int intLen = sizeof(int); if (content.Length < intLen) { Debug.LogError($"== Change Error == len:[{content.Length}]"); return binary; } var proctorId = BitConverter.ToInt32(content, 0); binary.ProtocolId = proctorId; if (content.Length == intLen) return binary; var messageLen = content.Length - intLen; var message_array = new byte[messageLen]; Array.Copy(content, intLen, message_array, 0, messageLen); binary.SetReceiveBuffer(message_array); return binary; } public void SetReceiveBuffer(byte[] data) { _receiveArray = data; } public byte[] GetSendBuffer() { const int int_len = sizeof(int); var totalLen = int_len * 2 + SendMsgSize; var retArr = new byte[totalLen]; var startIdx = 0; var lenArr = BitConverter.GetBytes(totalLen); Array.Copy(lenArr, 0, retArr, startIdx, lenArr.Length); var protocolArr = BitConverter.GetBytes(ProtocolId); startIdx += int_len; Array.Copy(protocolArr, 0, retArr, startIdx, protocolArr.Length); // start_idx += type_len; // Array.Copy(len_arr, 0, ret_arr, start_idx, len_arr.Length); startIdx += int_len; foreach (var single in _sendList) { Array.Copy(single, 0, retArr, startIdx, single.Length); startIdx += single.Length; } return retArr; } public void Add<T>(T data) { switch (data) { // Debug.LogWarning($"========= Add Type: [{data.GetType()}]========="); case string _: { var dataStr = Convert.ToString(data); var contArr = Encoding.UTF8.GetBytes(dataStr); var contentLen = BitConverter.GetBytes(contArr.Length + 1); const int int_len = sizeof(int); var arrLen = int_len + contArr.Length + 1; var destArr = new byte[arrLen]; Array.Copy(contentLen, destArr, contentLen.Length); var startIdx = int_len; Array.Copy(contArr, 0, destArr, startIdx, contArr.Length); AddBufferList(destArr.Length, destArr); break; } case char[] _: { var array = data as Array; var dest = new char[array.Length]; for (var i = 0; i < array.Length; i++) { dest[i] = (char) array.GetValue(i); } var bytes = Encoding.Unicode.GetBytes(dest); var arr = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytes, 0, bytes.Length); AddBufferList(bytes.Length, arr); break; } case byte[] _: { var array = data as Array; var dest = new byte[array.Length]; for (var i = 0; i < array.Length; i++) { dest[i] = (byte) array.GetValue(i); } AddBufferList(dest.Length, dest); break; } } if (!(data is ValueType)) { return; } var typeLen = 0; byte[] destArray = null; switch (data) { //Debug.LogWarning(string.Format("========= Add Type ========= type:[{0}] Len:[{1}]", type_str, len)); case bool _: typeLen = sizeof(bool); destArray = BitConverter.GetBytes(Convert.ToBoolean(data)); break; case byte _: typeLen = sizeof(byte); destArray = new[] {Convert.ToByte(data)}; break; case char _: typeLen = sizeof(char); destArray = BitConverter.GetBytes(Convert.ToChar(data)); break; case ushort _: typeLen = sizeof(ushort); destArray = BitConverter.GetBytes(Convert.ToUInt16(data)); break; case short _: typeLen = sizeof(short); destArray = BitConverter.GetBytes(Convert.ToInt16(data)); break; case uint _: typeLen = sizeof(uint); destArray = BitConverter.GetBytes(Convert.ToUInt32(data)); break; case int _: typeLen = sizeof(int); destArray = BitConverter.GetBytes(Convert.ToInt32(data)); break; case ulong _: typeLen = sizeof(ulong); destArray = BitConverter.GetBytes(Convert.ToUInt64(data)); break; case long _: typeLen = sizeof(long); destArray = BitConverter.GetBytes(Convert.ToInt64(data)); break; case float _: typeLen = sizeof(float); destArray = BitConverter.GetBytes(Convert.ToSingle(data)); break; case double _: typeLen = sizeof(double); destArray = BitConverter.GetBytes(Convert.ToDouble(data)); break; } if (destArray != null) { AddBufferList(typeLen, destArray); } else { Debug.LogError("== BinaryMessage Add Length is Zero =="); } } public bool GetBoolean() { var dest = ReadByte(sizeof(bool)); return BitConverter.ToBoolean(dest, 0); } public byte GetByte() { var dest = ReadByte(sizeof(byte)); return dest[0]; } public char GetChar() { var dest = ReadByte(sizeof(char)); return BitConverter.ToChar(dest, 0); } public ushort GetUInt16() { var dest = ReadByte(sizeof(ushort)); return BitConverter.ToUInt16(dest, 0); } public short GetInt16() { var dest = ReadByte(sizeof(short)); return BitConverter.ToInt16(dest, 0); } public uint GetUInt32() { var dest = ReadByte(sizeof(uint)); return BitConverter.ToUInt32(dest, 0); } public int GetInt32() { var dest = ReadByte(sizeof(int)); return BitConverter.ToInt32(dest, 0); } public ulong GetUInt64() { var dest = ReadByte(sizeof(ulong)); return BitConverter.ToUInt64(dest, 0); } public long GetInt64() { var dest = ReadByte(sizeof(long)); return BitConverter.ToInt64(dest, 0); } public float GetFloat() { var dest = ReadByte(sizeof(float)); return BitConverter.ToSingle(dest, 0); } public double GetDouble() { var dest = ReadByte(sizeof(double)); return BitConverter.ToDouble(dest, 0); } public char[] GetCharArray() { var strLen = ReadByte(sizeof(int)); var readLen = BitConverter.ToInt32(strLen, 0); var dest = ReadByte(readLen); var charArr = new char[readLen]; Array.Copy(dest, charArr, readLen); return charArr; } public byte[] GetByteArray() { var strLen = ReadByte(sizeof(int)); var readLen = BitConverter.ToInt32(strLen, 0); return ReadByte(readLen); } public string GetString() { var strLen = ReadByte(sizeof(int)); if (strLen == null || strLen.Length == 0) return string.Empty; var readLen = BitConverter.ToInt32(strLen, 0); if (readLen == 0) return string.Empty; var dest = ReadByte(readLen); return Encoding.UTF8.GetString(dest); } public void Clear() { ProtocolId = 0; SendMsgSize = 0; _sendList.Clear(); _readOffset = sizeof(int) * 2; _receiveArray = new byte[0]; } private void AddBufferList(int typeLen, byte[] arr) { _sendList.Add(arr); SendMsgSize += typeLen; } private byte[] ReadByte(int len) { if (len == 0) return new byte[0]; if (len < 0 || _receiveArray == null) { Debug.LogError("== BinaryMessage ReadByte receive_array is null =="); return new byte[0]; } var lave = _receiveArray.Length - _readOffset; if (lave < len) { Debug.LogError($"== BinaryMessage ReadByte Error ID:[{ProtocolId}] Length:[{lave}] Get:[{len}]=="); return new byte[0]; } var dest = new byte[len]; Array.Copy(_receiveArray, _readOffset, dest, 0, len); _readOffset += len; return dest; } } }
32.364486
118
0.470786
[ "BSD-3-Clause" ]
LacusCon/ILHotFix
Assets/Scripts/LC_Tools/Message/BinaryMessage.cs
10,389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace SharpMessaging.Persistence { /// <summary> /// Facade for the queue files /// </summary> /// <remarks> /// <para> /// Persistant coordinates the reader and writer classes. It switches files when required and keep track of the /// file size. /// </para> /// </remarks> public class PersistantQueue : IPersistantQueue { private readonly IQueueFileManager _fileManager; private int _count = 0; private IPersistantQueueFileReader _readFile; private IPersistantQueueFileWriter _writefile; public PersistantQueue(string queuePath, string optionalReadQueuePath, string queueName) { if (queuePath == null) throw new ArgumentNullException("queuePath"); if (queueName == null) throw new ArgumentNullException("queueName"); _fileManager = new QueueFileManager(queuePath, optionalReadQueuePath, queueName); MaxFileSizeInBytes = 30000000; } public PersistantQueue(string queuePath, string queueName) { if (queuePath == null) throw new ArgumentNullException("queuePath"); if (queueName == null) throw new ArgumentNullException("queueName"); _fileManager = new QueueFileManager(queuePath, queueName); MaxFileSizeInBytes = 30000000; } public PersistantQueue(IQueueFileManager queueFileManager) { if (queueFileManager == null) throw new ArgumentNullException("queueFileManager"); MaxFileSizeInBytes = 30000000; _fileManager = queueFileManager; } /// <summary> /// Max amount of bytes that can be written to the file. /// </summary> /// <remarks> /// <para> /// Do note that the writer will exceed this limit and switch to a new file as soon as it can. /// </para> /// </remarks> public int MaxFileSizeInBytes { get; set; } public int Count { get { if (_writefile == null) throw new InvalidOperationException("Must Open() queue first."); return _count; } } /// <summary> /// Close both the reader and writer side. /// </summary> public void Close() { _readFile.Close(); _writefile.Close(); } /// <summary> /// Dequeue a set of records. /// </summary> /// <param name="buffers">Will be cleared and then filled with all available buffers</param> /// <param name="maxAmountOfMessages">Number of wanted records (will return less if less are available)</param> public void Dequeue(List<byte[]> buffers, int maxAmountOfMessages) { if (buffers == null) throw new ArgumentNullException("buffers"); var initialSize = buffers.Count; var count1 = _readFile.Dequeue(buffers, maxAmountOfMessages); if (buffers.Any()) { Interlocked.Add(ref _count, 0 - count1); return; } if (!TryOpenNextReadFile()) return; var leftToEnqueue = maxAmountOfMessages - (buffers.Count - initialSize); var count2 = _readFile.Dequeue(buffers, leftToEnqueue); Interlocked.Add(ref _count, 0 - (count1 + count2)); } /// <summary> /// Write a record to the file /// </summary> /// <param name="buffer"></param> /// <remarks> /// <para> /// Make sure that you call <see cref="FlushWriter" /> once you've enqueued all messages in the current batch. /// There is otherwise no guarantee that the content have been written to disk. /// </para> /// </remarks> public void Enqueue(byte[] buffer) { if (buffer == null) throw new ArgumentNullException("buffer"); Enqueue(buffer, 0, buffer.Length); } /// <summary> /// Write a record to the file /// </summary> /// <param name="buffer">Buffer to read record from</param> /// <param name="offset">Start offset of the record</param> /// <param name="count">Number of bytes to write (starting at offset)</param> /// <remarks> /// <para> /// Make sure that you call <see cref="FlushWriter" /> once you've enqueued all messages in the current batch. /// There is otherwise no guarantee that the content have been written to disk. /// </para> /// </remarks> public void Enqueue(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); if (_writefile.FileSize > MaxFileSizeInBytes) { _writefile.Close(); _writefile = _fileManager.CreateNewWriteFile(); } _writefile.Enqueue(buffer, offset, count); Interlocked.Increment(ref _count); } /// <summary> /// Flush write IO to disk, i.e. make sure that everything is written to the file (and not being left in the OS IO /// buffer) /// </summary> /// <remarks> /// <para>MUST be done after enqueue operations</para> /// </remarks> public void FlushWriter() { _writefile.Flush(); } /// <summary> /// Open our files /// </summary> public void Open() { _fileManager.Scan(); _writefile = _fileManager.OpenCurrentWriteFile(); _readFile = _fileManager.OpenCurrentReadFile(); _count = _fileManager.InitialQueueLength; } /// <summary> /// Read from the file, but do not update the positition (in the position file) /// </summary> /// <param name="buffers">The list will be appended with all available records (max <c>maxNumberOfMessages</c> records).</param> /// <param name="maxNumberOfMessages">Number of wanted records (will return less if less are available)</param> public void Peek(List<byte[]> buffers, int maxNumberOfMessages) { if (buffers == null) throw new ArgumentNullException("buffers"); var initialSize = buffers.Count; _readFile.Peek(buffers, maxNumberOfMessages); if (buffers.Any()) return; if (!TryOpenNextReadFile()) return; var leftToEnqueue = maxNumberOfMessages - (buffers.Count - initialSize); _readFile.Peek(buffers, leftToEnqueue); } /// <summary> /// Try to dequeue a record /// </summary> /// <param name="buffer">Record dequeued</param> /// <returns><c>true</c> if there was a record available; otherwise <c>false</c></returns> public bool TryDequeue(out byte[] buffer) { if (_readFile.TryDequeue(out buffer)) { Interlocked.Decrement(ref _count); return true; } if (!TryOpenNextReadFile()) return false; var success = _readFile.TryDequeue(out buffer); if (success) { Interlocked.Decrement(ref _count); } return success; } /// <summary> /// Try to peek a record (i.e. to not update the position file) /// </summary> /// <param name="buffer">Record dequeued</param> /// <returns><c>true</c> if there was a record available; otherwise <c>false</c></returns> public bool TryPeek(out byte[] buffer) { if (_readFile.TryPeek(out buffer)) return true; if (!TryOpenNextReadFile()) return false; return _readFile.TryPeek(out buffer); } public void Remove(int count) { if (count <= 0 || count > Count) throw new ArgumentOutOfRangeException("count", count, string.Format("Expected to be between 1 and {0}.", count)); var buffers = new List<byte[]>(); var count1 = _readFile.Dequeue(buffers, count); if (buffers.Any()) { Interlocked.Add(ref _count, 0 - count1); return; } if (!TryOpenNextReadFile()) return; var count2 = _readFile.Dequeue(buffers, count - count1); Interlocked.Add(ref _count, 0 - (count1 + count2)); } private bool TryOpenNextReadFile() { // we are in the same file for reads and writes. i.e. it do currently not have any more records to read. if (!_fileManager.CanIncreaseReadFile()) return false; _readFile.Delete(); _readFile = _fileManager.OpenNextReadFile(); return true; } } }
35.984962
137
0.533849
[ "Apache-2.0" ]
gauffininteractive/SharpMessaging
src/lib/SharpMessaging/Persistence/PersistantQueue.cs
9,572
C#
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; namespace DemoV3.Model.Base { /// AUTOGENERED BY caffoa /// [JsonObject(MemberSerialization.OptIn)] public partial class Address { public const string AddressObjectName = "address"; [JsonProperty("street", Required = Required.Always)] public virtual string Street { get; set; } [JsonProperty("street.extra")] public virtual string StreetExtra { get; set; } [JsonProperty("postalCode", Required = Required.Always)] public virtual string PostalCode { get; set; } [JsonProperty("city", Required = Required.Always)] public virtual string City { get; set; } [JsonProperty("country", Required = Required.Always)] public virtual string Country { get; set; } [JsonProperty("flags")] public virtual Dictionary<string, Flags> Flags { get; set; } = new Dictionary<string, Flags>(); [JsonExtensionData] public Dictionary<string, object> AdditionalProperties; public Address(){} public Address(Address other) { Street = other.Street; StreetExtra = other.StreetExtra; PostalCode = other.PostalCode; City = other.City; Country = other.Country; Flags = other.Flags; AdditionalProperties = other.AdditionalProperties != null ? new Dictionary<string, object>(other.AdditionalProperties) : null; } public Address ToAddress() => new Address(this); } }
34.276596
138
0.641217
[ "MIT" ]
claasd/caffoa.net
demo/DemoV3/Model/Base/Address.generated.cs
1,611
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using static Root; /// <summary> /// Defines a vertex to which data may be attached /// </summary> /// <typeparam name="K">The vertex index type</typeparam> /// <typeparam name="T">The payload type</typeparam> public struct Node<K,T> : INode<K,T> where K : unmanaged { /// <summary> /// The index of the vertex that uniquely identifies it within a graph /// </summary> public K Index; /// <summary> /// The vertex payload /// </summary> public T Content; [MethodImpl(Inline)] public Node(K index, T content) { Index = index; Content = content; } K INode<K,T>.Index => Index; T INode<T>.Content => Content; public string Format() => string.Format("({0},{1})", Index, Content); public override string ToString() => Format(); [MethodImpl(Inline)] public static Arrow<K> operator +(in Node<K,T> src, in Node<K,T> dst) => new Arrow<K>(src.Index, dst.Index); /// <summary> /// Sheds the associated data to form a payload-free vertex /// </summary> /// <param name="src">The source vertex</param> [MethodImpl(Inline)] public static implicit operator Node<T>(in Node<K,T> src) => new Node<T>(core.bw32(src.Index), src.Content); } }
28.901639
79
0.485536
[ "BSD-3-Clause" ]
0xCM/z0
src/relations/src/models/NodeKT.cs
1,763
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Modules { #region Using using System; using System.Linq; using System.Text; using System.Web.UI.HtmlControls; using YAF.Types; using YAF.Types.Attributes; using YAF.Types.Constants; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Utils.Helpers; using YAF.Web.Controls; using YAF.Web.EventsArgs; #endregion /// <summary> /// Page Title Module /// </summary> [Module("Page Title Module", "Tiny Gecko", 1)] public class PageTitleForumModule : SimpleBaseForumModule { #region Constants and Fields /// <summary> /// The forum page title. /// </summary> private string forumPageTitle; #endregion #region Public Methods /// <summary> /// The init after page. /// </summary> public override void InitAfterPage() { this.CurrentForumPage.PreRender += this.ForumPage_PreRender; this.CurrentForumPage.Load += this.ForumPage_Load; } #endregion #region Methods /// <summary> /// Handles the Load event of the ForumPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void ForumPage_Load([NotNull] object sender, [NotNull] EventArgs e) { this.GeneratePageTitle(); } /// <summary> /// Handles the PreRender event of the ForumPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void ForumPage_PreRender([NotNull] object sender, [NotNull] EventArgs e) { var head = this.ForumControl.Page.Header ?? this.CurrentForumPage.FindControlRecursiveBothAs<HtmlHead>("YafHead"); if (head != null) { // setup the title... var addition = string.Empty; if (head.Title.IsSet()) { addition = $" - {head.Title.Trim()}"; } head.Title = $"{this.forumPageTitle}{addition}"; } else { // old style var title = this.CurrentForumPage.FindControlRecursiveBothAs<HtmlTitle>("ForumTitle"); if (title != null) { title.Text = this.forumPageTitle; } } } /// <summary> /// Creates this pages title and fires a PageTitleSet event if one is set /// </summary> private void GeneratePageTitle() { // compute page title.. var title = new StringBuilder(); var pageString = string.Empty; if (this.ForumPageType == ForumPages.Posts || this.ForumPageType == ForumPages.Topics) { // get current page... var currentPager = this.CurrentForumPage.FindControlAs<Pager>("Pager"); if (currentPager != null && currentPager.CurrentPageIndex != 0) { pageString = $"- Page {currentPager.CurrentPageIndex + 1}"; } } var addBoardName = true; if (!this.PageContext.CurrentForumPage.IsAdminPage) { switch (this.ForumPageType) { case ForumPages.Posts: if (this.PageContext.PageTopicID != 0) { // Tack on the topic we're viewing title.Append( this.Get<IBadWordReplace>().Replace(this.PageContext.PageTopicName.Truncate(80))); } addBoardName = false; // Append Current Page title.Append(pageString); break; case ForumPages.Topics: if (this.PageContext.PageForumName != string.Empty) { // Tack on the forum we're viewing title.Append(this.CurrentForumPage.HtmlEncode(this.PageContext.PageForumName.Truncate(80))); } addBoardName = false; // Append Current Page title.Append(pageString); break; case ForumPages.Board: if (this.PageContext.PageCategoryName != string.Empty) { addBoardName = false; // Tack on the forum we're viewing title.Append( this.CurrentForumPage.HtmlEncode(this.PageContext.PageCategoryName.Truncate(80))); } break; default: var pageLinks = this.CurrentForumPage.FindControlAs<PageLinks>("PageLinks"); var activePageLink = pageLinks?.PageLinkList?.FirstOrDefault(link => link.URL.IsNotSet()); if (activePageLink != null) { addBoardName = false; // Tack on the forum we're viewing title.Append(this.CurrentForumPage.HtmlEncode(activePageLink.Title.Truncate(80))); } break; } } if (addBoardName) { // and lastly, tack on the board's name title.Append(this.CurrentForumPage.HtmlEncode(this.PageContext.BoardSettings.Name)); } this.forumPageTitle = title.ToString(); this.ForumControl.FirePageTitleSet(this, new ForumPageTitleArgs(this.forumPageTitle)); } #endregion } }
35.037559
121
0.51293
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/YetAnotherForum.NET/Modules/PageTitleForumModule.cs
7,252
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("Login (If verschachteln)")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Login (If verschachteln)")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("432e854f-35b2-40c9-82ed-e1636bb90634")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.216216
107
0.745198
[ "MIT" ]
PatrickKranig/basics-C-console
Abfagen - If - Wenn/Login (If verschachteln)/Login (If verschachteln)/Properties/AssemblyInfo.cs
1,578
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the organizations-2016-11-28.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.Organizations { /// <summary> /// Configuration for accessing Amazon Organizations service /// </summary> public partial class AmazonOrganizationsConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.0.50"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonOrganizationsConfig() { this.AuthenticationServiceName = "organizations"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "organizations"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2016-11-28"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.4125
111
0.592522
[ "Apache-2.0" ]
mikemissakian/aws-sdk-net
sdk/src/Services/Organizations/Generated/AmazonOrganizationsConfig.cs
2,113
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 Xunit; namespace System.Windows.Forms.Tests { public class ToolStripTests { [Fact] public void ToolStrip_Constructor() { var ts = new ToolStrip(); Assert.NotNull(ts); Assert.False(ts.ImageScalingSize.IsEmpty); Assert.Equal(16, ts.ImageScalingSize.Width); Assert.Equal(16, ts.ImageScalingSize.Height); Assert.True(ts.CanOverflow); Assert.False(ts.TabStop); Assert.False(ts.MenuAutoExpand); Assert.NotNull(ToolStripManager.ToolStrips); Assert.True(ToolStripManager.ToolStrips.Contains(ts)); Assert.True(ts.AutoSize); Assert.False(ts.CausesValidation); Assert.Equal(100, ts.Size.Width); Assert.Equal(25, ts.Size.Height); Assert.True(ts.ShowItemToolTips); } [Fact] public void ToolStrip_ConstructorItems() { var button = new ToolStripButton(); var items = new ToolStripItem[1] { button }; var ts = new ToolStrip(items); Assert.NotNull(ts); Assert.NotNull(ts.Items); Assert.Single(ts.Items); Assert.Equal(button, ts.Items[0]); } } }
31.829787
78
0.588235
[ "MIT" ]
0xflotus/winforms
src/System.Windows.Forms/tests/UnitTests/ToolStrip.cs
1,498
C#
// Copyright © 2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using CefSharp.Example; using CefSharp.Example.Handlers; using CefSharp.Internals; using CefSharp.OffScreen; using Xunit; using Xunit.Abstractions; namespace CefSharp.Test.OffScreen { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] public class OffScreenBrowserBasicFacts { //TODO: Move into own file/namespace public class AsyncBoundObject { public bool MethodCalled { get; set; } public string Echo(string arg) { MethodCalled = true; return arg; } } private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; public OffScreenBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; } [Fact] public async Task CanLoadGoogle() { using (var browser = new ChromiumWebBrowser("www.google.com")) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); output.WriteLine("Url {0}", mainFrame.Url); } } [Fact] public void BrowserRefCountDecrementedOnDispose() { var manualResetEvent = new ManualResetEvent(false); var browser = new ChromiumWebBrowser("https://google.com"); browser.LoadingStateChanged += (sender, e) => { if (!e.IsLoading) { manualResetEvent.Set(); } }; manualResetEvent.WaitOne(); //TODO: Refactor this so reference is injected into browser Assert.Equal(1, BrowserRefCounter.Instance.Count); browser.Dispose(); Assert.True(BrowserRefCounter.Instance.Count <= 1); Cef.WaitForBrowsersToClose(); Assert.Equal(0, BrowserRefCounter.Instance.Count); } [Fact] public async Task CanLoadGoogleAndEvaluateScript() { using (var browser = new ChromiumWebBrowser("www.google.com")) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("www.google", mainFrame.Url); var javascriptResponse = await browser.EvaluateScriptAsync("2 + 2"); Assert.True(javascriptResponse.Success); Assert.Equal(4, (int)javascriptResponse.Result); output.WriteLine("Result of 2 + 2: {0}", javascriptResponse.Result); } } [Fact] public async Task CrossSiteNavigationJavascriptBinding() { const string script = @" (async function() { await CefSharp.BindObjectAsync('bound'); bound.echo('test'); })();"; var boundObj = new AsyncBoundObject(); using (var browser = new ChromiumWebBrowser("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url")) { #if NETCOREAPP browser.JavascriptObjectRepository.Register("bound", boundObj); #else browser.JavascriptObjectRepository.Register("bound", boundObj, true); #endif await browser.LoadPageAsync(); browser.GetMainFrame().ExecuteJavaScriptAsync(script); await Task.Delay(2000); Assert.True(boundObj.MethodCalled); boundObj.MethodCalled = false; browser.Load("https://www.google.com"); await browser.LoadPageAsync(); browser.GetMainFrame().ExecuteJavaScriptAsync(script); await Task.Delay(2000); Assert.True(boundObj.MethodCalled); } } [Fact] public async Task JavascriptBindingMultipleObjects() { const string script = @" (async function() { await CefSharp.BindObjectAsync('first'); await CefSharp.BindObjectAsync('first', 'second'); })();"; var objectNames = new List<string>(); var boundObj = new AsyncBoundObject(); using (var browser = new ChromiumWebBrowser("https://www.google.com")) { browser.JavascriptObjectRepository.ResolveObject += (s, e) => { objectNames.Add(e.ObjectName); #if NETCOREAPP e.ObjectRepository.Register(e.ObjectName, boundObj); #else e.ObjectRepository.Register(e.ObjectName, boundObj, isAsync: true); #endif }; await browser.LoadPageAsync(); browser.GetMainFrame().ExecuteJavaScriptAsync(script); await Task.Delay(2000); Assert.Equal(new[] { "first", "second" }, objectNames); } } /// <summary> /// Use the EvaluateScriptAsync (IWebBrowser, String,Object[]) overload and pass in string params /// that require encoding. Test case for https://github.com/cefsharp/CefSharp/issues/2339 /// </summary> /// <returns>A task</returns> [Fact] public async Task CanEvaluateScriptAsyncWithEncodedStringArguments() { using (var browser = new ChromiumWebBrowser("http://www.google.com")) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); var javascriptResponse = await browser.EvaluateScriptAsync("var testfunc=function(s) { return s; }"); Assert.True(javascriptResponse.Success); // now call the function we just created string[] teststrings = new string[]{"Mary's\tLamb & \r\nOther Things", "[{test:\"Mary's Lamb & \\nOther Things\", 'other': \"\", 'and': null}]" }; foreach (var test in teststrings) { javascriptResponse = await browser.EvaluateScriptAsync("testfunc", test); Assert.True(javascriptResponse.Success); Assert.Equal(test, (string)javascriptResponse.Result); output.WriteLine("{0} passes {1}", test, javascriptResponse.Result); } } } [Theory] [InlineData("return 42;", true, "42")] [InlineData("return new Promise(function(resolve, reject) { resolve(42); });", true, "42")] [InlineData("return new Promise(function(resolve, reject) { reject('reject test'); });", false, "reject test")] public async Task CanEvaluateScriptAsPromiseAsync(string script, bool success, string expected) { using (var browser = new ChromiumWebBrowser("http://www.google.com")) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); var javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script); Assert.Equal(success, javascriptResponse.Success); if (success) { Assert.Equal(expected, javascriptResponse.Result.ToString()); } else { Assert.Equal(expected, javascriptResponse.Message); } } } [Fact] public async Task CanMakeFrameUrlRequest() { using (var browser = new ChromiumWebBrowser("https://code.jquery.com/jquery-3.4.1.min.js")) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); var taskCompletionSource = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); var wasCached = false; var requestClient = new UrlRequestClient((IUrlRequest req, byte[] responseBody) => { wasCached = req.ResponseWasCached; taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); }); //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread await Cef.UIThreadTaskFactory.StartNew(delegate { var request = mainFrame.CreateRequest(false); request.Method = "GET"; request.Url = "https://code.jquery.com/jquery-3.4.1.min.js"; var urlRequest = mainFrame.CreateUrlRequest(request, requestClient); }); var stringResult = await taskCompletionSource.Task; Assert.True(!string.IsNullOrEmpty(stringResult)); Assert.True(wasCached); } } [Fact] public async Task CanMakeUrlRequest() { var taskCompletionSource = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); IUrlRequest urlRequest = null; int statusCode = -1; //Can be created on any valid CEF Thread, here we'll use the CEF UI Thread await Cef.UIThreadTaskFactory.StartNew(delegate { var requestClient = new UrlRequestClient((IUrlRequest req, byte[] responseBody) => { statusCode = req.Response.StatusCode; taskCompletionSource.TrySetResult(Encoding.UTF8.GetString(responseBody)); }); var request = new Request(); request.Method = "GET"; request.Url = "https://code.jquery.com/jquery-3.4.1.min.js"; //Global RequestContext will be used urlRequest = new UrlRequest(request, requestClient); }); var stringResult = await taskCompletionSource.Task; Assert.True(!string.IsNullOrEmpty(stringResult)); Assert.Equal(200, statusCode); } [Theory] //TODO: Add more urls [InlineData("http://www.google.com", "http://cefsharp.github.io/")] public async Task CanExecuteJavascriptInMainFrameAfterNavigatingToDifferentOrigin(string firstUrl, string secondUrl) { using (var browser = new ChromiumWebBrowser(firstUrl)) { await browser.LoadPageAsync(); Assert.True(browser.CanExecuteJavascriptInMainFrame); await browser.LoadPageAsync(secondUrl); Assert.True(browser.CanExecuteJavascriptInMainFrame); await browser.LoadPageAsync(firstUrl); Assert.True(browser.CanExecuteJavascriptInMainFrame); } } [SkipIfRunOnAppVeyorFact] public async Task CanLoadHttpWebsiteUsingProxy() { fixture.StartProxyServerIfRequired(); var requestContext = RequestContext .Configure() .WithProxyServer("127.0.0.1", 8080) .Create(); using (var browser = new ChromiumWebBrowser("http://cefsharp.github.io/", requestContext: requestContext)) { await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.Contains("cefsharp.github.io", mainFrame.Url); output.WriteLine("Url {0}", mainFrame.Url); } } } }
36.517647
128
0.5625
[ "BSD-3-Clause" ]
kevinnet37/CefSharp
CefSharp.Test/OffScreen/OffScreenBrowserBasicFacts.cs
12,417
C#
// SPDX-License-Identifier: BSD-3-Clause // // Copyright 2020 Raritan Inc. All rights reserved. // // This file was generated by IdlC from NumericSensor.idl. using System; using System.Linq; using LightJson; using Com.Raritan.Idl; using Com.Raritan.JsonRpc; using Com.Raritan.Util; #pragma warning disable 0108, 0219, 0414, 1591 namespace Com.Raritan.Idl.sensors { public class NumericSensor_4_0_0 : Com.Raritan.Idl.sensors.Sensor_4_0_0 { static public readonly new TypeInfo typeInfo = new TypeInfo("sensors.NumericSensor:4.0.0", null); public NumericSensor_4_0_0(Agent agent, string rid, TypeInfo ti) : base(agent, rid, ti) {} public NumericSensor_4_0_0(Agent agent, string rid) : this(agent, rid, typeInfo) {} public static new NumericSensor_4_0_0 StaticCast(ObjectProxy proxy) { return proxy == null ? null : new NumericSensor_4_0_0(proxy.Agent, proxy.Rid, proxy.StaticTypeInfo); } public const int THRESHOLD_OUT_OF_RANGE = 1; public const int THRESHOLD_INVALID = 2; public const int THRESHOLD_NOT_SUPPORTED = 3; public class Range : ICloneable { public object Clone() { Range copy = new Range(); copy.lower = this.lower; copy.upper = this.upper; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["lower"] = this.lower; json["upper"] = this.upper; return json; } public static Range Decode(LightJson.JsonObject json, Agent agent) { Range inst = new Range(); inst.lower = (double)json["lower"]; inst.upper = (double)json["upper"]; return inst; } public double lower = 0.0; public double upper = 0.0; } public class ThresholdCapabilities : ICloneable { public object Clone() { ThresholdCapabilities copy = new ThresholdCapabilities(); copy.hasUpperCritical = this.hasUpperCritical; copy.hasUpperWarning = this.hasUpperWarning; copy.hasLowerWarning = this.hasLowerWarning; copy.hasLowerCritical = this.hasLowerCritical; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["hasUpperCritical"] = this.hasUpperCritical; json["hasUpperWarning"] = this.hasUpperWarning; json["hasLowerWarning"] = this.hasLowerWarning; json["hasLowerCritical"] = this.hasLowerCritical; return json; } public static ThresholdCapabilities Decode(LightJson.JsonObject json, Agent agent) { ThresholdCapabilities inst = new ThresholdCapabilities(); inst.hasUpperCritical = (bool)json["hasUpperCritical"]; inst.hasUpperWarning = (bool)json["hasUpperWarning"]; inst.hasLowerWarning = (bool)json["hasLowerWarning"]; inst.hasLowerCritical = (bool)json["hasLowerCritical"]; return inst; } public bool hasUpperCritical = false; public bool hasUpperWarning = false; public bool hasLowerWarning = false; public bool hasLowerCritical = false; } public class MetaData : ICloneable { public object Clone() { MetaData copy = new MetaData(); copy.type = this.type; copy.decdigits = this.decdigits; copy.accuracy = this.accuracy; copy.resolution = this.resolution; copy.tolerance = this.tolerance; copy.noiseThreshold = this.noiseThreshold; copy.range = this.range; copy.thresholdCaps = this.thresholdCaps; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["type"] = this.type.Encode(); json["decdigits"] = this.decdigits; json["accuracy"] = this.accuracy; json["resolution"] = this.resolution; json["tolerance"] = this.tolerance; json["noiseThreshold"] = this.noiseThreshold; json["range"] = this.range.Encode(); json["thresholdCaps"] = this.thresholdCaps.Encode(); return json; } public static MetaData Decode(LightJson.JsonObject json, Agent agent) { MetaData inst = new MetaData(); inst.type = Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpec.Decode(json["type"], agent); inst.decdigits = (int)json["decdigits"]; inst.accuracy = (float)json["accuracy"]; inst.resolution = (float)json["resolution"]; inst.tolerance = (float)json["tolerance"]; inst.noiseThreshold = (float)json["noiseThreshold"]; inst.range = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Range.Decode(json["range"], agent); inst.thresholdCaps = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.ThresholdCapabilities.Decode(json["thresholdCaps"], agent); return inst; } public Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpec type = new Com.Raritan.Idl.sensors.Sensor_4_0_0.TypeSpec(); public int decdigits = 0; public float accuracy = 0.0f; public float resolution = 0.0f; public float tolerance = 0.0f; public float noiseThreshold = 0.0f; public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Range range = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Range(); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.ThresholdCapabilities thresholdCaps = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.ThresholdCapabilities(); } public class Thresholds : ICloneable { public object Clone() { Thresholds copy = new Thresholds(); copy.upperCriticalActive = this.upperCriticalActive; copy.upperCritical = this.upperCritical; copy.upperWarningActive = this.upperWarningActive; copy.upperWarning = this.upperWarning; copy.lowerWarningActive = this.lowerWarningActive; copy.lowerWarning = this.lowerWarning; copy.lowerCriticalActive = this.lowerCriticalActive; copy.lowerCritical = this.lowerCritical; copy.assertionTimeout = this.assertionTimeout; copy.deassertionHysteresis = this.deassertionHysteresis; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["upperCriticalActive"] = this.upperCriticalActive; json["upperCritical"] = this.upperCritical; json["upperWarningActive"] = this.upperWarningActive; json["upperWarning"] = this.upperWarning; json["lowerWarningActive"] = this.lowerWarningActive; json["lowerWarning"] = this.lowerWarning; json["lowerCriticalActive"] = this.lowerCriticalActive; json["lowerCritical"] = this.lowerCritical; json["assertionTimeout"] = this.assertionTimeout; json["deassertionHysteresis"] = this.deassertionHysteresis; return json; } public static Thresholds Decode(LightJson.JsonObject json, Agent agent) { Thresholds inst = new Thresholds(); inst.upperCriticalActive = (bool)json["upperCriticalActive"]; inst.upperCritical = (double)json["upperCritical"]; inst.upperWarningActive = (bool)json["upperWarningActive"]; inst.upperWarning = (double)json["upperWarning"]; inst.lowerWarningActive = (bool)json["lowerWarningActive"]; inst.lowerWarning = (double)json["lowerWarning"]; inst.lowerCriticalActive = (bool)json["lowerCriticalActive"]; inst.lowerCritical = (double)json["lowerCritical"]; inst.assertionTimeout = (int)json["assertionTimeout"]; inst.deassertionHysteresis = (float)json["deassertionHysteresis"]; return inst; } public bool upperCriticalActive = false; public double upperCritical = 0.0; public bool upperWarningActive = false; public double upperWarning = 0.0; public bool lowerWarningActive = false; public double lowerWarning = 0.0; public bool lowerCriticalActive = false; public double lowerCritical = 0.0; public int assertionTimeout = 0; public float deassertionHysteresis = 0.0f; } public class Reading : ICloneable { public object Clone() { Reading copy = new Reading(); copy.timestamp = this.timestamp; copy.available = this.available; copy.status = this.status; copy.valid = this.valid; copy.value = this.value; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["timestamp"] = this.timestamp.Ticks; json["available"] = this.available; json["status"] = this.status.Encode(); json["valid"] = this.valid; json["value"] = this.value; return json; } public static Reading Decode(LightJson.JsonObject json, Agent agent) { Reading inst = new Reading(); inst.timestamp = new System.DateTime(json["timestamp"]); inst.available = (bool)json["available"]; inst.status = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading.Status.Decode(json["status"], agent); inst.valid = (bool)json["valid"]; inst.value = (double)json["value"]; return inst; } public class Status : ICloneable { public object Clone() { Status copy = new Status(); copy.aboveUpperCritical = this.aboveUpperCritical; copy.aboveUpperWarning = this.aboveUpperWarning; copy.belowLowerWarning = this.belowLowerWarning; copy.belowLowerCritical = this.belowLowerCritical; return copy; } public LightJson.JsonObject Encode() { LightJson.JsonObject json = new LightJson.JsonObject(); json["aboveUpperCritical"] = this.aboveUpperCritical; json["aboveUpperWarning"] = this.aboveUpperWarning; json["belowLowerWarning"] = this.belowLowerWarning; json["belowLowerCritical"] = this.belowLowerCritical; return json; } public static Status Decode(LightJson.JsonObject json, Agent agent) { Status inst = new Status(); inst.aboveUpperCritical = (bool)json["aboveUpperCritical"]; inst.aboveUpperWarning = (bool)json["aboveUpperWarning"]; inst.belowLowerWarning = (bool)json["belowLowerWarning"]; inst.belowLowerCritical = (bool)json["belowLowerCritical"]; return inst; } public bool aboveUpperCritical = false; public bool aboveUpperWarning = false; public bool belowLowerWarning = false; public bool belowLowerCritical = false; } public System.DateTime timestamp = new System.DateTime(0); public bool available = false; public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading.Status status = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading.Status(); public bool valid = false; public double value = 0.0; } public class ReadingChangedEvent : Com.Raritan.Idl.idl.Event { static public readonly new TypeInfo typeInfo = new TypeInfo("sensors.NumericSensor_4_0_0.ReadingChangedEvent:1.0.0", Com.Raritan.Idl.idl.Event.typeInfo); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading newReading = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading(); } public class StateChangedEvent : Com.Raritan.Idl.idl.Event { static public readonly new TypeInfo typeInfo = new TypeInfo("sensors.NumericSensor_4_0_0.StateChangedEvent:1.0.0", Com.Raritan.Idl.idl.Event.typeInfo); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading oldReading = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading(); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading newReading = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading(); } public class MetaDataChangedEvent : Com.Raritan.Idl.idl.Event { static public readonly new TypeInfo typeInfo = new TypeInfo("sensors.NumericSensor_4_0_0.MetaDataChangedEvent:1.0.0", Com.Raritan.Idl.idl.Event.typeInfo); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData oldMetaData = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData(); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData newMetaData = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData(); } public class ThresholdsChangedEvent : Com.Raritan.Idl._event.UserEvent { static public readonly new TypeInfo typeInfo = new TypeInfo("sensors.NumericSensor_4_0_0.ThresholdsChangedEvent:1.0.0", Com.Raritan.Idl._event.UserEvent.typeInfo); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds oldThresholds = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds(); public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds newThresholds = new Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds(); } public class GetMetaDataResult { public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData _ret_; } public GetMetaDataResult getMetaData() { JsonObject _parameters = null; var _result = RpcCall("getMetaData", _parameters); var _ret = new GetMetaDataResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData.Decode(_result["_ret_"], agent); return _ret; } public AsyncRequest getMetaData(AsyncRpcResponse<GetMetaDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) { return getMetaData(rsp, fail, RpcCtrl.Default); } public AsyncRequest getMetaData(AsyncRpcResponse<GetMetaDataResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) { JsonObject _parameters = null; return RpcCall("getMetaData", _parameters, _result => { try { var _ret = new GetMetaDataResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.MetaData.Decode(_result["_ret_"], agent); rsp(_ret); } catch (Exception e) { if (fail != null) fail(e); } }, fail, rpcCtrl); } public class GetDefaultThresholdsResult { public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds _ret_; } public GetDefaultThresholdsResult getDefaultThresholds() { JsonObject _parameters = null; var _result = RpcCall("getDefaultThresholds", _parameters); var _ret = new GetDefaultThresholdsResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds.Decode(_result["_ret_"], agent); return _ret; } public AsyncRequest getDefaultThresholds(AsyncRpcResponse<GetDefaultThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) { return getDefaultThresholds(rsp, fail, RpcCtrl.Default); } public AsyncRequest getDefaultThresholds(AsyncRpcResponse<GetDefaultThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) { JsonObject _parameters = null; return RpcCall("getDefaultThresholds", _parameters, _result => { try { var _ret = new GetDefaultThresholdsResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds.Decode(_result["_ret_"], agent); rsp(_ret); } catch (Exception e) { if (fail != null) fail(e); } }, fail, rpcCtrl); } public class GetThresholdsResult { public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds _ret_; } public GetThresholdsResult getThresholds() { JsonObject _parameters = null; var _result = RpcCall("getThresholds", _parameters); var _ret = new GetThresholdsResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds.Decode(_result["_ret_"], agent); return _ret; } public AsyncRequest getThresholds(AsyncRpcResponse<GetThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) { return getThresholds(rsp, fail, RpcCtrl.Default); } public AsyncRequest getThresholds(AsyncRpcResponse<GetThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) { JsonObject _parameters = null; return RpcCall("getThresholds", _parameters, _result => { try { var _ret = new GetThresholdsResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds.Decode(_result["_ret_"], agent); rsp(_ret); } catch (Exception e) { if (fail != null) fail(e); } }, fail, rpcCtrl); } public class SetThresholdsResult { public int _ret_; } public SetThresholdsResult setThresholds(Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds thresh) { var _parameters = new LightJson.JsonObject(); _parameters["thresh"] = thresh.Encode(); var _result = RpcCall("setThresholds", _parameters); var _ret = new SetThresholdsResult(); _ret._ret_ = (int)_result["_ret_"]; return _ret; } public AsyncRequest setThresholds(Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds thresh, AsyncRpcResponse<SetThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) { return setThresholds(thresh, rsp, fail, RpcCtrl.Default); } public AsyncRequest setThresholds(Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Thresholds thresh, AsyncRpcResponse<SetThresholdsResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) { var _parameters = new LightJson.JsonObject(); try { _parameters["thresh"] = thresh.Encode(); } catch (Exception e) { if (fail != null) fail(e); } return RpcCall("setThresholds", _parameters, _result => { try { var _ret = new SetThresholdsResult(); _ret._ret_ = (int)_result["_ret_"]; rsp(_ret); } catch (Exception e) { if (fail != null) fail(e); } }, fail, rpcCtrl); } public class GetReadingResult { public Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading _ret_; } public GetReadingResult getReading() { JsonObject _parameters = null; var _result = RpcCall("getReading", _parameters); var _ret = new GetReadingResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading.Decode(_result["_ret_"], agent); return _ret; } public AsyncRequest getReading(AsyncRpcResponse<GetReadingResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail) { return getReading(rsp, fail, RpcCtrl.Default); } public AsyncRequest getReading(AsyncRpcResponse<GetReadingResult>.SuccessHandler rsp, AsyncRpcResponse.FailureHandler fail, RpcCtrl rpcCtrl) { JsonObject _parameters = null; return RpcCall("getReading", _parameters, _result => { try { var _ret = new GetReadingResult(); _ret._ret_ = Com.Raritan.Idl.sensors.NumericSensor_4_0_0.Reading.Decode(_result["_ret_"], agent); rsp(_ret); } catch (Exception e) { if (fail != null) fail(e); } }, fail, rpcCtrl); } } }
41.928416
215
0.680377
[ "BSD-3-Clause" ]
gregoa/raritan-pdu-json-rpc-sdk
pdu-dotnet-api/_idlc_gen/dotnet/Com/Raritan/Idl/sensors/NumericSensor_4_0_0.cs
19,329
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Serialization; using NewLife; using NewLife.Data; using NewLife.Log; using NewLife.Model; using NewLife.Reflection; using NewLife.Threading; using NewLife.Web; using XCode; using XCode.Cache; using XCode.Configuration; using XCode.DataAccessLayer; using XCode.Membership; namespace COMCMS.Core { /// <summary>商家</summary> public partial class Shop : Entity<Shop> { #region 对象操作 static Shop() { // 累加字段 //var df = Meta.Factory.AdditionalFields; //df.Add(__.KId); // 过滤器 UserModule、TimeModule、IPModule } /// <summary>验证数据,通过抛出异常的方式提示验证失败。</summary> /// <param name="isNew">是否插入</param> public override void Valid(Boolean isNew) { // 如果没有脏数据,则不需要进行任何处理 if (!HasDirty) return; // 在新插入数据或者修改了指定字段时进行修正 // 货币保留6位小数 Latitude = Math.Round(Latitude, 6); Longitude = Math.Round(Longitude, 6); Balance = Math.Round(Balance, 6); AvgScore = Math.Round(AvgScore, 6); ServiceScore = Math.Round(ServiceScore, 6); SpeedScore = Math.Round(SpeedScore, 6); EnvironmentScore = Math.Round(EnvironmentScore, 6); DefaultFare = Math.Round(DefaultFare, 6); MaxFreeFare = Math.Round(MaxFreeFare, 6); } ///// <summary>首次连接数据库时初始化数据,仅用于实体类重载,用户不应该调用该方法</summary> //[EditorBrowsable(EditorBrowsableState.Never)] //protected override void InitData() //{ // // InitData一般用于当数据表没有数据时添加一些默认数据,该实体类的任何第一次数据库操作都会触发该方法,默认异步调用 // if (Meta.Session.Count > 0) return; // if (XTrace.Debug) XTrace.WriteLine("开始初始化Shop[商家]数据……"); // var entity = new Shop(); // entity.Id = 0; // entity.ShopName = "abc"; // entity.KId = 0; // entity.AId = 0; // entity.Sequence = 0; // entity.Latitude = 0.0; // entity.Longitude = 0.0; // entity.Country = "abc"; // entity.Province = "abc"; // entity.City = "abc"; // entity.District = "abc"; // entity.Address = "abc"; // entity.Postcode = "abc"; // entity.IsDel = 0; // entity.IsHide = 0; // entity.IsDisabled = 0; // entity.Content = "abc"; // entity.Keyword = "abc"; // entity.Description = "abc"; // entity.BannerImg = "abc"; // entity.Balance = 0.0; // entity.IsTop = 0; // entity.IsVip = 0; // entity.IsRecommend = 0; // entity.Likes = 0; // entity.AvgScore = 0.0; // entity.ServiceScore = 0.0; // entity.SpeedScore = 0.0; // entity.EnvironmentScore = 0.0; // entity.Pic = "abc"; // entity.MorePics = "abc"; // entity.Email = "abc"; // entity.Tel = "abc"; // entity.Phone = "abc"; // entity.Qq = "abc"; // entity.Skype = "abc"; // entity.HomePage = "abc"; // entity.Weixin = "abc"; // entity.IsShip = 0; // entity.OpenTime = DateTime.Now; // entity.CloseTime = DateTime.Now; // entity.ShippingStartTime = DateTime.Now; // entity.ShippingEndTime = DateTime.Now; // entity.AddTime = DateTime.Now; // entity.Hits = 0; // entity.MyType = 0; // entity.DefaultFare = 0.0; // entity.MaxFreeFare = 0.0; // entity.Insert(); // if (XTrace.Debug) XTrace.WriteLine("完成初始化Shop[商家]数据!"); //} ///// <summary>已重载。基类先调用Valid(true)验证数据,然后在事务保护内调用OnInsert</summary> ///// <returns></returns> //public override Int32 Insert() //{ // return base.Insert(); //} ///// <summary>已重载。在事务保护范围内处理业务,位于Valid之后</summary> ///// <returns></returns> //protected override Int32 OnDelete() //{ // return base.OnDelete(); //} #endregion #region 扩展属性 #endregion #region 扩展查询 /// <summary>根据编号查找</summary> /// <param name="id">编号</param> /// <returns>实体对象</returns> public static Shop FindById(Int32 id) { if (id <= 0) return null; // 实体缓存 if (Meta.Session.Count < 1000) return Meta.Cache.Find(e => e.Id == id); // 单对象缓存 return Meta.SingleCache[id]; //return Find(_.Id == id); } #endregion #region 高级查询 #endregion #region 业务操作 #endregion } }
30.243902
83
0.520565
[ "MIT" ]
NewLifeX/comcms
XCoder/Entity/商家.Biz.cs
5,504
C#
using System; using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; namespace Umbraco.Core.PropertyEditors.ValueConverters { /// <summary> /// The upload property value converter. /// </summary> [DefaultPropertyValueConverter] [PropertyValueType(typeof(string))] [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] public class UploadPropertyConverter : PropertyValueConverterBase { /// <summary> /// Checks if this converter can convert the property editor and registers if it can. /// </summary> /// <param name="propertyType"> /// The published property type. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public override bool IsConverter(PublishedPropertyType propertyType) { if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters) { return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.UploadFieldAlias); } return false; } /// <summary> /// Convert the source object to a string /// </summary> /// <param name="propertyType"> /// The published property type. /// </param> /// <param name="source"> /// The value of the property /// </param> /// <param name="preview"> /// The preview. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { return (source ?? "").ToString(); } } }
32.964912
117
0.600852
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Core/PropertyEditors/ValueConverters/UploadPropertyConverter.cs
1,881
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class State<T> { public Action OnEnter { get; protected set; } public Func<T> OnStay { get; protected set; } public Action OnLeave { get; protected set; } public T Name { get; protected set; } public State(T name, Action onEnter, Func<T> onStay, Action onLeave) { Name = name; OnEnter = onEnter; OnStay = onStay; OnLeave = onLeave; } }
22.791667
73
0.619744
[ "MIT" ]
182719/Bachelor-Oppgave
BachelorScene/Assets/Scripts/State.cs
549
C#
// 283. Move Zeroes Easy // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. // Example: // Input: [0,1,0,3,12] // Output: [1,3,12,0,0] // Note: // You must do this in-place without making a copy of the array. // Minimize the total number of operations. using System; namespace LeetCode{ public partial class MoveZero{ /// <summary> /// 将数组中0元素移至末尾,要求不允许复制数组,最小化移动,还要保持非0元素的相对位置 /// 0 1 0 3 12 1 0 0 3 0 12 1 0 0 3 0 12 /// 12 1 0 3 0 1 0 0 3 0 12 1 3 0 0 0 12 /// 1 12 0 3 0 1 3 0 0 12 /// 1 12 3 0 0 1 3 12 0 0 /// 1 3 12 0 0 /// Runtime: 264 ms /// Memory Usage: 29.8 MB /// </summary> /// <param name="nums"></param> public void MoveZeroes(int[] nums) { int startZero = 0; int zeroLen = 0; for (var i = 0; i < nums.Length;i++){ if(startZero+zeroLen==nums.Length) return; if(nums[i]==0){ if(zeroLen==0){ startZero = i; } zeroLen++; continue; } if(zeroLen>0){ nums[startZero] = nums[i]; nums[i] = 0; startZero++; } } } /// <summary> /// 更好看的解决方案,然而测试结果和上面的差不多。。。 /// https://leetcode.com/problems/move-zeroes/discuss/72379/C-easy-move-O(n) /// Runtime: 268 ms /// Memory Usage: 29.8 MB /// </summary> /// <param name="nums"></param> public void MoveZeroes_2(int[] nums){ if(nums==null || nums.Length==0) return; int startZero = 0; for (var i = 0; i < nums.Length;i++){ if(nums[i]!=0){ if(startZero!=i){ nums[startZero] = nums[i]; nums[i] = 0; } startZero++; } } } } }
30.857143
136
0.431019
[ "MIT" ]
Yqdbbh/LeetCode
Src/src/Array/MoveZeroes.cs
2,288
C#
using System; using FluentAssertions; using Xunit; namespace KubeOps.Templates.Test.Templates; [Collection("Template Tests")] public class OperatorCSharpTest : IDisposable { private readonly TemplateExecutor _executor = new(); public OperatorCSharpTest(TemplateInstaller _) { } [Fact] public void Should_Create_Correct_Files() { _executor.ExecuteCSharpTemplate("operator"); _executor.FileExists("Template.csproj").Should().BeTrue(); _executor.FileExists("Startup.cs").Should().BeTrue(); _executor.FileExists("Program.cs").Should().BeTrue(); _executor.FileExists("appsettings.Development.json").Should().BeTrue(); _executor.FileExists("appsettings.json").Should().BeTrue(); _executor.FileExists("Controller", "DemoController.cs").Should().BeTrue(); _executor.FileExists("Entities", "V1DemoEntity.cs").Should().BeTrue(); _executor.FileExists("Finalizer", "DemoFinalizer.cs").Should().BeTrue(); _executor.FileExists("Webhooks", "DemoValidator.cs").Should().BeTrue(); _executor.FileExists("Webhooks", "DemoMutator.cs").Should().BeTrue(); } [Fact] public void Should_Add_KubeOps_Reference() { _executor.ExecuteCSharpTemplate("operator"); _executor.FileContains(@"PackageReference Include=""KubeOps""", "Template.csproj").Should().BeTrue(); } [Fact] public void Should_Add_KubeOps_Reference_Into_Startup_Files() { _executor.ExecuteCSharpTemplate("operator"); _executor.FileContains("services.AddKubernetesOperator();", "Startup.cs").Should().BeTrue(); _executor.FileContains("app.UseKubernetesOperator();", "Startup.cs").Should().BeTrue(); } [Fact] public void Should_Create_Correct_Program_Code() { _executor.ExecuteCSharpTemplate("operator"); _executor.FileContains("await CreateHostBuilder(args).Build().RunOperatorAsync(args);", "Program.cs") .Should() .BeTrue(); } [Fact] public void Should_Add_Correct_Demo_Files() { _executor.ExecuteCSharpTemplate("operator"); _executor.FileContains( "public class V1DemoEntity : CustomKubernetesEntity<V1DemoEntity.V1DemoEntitySpec, V1DemoEntity.V1DemoEntityStatus>", "Entities", "V1DemoEntity.cs") .Should() .BeTrue(); _executor.FileContains( "public class DemoController : IResourceController<V1DemoEntity>", "Controller", "DemoController.cs") .Should() .BeTrue(); _executor.FileContains( "public class DemoFinalizer : IResourceFinalizer<V1DemoEntity>", "Finalizer", "DemoFinalizer.cs") .Should() .BeTrue(); _executor.FileContains( "public class DemoValidator : IValidationWebhook<V1DemoEntity>", "Webhooks", "DemoValidator.cs") .Should() .BeTrue(); _executor.FileContains( "public class DemoMutator : IMutationWebhook<V1DemoEntity>", "Webhooks", "DemoMutator.cs") .Should() .BeTrue(); } public void Dispose() { _executor.Dispose(); } }
34.121212
133
0.618709
[ "Apache-2.0" ]
hypnopotamus/dotnet-operator-sdk
tests/KubeOps.Templates.Test/Templates/Operator.CSharp.Test.cs
3,378
C#
// ReSharper disable once CheckNamespace namespace Fluent { using System; /// <summary> /// Represents the result of <see cref="IKeyTipedControl.OnKeyTipPressed"/>. /// </summary> public class KeyTipPressedResult : EventArgs { /// <summary> /// An empty default instance. /// </summary> public static new readonly KeyTipPressedResult Empty = new KeyTipPressedResult(); private KeyTipPressedResult() { } /// <summary> /// Creates a new instance. /// </summary> /// <param name="pressedElementAquiredFocus">Defines if the pressed element aquired focus or not.</param> /// <param name="pressedElementOpenedPopup">Defines if the pressed element opened a popup or not.</param> public KeyTipPressedResult(bool pressedElementAquiredFocus, bool pressedElementOpenedPopup) { this.PressedElementAquiredFocus = pressedElementAquiredFocus; this.PressedElementOpenedPopup = pressedElementOpenedPopup; } /// <summary> /// Defines if the pressed element aquired focus or not. /// </summary> public bool PressedElementAquiredFocus { get; } /// <summary> /// Defines if the pressed element opened a popup or not. /// </summary> public bool PressedElementOpenedPopup { get; } } }
34.219512
113
0.631504
[ "MIT" ]
DevTown/Fluent.Ribbon
Fluent.Ribbon/Data/KeyTipPressedResult.cs
1,405
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use 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 OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 CONTRIBUTORS 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 log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Services.Connectors.Simulation; using OpenSim.Services.Interfaces; using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services.Connectors.Hypergrid { public class UserAgentServiceConnector : SimulationServiceConnector, IUserAgentService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURLHost; private string m_ServerURL; private GridRegion m_Gatekeeper; public UserAgentServiceConnector(string url) : this(url, true) { } public UserAgentServiceConnector(string url, bool dnsLookup) { m_ServerURL = m_ServerURLHost = url; if (dnsLookup) { // Doing this here, because XML-RPC or mono have some strong ideas about // caching DNS translations. try { Uri m_Uri = new Uri(m_ServerURL); IPAddress ip = Util.GetHostFromDNS(m_Uri.Host); m_ServerURL = m_ServerURL.Replace(m_Uri.Host, ip.ToString()); if (!m_ServerURL.EndsWith("/")) m_ServerURL += "/"; } catch (Exception e) { m_log.DebugFormat("[USER AGENT CONNECTOR]: Malformed Uri {0}: {1}", url, e.Message); } } //m_log.DebugFormat("[USER AGENT CONNECTOR]: new connector to {0} ({1})", url, m_ServerURL); } public UserAgentServiceConnector(IConfigSource config) { IConfig serviceConfig = config.Configs["UserAgentService"]; if (serviceConfig == null) { m_log.Error("[USER AGENT CONNECTOR]: UserAgentService missing from ini"); throw new Exception("UserAgent connector init error"); } string serviceURI = serviceConfig.GetString("UserAgentServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[USER AGENT CONNECTOR]: No Server URI named in section UserAgentService"); throw new Exception("UserAgent connector init error"); } m_ServerURL = m_ServerURLHost = serviceURI; if (!m_ServerURL.EndsWith("/")) m_ServerURL += "/"; //m_log.DebugFormat("[USER AGENT CONNECTOR]: new connector to {0}", m_ServerURL); } protected override string AgentPath() { return "homeagent/"; } // The Login service calls this interface with fromLogin=true // Sims call it with fromLogin=false // Either way, this is verified by the handler public bool LoginAgentToGrid(GridRegion source, AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, bool fromLogin, out string reason) { reason = String.Empty; if (destination == null) { reason = "Destination is null"; m_log.Debug("[USER AGENT CONNECTOR]: Given destination is null"); return false; } GridRegion home = new GridRegion(); home.ServerURI = m_ServerURL; home.RegionID = destination.RegionID; home.RegionLocX = destination.RegionLocX; home.RegionLocY = destination.RegionLocY; m_Gatekeeper = gatekeeper; Console.WriteLine(" >>> LoginAgentToGrid <<< " + home.ServerURI); uint flags = fromLogin ? (uint)TeleportFlags.ViaLogin : (uint)TeleportFlags.ViaHome; return CreateAgent(source, home, aCircuit, flags, out reason); } // The simulators call this interface public bool LoginAgentToGrid(GridRegion source, AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, out string reason) { return LoginAgentToGrid(source, aCircuit, gatekeeper, destination, false, out reason); } protected override void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags) { base.PackData(args, source, aCircuit, destination, flags); args["gatekeeper_serveruri"] = OSD.FromString(m_Gatekeeper.ServerURI); args["gatekeeper_host"] = OSD.FromString(m_Gatekeeper.ExternalHostName); args["gatekeeper_port"] = OSD.FromString(m_Gatekeeper.HttpPort.ToString()); args["destination_serveruri"] = OSD.FromString(destination.ServerURI); } public void SetClientToken(UUID sessionID, string token) { // no-op } private Hashtable CallServer(string methodName, Hashtable hash) { IList paramList = new ArrayList(); paramList.Add(hash); ServicePointManagerTimeoutSupport.ResetHosts(); XmlRpcRequest request = new XmlRpcRequest(methodName, paramList); // Send and get reply XmlRpcResponse response = null; try { response = request.Send(m_ServerURL, 10000); } catch (Exception e) { m_log.DebugFormat("[USER AGENT CONNECTOR]: {0} call to {1} failed: {2}", methodName, m_ServerURLHost, e.Message); throw; } if (response.IsFault) { throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned an error: {2}", methodName, m_ServerURLHost, response.FaultString)); } hash = (Hashtable)response.Value; if (hash == null) { throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned null", methodName, m_ServerURLHost)); } return hash; } public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt) { position = Vector3.UnitY; lookAt = Vector3.UnitY; Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash = CallServer("get_home_region", hash); bool success; if (!Boolean.TryParse((string)hash["result"], out success) || !success) return null; GridRegion region = new GridRegion(); UUID.TryParse((string)hash["uuid"], out region.RegionID); //m_log.Debug(">> HERE, uuid: " + region.RegionID); int n = 0; if (hash["x"] != null) { Int32.TryParse((string)hash["x"], out n); region.RegionLocX = n; //m_log.Debug(">> HERE, x: " + region.RegionLocX); } if (hash["y"] != null) { Int32.TryParse((string)hash["y"], out n); region.RegionLocY = n; //m_log.Debug(">> HERE, y: " + region.RegionLocY); } if (hash["size_x"] != null) { Int32.TryParse((string)hash["size_x"], out n); region.RegionSizeX = n; //m_log.Debug(">> HERE, x: " + region.RegionLocX); } if (hash["size_y"] != null) { Int32.TryParse((string)hash["size_y"], out n); region.RegionSizeY = n; //m_log.Debug(">> HERE, y: " + region.RegionLocY); } if (hash["region_name"] != null) { region.RegionName = (string)hash["region_name"]; //m_log.Debug(">> HERE, name: " + region.RegionName); } if (hash["hostname"] != null) region.ExternalHostName = (string)hash["hostname"]; if (hash["http_port"] != null) { uint p = 0; UInt32.TryParse((string)hash["http_port"], out p); region.HttpPort = p; } if (hash.ContainsKey("server_uri") && hash["server_uri"] != null) region.ServerURI = (string)hash["server_uri"]; if (hash["internal_port"] != null) { int p = 0; Int32.TryParse((string)hash["internal_port"], out p); region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p); } if (hash["position"] != null) Vector3.TryParse((string)hash["position"], out position); if (hash["lookAt"] != null) Vector3.TryParse((string)hash["lookAt"], out lookAt); // Successful return return region; } public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName) { Hashtable hash = new Hashtable(); hash["sessionID"] = sessionID.ToString(); hash["externalName"] = thisGridExternalName; IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("agent_is_coming_home", paramList); string reason = string.Empty; return GetBoolResponse(request, out reason); } public bool VerifyAgent(UUID sessionID, string token) { Hashtable hash = new Hashtable(); hash["sessionID"] = sessionID.ToString(); hash["token"] = token; IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("verify_agent", paramList); string reason = string.Empty; return GetBoolResponse(request, out reason); } public bool VerifyClient(UUID sessionID, string token) { Hashtable hash = new Hashtable(); hash["sessionID"] = sessionID.ToString(); hash["token"] = token; IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("verify_client", paramList); string reason = string.Empty; return GetBoolResponse(request, out reason); } public void LogoutAgent(UUID userID, UUID sessionID) { Hashtable hash = new Hashtable(); hash["sessionID"] = sessionID.ToString(); hash["userID"] = userID.ToString(); IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("logout_agent", paramList); string reason = string.Empty; GetBoolResponse(request, out reason); } public List<UUID> StatusNotification(List<string> friends, UUID userID, bool online) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash["online"] = online.ToString(); int i = 0; foreach (string s in friends) { hash["friend_" + i.ToString()] = s; i++; } IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("status_notification", paramList); // string reason = string.Empty; // Send and get reply List<UUID> friendsOnline = new List<UUID>(); XmlRpcResponse response = null; try { response = request.Send(m_ServerURL, 6000); } catch { m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for StatusNotification", m_ServerURLHost); // reason = "Exception: " + e.Message; return friendsOnline; } if (response.IsFault) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for StatusNotification returned an error: {1}", m_ServerURLHost, response.FaultString); // reason = "XMLRPC Fault"; return friendsOnline; } hash = (Hashtable)response.Value; //foreach (Object o in hash) // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value); try { if (hash == null) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: GetOnlineFriends Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost); // reason = "Internal error 1"; return friendsOnline; } // Here is the actual response foreach (object key in hash.Keys) { if (key is string && ((string)key).StartsWith("friend_") && hash[key] != null) { UUID uuid; if (UUID.TryParse(hash[key].ToString(), out uuid)) friendsOnline.Add(uuid); } } } catch { m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetOnlineFriends response."); // reason = "Exception: " + e.Message; } return friendsOnline; } [Obsolete] public List<UUID> GetOnlineFriends(UUID userID, List<string> friends) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); int i = 0; foreach (string s in friends) { hash["friend_" + i.ToString()] = s; i++; } IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("get_online_friends", paramList); // string reason = string.Empty; // Send and get reply List<UUID> online = new List<UUID>(); XmlRpcResponse response = null; try { response = request.Send(m_ServerURL, 10000); } catch { m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for GetOnlineFriends", m_ServerURLHost); // reason = "Exception: " + e.Message; return online; } if (response.IsFault) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for GetOnlineFriends returned an error: {1}", m_ServerURLHost, response.FaultString); // reason = "XMLRPC Fault"; return online; } hash = (Hashtable)response.Value; //foreach (Object o in hash) // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value); try { if (hash == null) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: GetOnlineFriends Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost); // reason = "Internal error 1"; return online; } // Here is the actual response foreach (object key in hash.Keys) { if (key is string && ((string)key).StartsWith("friend_") && hash[key] != null) { UUID uuid; if (UUID.TryParse(hash[key].ToString(), out uuid)) online.Add(uuid); } } } catch { m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetOnlineFriends response."); // reason = "Exception: " + e.Message; } return online; } public Dictionary<string,object> GetUserInfo (UUID userID) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash = CallServer("get_user_info", hash); Dictionary<string, object> info = new Dictionary<string, object>(); foreach (object key in hash.Keys) { if (hash[key] != null) { info.Add(key.ToString(), hash[key]); } } return info; } public Dictionary<string, object> GetServerURLs(UUID userID) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash = CallServer("get_server_urls", hash); Dictionary<string, object> serverURLs = new Dictionary<string, object>(); foreach (object key in hash.Keys) { if (key is string && ((string)key).StartsWith("SRV_") && hash[key] != null) { string serverType = key.ToString().Substring(4); // remove "SRV_" serverURLs.Add(serverType, hash[key].ToString()); } } return serverURLs; } public string LocateUser(UUID userID) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash = CallServer("locate_user", hash); string url = string.Empty; // Here's the actual response if (hash.ContainsKey("URL")) url = hash["URL"].ToString(); return url; } public string GetUUI(UUID userID, UUID targetUserID) { Hashtable hash = new Hashtable(); hash["userID"] = userID.ToString(); hash["targetUserID"] = targetUserID.ToString(); hash = CallServer("get_uui", hash); string uui = string.Empty; // Here's the actual response if (hash.ContainsKey("UUI")) uui = hash["UUI"].ToString(); return uui; } public UUID GetUUID(String first, String last) { Hashtable hash = new Hashtable(); hash["first"] = first; hash["last"] = last; hash = CallServer("get_uuid", hash); if (!hash.ContainsKey("UUID")) { throw new Exception(string.Format("[USER AGENT CONNECTOR]: get_uuid call to {0} didn't return a UUID", m_ServerURLHost)); } UUID uuid; if (!UUID.TryParse(hash["UUID"].ToString(), out uuid)) { throw new Exception(string.Format("[USER AGENT CONNECTOR]: get_uuid call to {0} returned an invalid UUID: {1}", m_ServerURLHost, hash["UUID"].ToString())); } return uuid; } private bool GetBoolResponse(XmlRpcRequest request, out string reason) { //m_log.Debug("[USER AGENT CONNECTOR]: GetBoolResponse from/to " + m_ServerURLHost); XmlRpcResponse response = null; try { response = request.Send(m_ServerURL, 10000); } catch (Exception e) { m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0} for GetBoolResponse", m_ServerURLHost); reason = "Exception: " + e.Message; return false; } if (response.IsFault) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} for GetBoolResponse returned an error: {1}", m_ServerURLHost, response.FaultString); reason = "XMLRPC Fault"; return false; } Hashtable hash = (Hashtable)response.Value; //foreach (Object o in hash) // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value); try { if (hash == null) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got null response from {0}! THIS IS BAAAAD", m_ServerURLHost); reason = "Internal error 1"; return false; } bool success = false; reason = string.Empty; if (hash.ContainsKey("result")) Boolean.TryParse((string)hash["result"], out success); else { reason = "Internal error 2"; m_log.WarnFormat("[USER AGENT CONNECTOR]: response from {0} does not have expected key 'result'", m_ServerURLHost); } return success; } catch (Exception e) { m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetBoolResponse response."); if (hash.ContainsKey("result") && hash["result"] != null) m_log.ErrorFormat("Reply was ", (string)hash["result"]); reason = "Exception: " + e.Message; return false; } } } }
37.301282
171
0.537163
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Services/Connectors/Hypergrid/UserAgentServiceConnector.cs
23,276
C#
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Text; #region using languages using Microshaoft.UtfUnknown.Core.Models.SingleByte.Arabic; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Bulgarian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Croatian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Czech; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Danish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Esperanto; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Estonian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Finnish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.French; using Microshaoft.UtfUnknown.Core.Models.SingleByte.German; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Greek; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Hebrew; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Hungarian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Irish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Italian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Latvian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Lithuanian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Maltese; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Polish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Portuguese; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Romanian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Russian; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Slovak; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Slovene; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Spanish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Swedish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Thai; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Turkish; using Microshaoft.UtfUnknown.Core.Models.SingleByte.Vietnamese; #endregion using languages namespace Microshaoft.UtfUnknown.Core.Probers { public class SBCSGroupProber : CharsetProber { private const int PROBERS_NUM = 100; private CharsetProber[] probers = new CharsetProber[PROBERS_NUM]; private bool[] isActive = new bool[PROBERS_NUM]; private int bestGuess; private int activeNum; public SBCSGroupProber() { // Russian probers[0] = new SingleByteCharSetProber(new Windows_1251_RussianModel()); probers[1] = new SingleByteCharSetProber(new Koi8r_Model()); probers[2] = new SingleByteCharSetProber(new Iso_8859_5_RussianModel()); probers[3] = new SingleByteCharSetProber(new X_Mac_Cyrillic_RussianModel()); probers[4] = new SingleByteCharSetProber(new Ibm866_RussianModel()); probers[5] = new SingleByteCharSetProber(new Ibm855_RussianModel()); // Greek probers[6] = new SingleByteCharSetProber(new Iso_8859_7_GreekModel()); probers[7] = new SingleByteCharSetProber(new Windows_1253_GreekModel()); // Bulgarian probers[8] = new SingleByteCharSetProber(new Iso_8859_5_BulgarianModel()); probers[9] = new SingleByteCharSetProber(new Windows_1251_BulgarianModel()); // Hebrew HebrewProber hebprober = new HebrewProber(); probers[10] = hebprober; // Logical probers[11] = new SingleByteCharSetProber(new Windows_1255_HebrewModel(), false, hebprober); // Visual probers[12] = new SingleByteCharSetProber(new Windows_1255_HebrewModel(), true, hebprober); hebprober.SetModelProbers(probers[11], probers[12]); // Thai probers[13] = new SingleByteCharSetProber(new Tis_620_ThaiModel()); probers[14] = new SingleByteCharSetProber(new Iso_8859_11_ThaiModel()); // French probers[15] = new SingleByteCharSetProber(new Iso_8859_1_FrenchModel()); probers[16] = new SingleByteCharSetProber(new Iso_8859_15_FrenchModel()); probers[17] = new SingleByteCharSetProber(new Windows_1252_FrenchModel()); // Spanish probers[18] = new SingleByteCharSetProber(new Iso_8859_1_SpanishModel()); probers[19] = new SingleByteCharSetProber(new Iso_8859_15_SpanishModel()); probers[20] = new SingleByteCharSetProber(new Windows_1252_SpanishModel()); // Is the following still valid? // disable latin2 before latin1 is available, otherwise all latin1 // will be detected as latin2 because of their similarity // Hungarian probers[21] = new SingleByteCharSetProber(new Iso_8859_2_HungarianModel()); probers[22] = new SingleByteCharSetProber(new Windows_1250_HungarianModel()); // German probers[23] = new SingleByteCharSetProber(new Iso_8859_1_GermanModel()); probers[24] = new SingleByteCharSetProber(new Windows_1252_GermanModel()); // Esperanto probers[25] = new SingleByteCharSetProber(new Iso_8859_3_EsperantoModel()); // Turkish probers[26] = new SingleByteCharSetProber(new Iso_8859_3_TurkishModel()); probers[27] = new SingleByteCharSetProber(new Iso_8859_9_TurkishModel()); // Arabic probers[28] = new SingleByteCharSetProber(new Iso_8859_6_ArabicModel()); probers[29] = new SingleByteCharSetProber(new Windows_1256_ArabicModel()); // Vietnamese probers[30] = new SingleByteCharSetProber(new Viscii_VietnameseModel()); probers[31] = new SingleByteCharSetProber(new Windows_1258_VietnameseModel()); // Danish probers[32] = new SingleByteCharSetProber(new Iso_8859_15_DanishModel()); probers[33] = new SingleByteCharSetProber(new Iso_8859_1_DanishModel()); probers[34] = new SingleByteCharSetProber(new Windows_1252_DanishModel()); // Lithuanian probers[35] = new SingleByteCharSetProber(new Iso_8859_13_LithuanianModel()); probers[36] = new SingleByteCharSetProber(new Iso_8859_10_LithuanianModel()); probers[37] = new SingleByteCharSetProber(new Iso_8859_4_LithuanianModel()); // Latvian probers[38] = new SingleByteCharSetProber(new Iso_8859_13_LatvianModel()); probers[39] = new SingleByteCharSetProber(new Iso_8859_10_LatvianModel()); probers[40] = new SingleByteCharSetProber(new Iso_8859_4_LatvianModel()); // Portuguese probers[41] = new SingleByteCharSetProber(new Iso_8859_1_PortugueseModel()); probers[42] = new SingleByteCharSetProber(new Iso_8859_9_PortugueseModel()); probers[43] = new SingleByteCharSetProber(new Iso_8859_15_PortugueseModel()); probers[44] = new SingleByteCharSetProber(new Windows_1252_PortugueseModel()); // Maltese probers[45] = new SingleByteCharSetProber(new Iso_8859_3_MalteseModel()); // Czech probers[46] = new SingleByteCharSetProber(new Windows_1250_CzechModel()); probers[47] = new SingleByteCharSetProber(new Iso_8859_2_CzechModel()); probers[48] = new SingleByteCharSetProber(new Mac_Centraleurope_CzechModel()); probers[49] = new SingleByteCharSetProber(new Ibm852_CzechModel()); // Slovak probers[50] = new SingleByteCharSetProber(new Windows_1250_SlovakModel()); probers[51] = new SingleByteCharSetProber(new Iso_8859_2_SlovakModel()); probers[52] = new SingleByteCharSetProber(new Mac_Centraleurope_SlovakModel()); probers[53] = new SingleByteCharSetProber(new Ibm852_SlovakModel()); // Polish probers[54] = new SingleByteCharSetProber(new Windows_1250_PolishModel()); probers[55] = new SingleByteCharSetProber(new Iso_8859_2_PolishModel()); probers[56] = new SingleByteCharSetProber(new Iso_8859_13_PolishModel()); probers[57] = new SingleByteCharSetProber(new Iso_8859_16_PolishModel()); probers[58] = new SingleByteCharSetProber(new Mac_Centraleurope_PolishModel()); probers[59] = new SingleByteCharSetProber(new Ibm852_PolishModel()); // Finnish probers[60] = new SingleByteCharSetProber(new Iso_8859_1_FinnishModel()); probers[61] = new SingleByteCharSetProber(new Iso_8859_4_FinnishModel()); probers[62] = new SingleByteCharSetProber(new Iso_8859_9_FinnishModel()); probers[63] = new SingleByteCharSetProber(new Iso_8859_13_FinnishModel()); probers[64] = new SingleByteCharSetProber(new Iso_8859_15_FinnishModel()); probers[65] = new SingleByteCharSetProber(new Windows_1252_FinnishModel()); // Italian probers[66] = new SingleByteCharSetProber(new Iso_8859_1_ItalianModel()); probers[67] = new SingleByteCharSetProber(new Iso_8859_3_ItalianModel()); probers[68] = new SingleByteCharSetProber(new Iso_8859_9_ItalianModel()); probers[69] = new SingleByteCharSetProber(new Iso_8859_15_ItalianModel()); probers[70] = new SingleByteCharSetProber(new Windows_1252_ItalianModel()); // Croatian probers[71] = new SingleByteCharSetProber(new Windows_1250_CroatianModel()); probers[72] = new SingleByteCharSetProber(new Iso_8859_2_CroatianModel()); probers[73] = new SingleByteCharSetProber(new Iso_8859_13_CroatianModel()); probers[74] = new SingleByteCharSetProber(new Iso_8859_16_CroatianModel()); probers[75] = new SingleByteCharSetProber(new Mac_Centraleurope_CroatianModel()); probers[76] = new SingleByteCharSetProber(new Ibm852_CroatianModel()); // Estonian probers[77] = new SingleByteCharSetProber(new Windows_1252_EstonianModel()); probers[78] = new SingleByteCharSetProber(new Windows_1257_EstonianModel()); probers[79] = new SingleByteCharSetProber(new Iso_8859_4_EstonianModel()); probers[80] = new SingleByteCharSetProber(new Iso_8859_13_EstonianModel()); probers[81] = new SingleByteCharSetProber(new Iso_8859_15_EstonianModel()); // Irish probers[82] = new SingleByteCharSetProber(new Iso_8859_1_IrishModel()); probers[83] = new SingleByteCharSetProber(new Iso_8859_9_IrishModel()); probers[84] = new SingleByteCharSetProber(new Iso_8859_15_IrishModel()); probers[85] = new SingleByteCharSetProber(new Windows_1252_IrishModel()); // Romanian probers[86] = new SingleByteCharSetProber(new Windows_1250_RomanianModel()); probers[87] = new SingleByteCharSetProber(new Iso_8859_2_RomanianModel()); probers[88] = new SingleByteCharSetProber(new Iso_8859_16_RomanianModel()); probers[89] = new SingleByteCharSetProber(new Ibm852_RomanianModel()); // Slovene probers[90] = new SingleByteCharSetProber(new Windows_1250_SloveneModel()); probers[91] = new SingleByteCharSetProber(new Iso_8859_2_SloveneModel()); probers[92] = new SingleByteCharSetProber(new Iso_8859_16_SloveneModel()); probers[93] = new SingleByteCharSetProber(new Mac_Centraleurope_SloveneModel()); probers[94] = new SingleByteCharSetProber(new Ibm852_SloveneModel()); // Swedish probers[95] = new SingleByteCharSetProber(new Iso_8859_1_SwedishModel()); probers[96] = new SingleByteCharSetProber(new Iso_8859_4_SwedishModel()); probers[97] = new SingleByteCharSetProber(new Iso_8859_9_SwedishModel()); probers[98] = new SingleByteCharSetProber(new Iso_8859_15_SwedishModel()); probers[99] = new SingleByteCharSetProber(new Windows_1252_SwedishModel()); Reset(); } public override ProbingState HandleData(byte[] buf, int offset, int len) { // apply filter to original buffer, and we got new buffer back // depend on what script it is, we will feed them the new buffer // we got after applying proper filter // this is done without any consideration to KeepEnglishLetters // of each prober since as of now, there are no probers here which // recognize languages with English characters. byte[] newBuf = FilterWithoutEnglishLetters(buf, offset, len); if (newBuf.Length == 0) return state; // Nothing to see here, move on. for (int i = 0; i < PROBERS_NUM; i++) { if (isActive[i]) { ProbingState st = probers[i].HandleData(newBuf, 0, newBuf.Length); if (st == ProbingState.FoundIt) { bestGuess = i; state = ProbingState.FoundIt; break; } else if (st == ProbingState.NotMe) { isActive[i] = false; activeNum--; if (activeNum <= 0) { state = ProbingState.NotMe; break; } } } } return state; } public override float GetConfidence(StringBuilder status = null) { float bestConf = 0.0f, cf; switch (state) { case ProbingState.FoundIt: return 0.99f; //sure yes case ProbingState.NotMe: return 0.01f; //sure no default: if (status != null) { status.AppendLine($"Get confidence:"); } for (int i = 0; i < PROBERS_NUM; i++) { if (isActive[i]) { cf = probers[i].GetConfidence(); if (bestConf < cf) { bestConf = cf; bestGuess = i; if (status != null) { status.AppendLine($"-- new match found: confidence {bestConf}, index {bestGuess}, charset {probers[i].GetCharsetName()}."); } } } } if (status != null) { status.AppendLine($"Get confidence done."); } break; } return bestConf; } public override string DumpStatus() { StringBuilder status = new StringBuilder(); float cf = GetConfidence(status); status.AppendLine(" SBCS Group Prober --------begin status"); for (int i = 0; i < PROBERS_NUM; i++) { if (probers[i] != null) { if (!isActive[i]) { status.AppendLine($" SBCS inactive: [{probers[i].GetCharsetName()}] (i.e. confidence is too low)."); } else { var cfp = probers[i].GetConfidence(); status.AppendLine($" SBCS {cfp}: [{probers[i].GetCharsetName()}]"); status.AppendLine(probers[i].DumpStatus()); } } } status.AppendLine($" SBCS Group found best match [{probers[bestGuess].GetCharsetName()}] confidence {cf}."); return status.ToString(); } public override void Reset() { activeNum = 0; for (int i = 0; i < PROBERS_NUM; i++) { if (probers[i] != null) { probers[i].Reset(); isActive[i] = true; ++activeNum; } else { isActive[i] = false; } } bestGuess = -1; state = ProbingState.Detecting; } public override string GetCharsetName() { //if we have no answer yet if (bestGuess == -1) { GetConfidence(); //no charset seems positive if (bestGuess == -1) bestGuess = 0; } return probers[bestGuess].GetCharsetName(); } } }
45.320482
159
0.619843
[ "MIT" ]
Microshaoft/Microshaoft.Common.Utilities.Net
SharedSources/Encoding/Ude/Core/Probers/SBCSGroupProber.cs
18,808
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(IErrorTag))] internal partial class DiagnosticsSuggestionTaggerProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { private static readonly IEnumerable<Option2<bool>> s_tagSourceOptions = ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles, ServiceComponentOnOffOptions.DiagnosticProvider); protected override IEnumerable<Option2<bool>> Options => s_tagSourceOptions; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public DiagnosticsSuggestionTaggerProvider( IThreadingContext threadingContext, IDiagnosticService diagnosticService, IForegroundNotificationService notificationService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, diagnosticService, notificationService, listenerProvider) { } protected internal override bool IncludeDiagnostic(DiagnosticData diagnostic) => diagnostic.Severity == DiagnosticSeverity.Info; protected override IErrorTag CreateTag(Workspace workspace, DiagnosticData diagnostic) => new ErrorTag( PredefinedErrorTypeNames.HintedSuggestion, CreateToolTipContent(workspace, diagnostic)); protected override SnapshotSpan AdjustSnapshotSpan(SnapshotSpan snapshotSpan, int minimumLength) { // We always want suggestion tags to be two characters long. return base.AdjustSnapshotSpan(snapshotSpan, minimumLength: 2, maximumLength: 2); } } }
45.83871
194
0.766362
[ "MIT" ]
Dean-ZhenYao-Wang/roslyn
src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs
2,844
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.Rds.Transform; using Aliyun.Acs.Rds.Transform.V20140815; namespace Aliyun.Acs.Rds.Model.V20140815 { public class ModifyDBInstanceTDERequest : RpcAcsRequest<ModifyDBInstanceTDEResponse> { public ModifyDBInstanceTDERequest() : base("Rds", "2014-08-15", "ModifyDBInstanceTDE", "rds", "openAPI") { } private long? resourceOwnerId; private string dBName; private string resourceOwnerAccount; private string roleArn; private string ownerAccount; private string dBInstanceId; private string encryptionKey; private long? ownerId; private string tDEStatus; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string DBName { get { return dBName; } set { dBName = value; DictionaryUtil.Add(QueryParameters, "DBName", value); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string RoleArn { get { return roleArn; } set { roleArn = value; DictionaryUtil.Add(QueryParameters, "RoleArn", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public string DBInstanceId { get { return dBInstanceId; } set { dBInstanceId = value; DictionaryUtil.Add(QueryParameters, "DBInstanceId", value); } } public string EncryptionKey { get { return encryptionKey; } set { encryptionKey = value; DictionaryUtil.Add(QueryParameters, "EncryptionKey", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string TDEStatus { get { return tDEStatus; } set { tDEStatus = value; DictionaryUtil.Add(QueryParameters, "TDEStatus", value); } } public override ModifyDBInstanceTDEResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ModifyDBInstanceTDEResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
20.449438
104
0.649176
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-rds/Rds/Model/V20140815/ModifyDBInstanceTDERequest.cs
3,640
C#
using System.Collections.Generic; using System.Reflection.Emit; using System.Linq; using HarmonyLib; namespace LifecycleRebalance { /// <summary> /// Harmony transpiler to remove 'vanishing corpse' check from ResidentAI.UpdateHealth and replace it with this mod's custom probabilities. /// </summary> [HarmonyPatch(typeof(ResidentAI))] [HarmonyPatch("UpdateHealth")] public static class UpdateHealthTranspiler { /// <summary> /// Harmony transpiler patching ResidentAI.UpdateHealth. /// </summary> /// <param name="instructions">CIL code to alter.</param> /// <returns>Patched CIL code</returns> public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { // The checks we're targeting for removal are fortunately clearly flagged by the call to Die(). // We're going to remove the immediately following: // (Singleton<SimulationManager>.instance.m_randomizer.Int32(2u) == 0); { Singleton<CitizenManager>.instance.ReleaseCitizen(citizenID); return true; } var codes = new List<CodeInstruction>(instructions); // Deal with each of the operands consecutively and independently to avoid risk of error. // Stores the number of operands to cut. int cutCount = 0; // Iterate through each opcode in the CIL, looking for a calls for (int i = 0; i < codes.Count; i++) { if (codes[i].opcode == OpCodes.Call && codes[i].operand == AccessTools.Method(typeof(ResidentAI), "Die")) { // Found call to ResidentAI.Die. // Increment i to start from the following instruction. i++; // Now, count forward from this operand until we encounter ldc.i4.2; that's the last instruction to be cut. while (codes[i + cutCount].opcode != OpCodes.Ldc_I4_2) { cutCount++; } // The following instruction is a call to ColossalFramework.Math.Randomizer; we keep the call and replace the operand with our own KeepCorpse method. codes[i + cutCount + 1].operand = AccessTools.Method(typeof(AIUtils), nameof(AIUtils.KeepCorpse)); Logging.Message("ResidentAI.Die transpiler removing CIL (offset", cutCount.ToString(), ") from ", i.ToString(), " (", codes[i].opcode.ToString(), " ", codes[i].operand.ToString(), " to ", codes[i + cutCount].opcode.ToString(), ")"); ; // Remove the CIL from the ldarg.0 to the throw (inclusive). // +1 to avoid fencepost error (need to include original instruction as well). codes.RemoveRange(i, cutCount + 1); // We're done with this one - no point in continuing the loop. break; } } return codes.AsEnumerable(); } } }
47.545455
255
0.582537
[ "Apache-2.0" ]
algernon-A/Lifecycle-Rebalance-Revisited
Code/Patches/UpdateHealthTranspiler.cs
3,140
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using Sce.Atf.Applications; using Sce.Atf.VectorMath; namespace Sce.Atf.Controls.Adaptable { /// <summary> /// OBSOLETE. Please use D2dGridAdapter instead. /// Adapter to draw a grid on the diagram and to perform layout constraints /// using that grid.</summary> public class GridAdapter : ControlAdapter, ILayoutConstraint { /// <summary> /// Gets or sets a value indicating if the grid is visible</summary> public bool Visible { get { return m_visible; } set { if (m_visible != value) { m_visible = value; Invalidate(); } } } /// <summary> /// Gets the grid's contrast with the control's back color; should be in [0..1]; /// default is 0.25.</summary> public float GridContrast { get { return m_gridContrast; } set { m_gridContrast = value; Invalidate(); } } /// <summary> /// Gets or sets the horizontal grid step size</summary> public int HorizontalGridSpacing { get { return m_horizontalGridSpacing; } set { if (value <= 0) throw new ArgumentOutOfRangeException(); m_horizontalGridSpacing = value; Invalidate(); } } /// <summary> /// Gets or sets the vertical grid step size</summary> public int VerticalGridSpacing { get { return m_verticalGridSpacing; } set { if (value <= 0) throw new ArgumentOutOfRangeException(); m_verticalGridSpacing = value; Invalidate(); } } #region ILayoutConstraint Members /// <summary> /// Gets the displayable name of the constraint</summary> public string Name { get { return "Grid".Localize("Grid location constraint"); } } /// <summary> /// Gets or sets whether the constraint is enabled and the grid rendered</summary> /// <remarks>Setting Enabled property also sets Visible, i.e., shows/hides the grid. /// Use ConstraintEnabled to enable/disable the constraint without any effect on rendering.</remarks> public bool Enabled { get { return m_enabled; } set { m_enabled = value; m_visible = value; } } /// <summary> /// Gets or sets a value indicating if the constraint is enabled (without any effect on grid rendering)</summary> public bool ConstraintEnabled { get { return m_enabled; } set { m_enabled = value; } } /// <summary> /// Applies constraint to bounding rectangle</summary> /// <param name="bounds">Unconstrained bounding rectangle</param> /// <param name="specified">Flags indicating which parts of bounding rectangle are meaningful</param> /// <returns>Constrained bounding rectangle</returns> public Rectangle Constrain(Rectangle bounds, BoundsSpecified specified) { if ((specified & BoundsSpecified.X) != 0) { bounds.X = (int)MathUtil.Snap(bounds.X, m_horizontalGridSpacing); if ((specified & BoundsSpecified.Width) != 0) { bounds.Width = (int)MathUtil.Snap(bounds.Width, m_horizontalGridSpacing); bounds.Width = Math.Max(bounds.Width, 0); } } if ((specified & BoundsSpecified.Y) != 0) { bounds.Y = (int)MathUtil.Snap(bounds.Y, m_verticalGridSpacing); if ((specified & BoundsSpecified.Height) != 0) { bounds.Height = (int)MathUtil.Snap(bounds.Height, m_verticalGridSpacing); bounds.Height = Math.Max(bounds.Height, 0); } } return bounds; } #endregion /// <summary> /// Binds the adapter to the adaptable control; called in the order that the adapters /// were defined on the control</summary> /// <param name="control">Adaptable control</param> protected override void Bind(AdaptableControl control) { m_transformAdapter = control.As<ITransformAdapter>(); SetGridColor(); if (control is D2dAdaptableControl) { var d2dControl = control as D2dAdaptableControl; d2dControl.DrawingD2d += control_DrawingD2d; } else control.Paint += control_Paint; control.BackColorChanged += control_BackColorChanged; } /// <summary> /// Unbinds the adapter from the adaptable control</summary> /// <param name="control">Adaptable control</param> protected override void Unbind(AdaptableControl control) { if (control is D2dAdaptableControl) ((D2dAdaptableControl)control).DrawingD2d -= control_DrawingD2d; else control.Paint -= control_Paint; } /// <summary> /// Sets grid to background color</summary> protected virtual void SetGridColor() { Color gridColor = AdaptedControl.BackColor; float intensity = ((float)gridColor.R + (float)gridColor.G + (float)gridColor.B) / 3; float shading = (intensity < 128) ? m_gridContrast : -m_gridContrast; m_gridColor = ColorUtil.GetShade(gridColor, 1 + shading); Invalidate(); } private void control_BackColorChanged(object sender, EventArgs e) { SetGridColor(); } private void control_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { if (m_visible) { Matrix transform = new Matrix(); if (m_transformAdapter != null) transform = m_transformAdapter.Transform; RectangleF clientRect = AdaptedControl.ClientRectangle; RectangleF canvasRect = GdiUtil.InverseTransform(transform, clientRect); // draw horizontal lines ChartUtil.DrawHorizontalGrid(transform, canvasRect, m_verticalGridSpacing, m_gridColor, e.Graphics); // draw vertical lines ChartUtil.DrawVerticalGrid(transform, canvasRect, m_horizontalGridSpacing, m_gridColor, e.Graphics); } } // draw dragged events private void control_DrawingD2d(object sender, EventArgs e) { if (m_visible) { // Matrix transform = new Matrix(); // if (m_transformAdapter != null) // transform = m_transformAdapter.Transform; var d2dControl = AdaptedControl as D2dAdaptableControl; Matrix3x2F xform = d2dControl.D2dGraphics.Transform; d2dControl.D2dGraphics.Transform = Matrix3x2F.Identity; Matrix transform = m_transformAdapter.Transform; RectangleF clientRect = AdaptedControl.ClientRectangle; // draw horizontal lines // ChartUtil.DrawHorizontalGrid(transform, canvasRect, m_verticalGridSpacing, d2dControl.Theme.GridPen, d2dControl.D2dGraphics); // draw vertical lines // ChartUtil.DrawVerticalGrid(transform, canvasRect, m_horizontalGridSpacing, d2dControl.Theme.GridPen, d2dControl.D2dGraphics); d2dControl.D2dGraphics.Transform = xform; } } private void Invalidate() { if (AdaptedControl != null) AdaptedControl.Invalidate(); } private ITransformAdapter m_transformAdapter; private Color m_gridColor; private float m_gridContrast = 0.25f; private int m_horizontalGridSpacing = 32; private int m_verticalGridSpacing = 32; private bool m_enabled = true; private bool m_visible = true; } }
35.505976
144
0.542639
[ "Apache-2.0" ]
StirfireStudios/ATF
Framework/Atf.Gui.WinForms/Controls/Adaptable/GridAdapter.cs
8,665
C#
using System; using System.Collections.Concurrent; using System.Reflection; using System.Runtime.Serialization; using System.Text.Json; using System.Text.Json.Serialization; namespace JsonNetMigrate.Json.Converters { /// <summary> /// An converter that extends <see cref="System.Text.Json.Serialization.JsonStringEnumConverter"/> /// to add support for <see cref="System.Runtime.Serialization.EnumMemberAttribute"/> name overrides. /// </summary> public class StringEnumConverter : JsonConverterFactory { private readonly JsonNamingPolicy? namingPolicy; private readonly bool allowIntegerValues; /// <summary> /// Constructs a default <see cref="StringEnumConverter"/>. /// </summary> public StringEnumConverter() : this(namingPolicy: null) { } /// <summary> /// Constructs a <see cref="StringEnumConverter"/> with the specified naming policy for enum values. /// </summary> /// <param name="namingPolicy">The naming policy used to resolve how enum values are written.</param> public StringEnumConverter(JsonNamingPolicy? namingPolicy) : this(namingPolicy: namingPolicy, allowIntegerValues: true) { } /// <summary> /// Constructs a <see cref="StringEnumConverter"/> with the specified options. /// </summary> /// <param name="namingPolicy">The naming policy used to resolve how enum values are written.</param> /// <param name="allowIntegerValues">Whether integers are allowed when reading.</param> public StringEnumConverter(JsonNamingPolicy? namingPolicy, bool allowIntegerValues) { this.namingPolicy = namingPolicy; this.allowIntegerValues = allowIntegerValues; } /// <inheritdoc /> public override bool CanConvert(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); return type.IsEnum; } /// <inheritdoc /> public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var converter = (JsonConverter)Activator.CreateInstance( type: typeof(GenericStringEnumConverter<>).MakeGenericType(typeToConvert), bindingAttr: BindingFlags.Instance | BindingFlags.Public, binder: null, args: new object?[] { namingPolicy, allowIntegerValues }, culture: null ); return converter; } private sealed class GenericStringEnumConverter<T> : JsonConverter<T> where T : struct, Enum { private readonly Lazy<EnumNamingPolicyCache<T>> lazyEnumNamingPolicyCache; public GenericStringEnumConverter(JsonNamingPolicy? namingPolicy, bool allowIntegerValues) { this.lazyEnumNamingPolicyCache = new Lazy<EnumNamingPolicyCache<T>>(() => new EnumNamingPolicyCache<T>(namingPolicy, allowIntegerValues)); } /// <inheritdoc /> public override bool CanConvert(Type type) { return type.IsEnum; } /// <inheritdoc /> public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.String) { string? name = reader.GetString(); string? transformedName = name != null ? lazyEnumNamingPolicyCache.Value.ReadNamingPolicy.ConvertName(name) : null; if (transformedName != null && !transformedName.Equals(name, StringComparison.Ordinal)) { if (Enum.TryParse(transformedName, out T value) || Enum.TryParse(transformedName, ignoreCase: true, result: out value)) { return value; } } } var defaultConverter = lazyEnumNamingPolicyCache.Value.DefaultJsonConverter; return defaultConverter.Read(ref reader, typeToConvert, options); } /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { var defaultConverter = lazyEnumNamingPolicyCache.Value.DefaultJsonConverter; defaultConverter.Write(writer, value, options); } } private sealed class EnumNamingPolicyCache<T> { public EnumNamingPolicyCache(JsonNamingPolicy? defaultWriteNamingPolicy, bool allowIntegerValues) { var enumType = typeof(T); var enumNameCache = new EnumNameCache(enumType, defaultWriteNamingPolicy); ReadNamingPolicy = new EnumReadNamingPolicy(enumNameCache); var writeNamingPolicy = new EnumWriteNamingPolicy(enumNameCache, defaultWriteNamingPolicy); var defaultJsonConverterFactory = new JsonStringEnumConverter(namingPolicy: writeNamingPolicy, allowIntegerValues: allowIntegerValues); DefaultJsonConverter = (JsonConverter<T>)defaultJsonConverterFactory.CreateConverter(typeToConvert: enumType, options: null); } public JsonNamingPolicy ReadNamingPolicy { get; } public JsonConverter<T> DefaultJsonConverter { get; } } private sealed class EnumReadNamingPolicy : JsonNamingPolicy { private readonly EnumNameCache enumNameCache; public EnumReadNamingPolicy(EnumNameCache enumNameCache) { this.enumNameCache = enumNameCache ?? throw new ArgumentNullException(nameof(enumNameCache)); } /// <inheritdoc /> public override string ConvertName(string name) { var nameTransformDictionary = enumNameCache.ReadNameTransformDictionary; if (nameTransformDictionary != null && nameTransformDictionary.TryGetValue(name, out string? transformedName)) { return transformedName; } var nameIgnoreCaseTransformDictionary = enumNameCache.ReadNameIgnoreCaseTransformDictionary; if (nameIgnoreCaseTransformDictionary != null && nameIgnoreCaseTransformDictionary.TryGetValue(name, out string? transformedNameIgnoreCase)) { return transformedNameIgnoreCase; } return name; } } private sealed class EnumWriteNamingPolicy : JsonNamingPolicy { private readonly EnumNameCache enumNameCache; private readonly JsonNamingPolicy? defaultNamingPolicy; public EnumWriteNamingPolicy(EnumNameCache enumNameCache, JsonNamingPolicy? defaultNamingPolicy) { this.enumNameCache = enumNameCache ?? throw new ArgumentNullException(nameof(enumNameCache)); this.defaultNamingPolicy = defaultNamingPolicy; } /// <inheritdoc /> public override string ConvertName(string name) { var nameTransformDictionary = enumNameCache.WriteNameTransformDictionary; if (nameTransformDictionary != null && nameTransformDictionary.TryGetValue(name, out string? transformedName)) { return transformedName; } if (defaultNamingPolicy != null) { return defaultNamingPolicy.ConvertName(name); } return name; } } private sealed class EnumNameCache { public EnumNameCache(Type enumType, JsonNamingPolicy? writeNamingPolicy) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException($"Type {enumType.FullName} is not an enum type"); string[] names = Enum.GetNames(enumType); foreach (var name in names) { var fieldInfo = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (fieldInfo == null) { continue; } string? explicitName; var enumMemberAttribute = fieldInfo.GetCustomAttribute<EnumMemberAttribute>(); if (enumMemberAttribute != null && !string.IsNullOrEmpty(enumMemberAttribute.Value)) { explicitName = enumMemberAttribute.Value; } else { explicitName = null; } string transformedName; if (explicitName != null) { transformedName = explicitName; } else if (writeNamingPolicy != null) { transformedName = writeNamingPolicy.ConvertName(name); } else { continue; } if (string.IsNullOrEmpty(transformedName)) { continue; } if (!transformedName.Equals(name, StringComparison.Ordinal)) { if (explicitName != null) { if (WriteNameTransformDictionary == null) { WriteNameTransformDictionary = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); } WriteNameTransformDictionary[name] = explicitName; } if (ReadNameTransformDictionary == null) { ReadNameTransformDictionary = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); } ReadNameTransformDictionary[transformedName] = name; } if (!transformedName.Equals(name, StringComparison.OrdinalIgnoreCase)) { if (ReadNameIgnoreCaseTransformDictionary == null) { ReadNameIgnoreCaseTransformDictionary = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); } ReadNameIgnoreCaseTransformDictionary[transformedName] = name; } } } public ConcurrentDictionary<string, string>? WriteNameTransformDictionary { get; } public ConcurrentDictionary<string, string>? ReadNameTransformDictionary { get; } public ConcurrentDictionary<string, string>? ReadNameIgnoreCaseTransformDictionary { get; } } } }
43.221402
157
0.557415
[ "MIT", "Unlicense" ]
22222/JsonNetMigrate
JsonNetMigrate/Converters/StringEnumConverter.cs
11,715
C#
#pragma checksum "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\Admin\DeleteGenre.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "25606a974638b5a9bbb18f947573fc35216f4c79" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Admin_DeleteGenre), @"mvc.1.0.view", @"/Views/Admin/DeleteGenre.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\_ViewImports.cshtml" using PicturesShop; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\_ViewImports.cshtml" using PicturesShop.Models; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\Admin\DeleteGenre.cshtml" using PicturesShop.Models.GenreController; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"25606a974638b5a9bbb18f947573fc35216f4c79", @"/Views/Admin/DeleteGenre.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"451189177e7713211cc6d71f1e21549ef78eb7c5", @"/Views/_ViewImports.cshtml")] public class Views_Admin_DeleteGenre : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<DeleteGenre> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "number", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Genre", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "DeleteGenre", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("@{\r\n ViewData[\"ActivePage\"] = \"DeleteGenre\";\r\n ViewData[\"ActiveTab\"] = \"Genres\";\r\n}\r\n"); WriteLiteral("<div class=\"mt-3 mr-3 ml-3 mb-3\">\r\n <h4>Delete genre</h4>\r\n <hr>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "25606a974638b5a9bbb18f947573fc35216f4c796143", async() => { WriteLiteral("\r\n <div class=\"row\">\r\n <div class=\"col\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "25606a974638b5a9bbb18f947573fc35216f4c796483", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 13 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\Admin\DeleteGenre.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.GenreId); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "25606a974638b5a9bbb18f947573fc35216f4c798106", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); #nullable restore #line 14 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\Admin\DeleteGenre.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.GenreId); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "25606a974638b5a9bbb18f947573fc35216f4c7910027", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 15 "D:\software engineering\вту софтуерно инженерство\1-ви курс\2-ри семестър\Уеб програмиране с .NET\Упражнения\PicturesShop mvc web asp net\PicturesShop\PicturesShop\Views\Admin\DeleteGenre.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.GenreId); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n </div>\r\n <div class=\"row mt-3\">\r\n <div class=\"col\">\r\n <button type=\"submit\" class=\"btn btn-primary\">Delete genre</button>\r\n </div>\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<DeleteGenre> Html { get; private set; } } } #pragma warning restore 1591
80.180791
350
0.754932
[ "MIT" ]
ruydiy/PicturesShop
PicturesShop/obj/Debug/net5.0/Razor/Views/Admin/DeleteGenre.cshtml.g.cs
14,647
C#
namespace CsIRC.Core { public enum MessageTarget { User = 0, Channel = 1 } public enum ModeType { List = 0, ParamUnset = 1, ParamSet = 2, NoParam = 3, Status = 4 } public enum MessageCommandType { Privmsg = 0, Notice = 1 } }
14
34
0.46131
[ "MIT" ]
Heufneutje/CsIRC
CsIRC/CsIRC.Core/Enums.cs
338
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ressy.Utils; namespace Ressy.HighLevel.Versions; /// <summary> /// Version information associated with a portable executable file. /// </summary> // https://docs.microsoft.com/en-us/windows/win32/menurc/vs-versioninfo public partial class VersionInfo { /// <summary> /// File version. /// </summary> public Version FileVersion { get; } /// <summary> /// Product version. /// </summary> public Version ProductVersion { get; } /// <summary> /// File flags. /// </summary> public FileFlags FileFlags { get; } /// <summary> /// File's target operating system. /// </summary> public FileOperatingSystem FileOperatingSystem { get; } /// <summary> /// File type. /// </summary> public FileType FileType { get; } /// <summary> /// File sub-type. /// </summary> public FileSubType FileSubType { get; } /// <summary> /// Version attribute tables. /// </summary> public IReadOnlyList<VersionAttributeTable> AttributeTables { get; } /// <summary> /// Initializes an instance of <see cref="VersionInfo"/>. /// </summary> public VersionInfo( Version fileVersion, Version productVersion, FileFlags fileFlags, FileOperatingSystem fileOperatingSystem, FileType fileType, FileSubType fileSubType, IReadOnlyList<VersionAttributeTable> attributeTables) { FileVersion = fileVersion; ProductVersion = productVersion; FileFlags = fileFlags; FileOperatingSystem = fileOperatingSystem; FileType = fileType; FileSubType = fileSubType; AttributeTables = attributeTables; } /// <summary> /// Gets the value of the specified attribute. /// Returns <c>null</c> if the specified attribute doesn't exist in any of the attribute tables. /// </summary> /// <remarks> /// If version info includes multiple attribute tables, this method retrieves the value from the /// first table that contains the specified attribute, while giving preference to tables in the /// neutral language. /// </remarks> public string? TryGetAttribute(VersionAttributeName name) => AttributeTables .OrderBy(t => t.Language.Id == Language.Neutral.Id) .Select(t => t.Attributes.GetValueOrDefault(name)) .FirstOrDefault(s => s is not null); /// <summary> /// Gets the value of the specified attribute. /// </summary> /// <remarks> /// If version info includes multiple attribute tables, this method retrieves the value from the /// first table that contains the specified attribute, while giving preference to tables in the /// neutral language. /// </remarks> public string GetAttribute(VersionAttributeName name) => TryGetAttribute(name) ?? throw new InvalidOperationException($"Attribute '{name}' does not exist in any of the attribute tables."); } public partial class VersionInfo { private static Encoding Encoding { get; } = Encoding.Unicode; }
31.29703
114
0.655489
[ "MIT" ]
Tyrrrz/Ressy
Ressy/HighLevel/Versions/VersionInfo.cs
3,161
C#
using System; using System.Collections.Generic; using System.Text; namespace ReactorUI.Primitives { public struct CornerRadius { public CornerRadius(double uniformRadius) { TopLeft = TopRight = BottomRight = BottomLeft = uniformRadius; } public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) { TopLeft = topLeft; TopRight = topRight; BottomRight = bottomRight; BottomLeft = bottomLeft; } public double TopLeft { get; set; } public double TopRight { get; set; } public double BottomRight { get; set; } public double BottomLeft { get; set; } } }
27.296296
99
0.61194
[ "MIT" ]
adospace/ReactorUI
src/ReactorUI/Primitives/CornerRadius.cs
739
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.sgw.Transform; using Aliyun.Acs.sgw.Transform.V20180511; namespace Aliyun.Acs.sgw.Model.V20180511 { public class EnableGatewayLoggingRequest : RpcAcsRequest<EnableGatewayLoggingResponse> { public EnableGatewayLoggingRequest() : base("sgw", "2018-05-11", "EnableGatewayLogging", "hcs_sgw", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string securityToken; private string gatewayId; public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string GatewayId { get { return gatewayId; } set { gatewayId = value; DictionaryUtil.Add(QueryParameters, "GatewayId", value); } } public override EnableGatewayLoggingResponse GetResponse(UnmarshallerContext unmarshallerContext) { return EnableGatewayLoggingResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
30.797468
134
0.693794
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-sgw/Sgw/Model/V20180511/EnableGatewayLoggingRequest.cs
2,433
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace ICSharpCode.SharpDevelop.Refactoring { /// <summary> /// Interaction logic for ContextActionsBulbControl.xaml /// </summary> public partial class ContextActionsBulbControl : UserControl { public ContextActionsBulbControl() { InitializeComponent(); this.IsOpen = false; } public event EventHandler ActionExecuted { add { this.ActionsTreeView.ActionExecuted += value; } remove { this.ActionsTreeView.ActionExecuted -= value; } } public new ContextActionsBulbViewModel DataContext { get { return (ContextActionsBulbViewModel)base.DataContext; } set { base.DataContext = value; } } bool isOpen; public bool IsOpen { get { return isOpen; } set { isOpen = value; this.Header.Opacity = isOpen ? 1.0 : 0.7; this.Header.BorderThickness = isOpen ? new Thickness(1, 1, 1, 0) : new Thickness(1); // Show / hide this.ContentBorder.Visibility = isOpen ? Visibility.Visible : Visibility.Collapsed; } } public bool IsHiddenActionsExpanded { get { return this.HiddenActionsExpander.IsExpanded; } set { this.HiddenActionsExpander.IsExpanded = value; } } public new void Focus() { if (this.ActionsTreeView != null) this.ActionsTreeView.Focus(); } void Header_MouseUp(object sender, MouseButtonEventArgs e) { this.IsOpen = !this.IsOpen; } void Expander_Expanded(object sender, RoutedEventArgs e) { this.DataContext.LoadHiddenActions(); } void CheckBox_Click(object sender, RoutedEventArgs e) { e.Handled = true; } } }
24.95
103
0.714429
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/Main/Base/Project/Src/Services/RefactoringService/ContextActions/ContextActionsBulbControl.xaml.cs
1,998
C#
using System; using CampgaignPOC.iOS.Resources; using CoreAnimation; using CoreGraphics; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(Entry), typeof(BorderlessEntryRenderer))] namespace CampgaignPOC.iOS.Resources { public class BorderlessEntryRenderer: EntryRenderer { private CALayer _line; protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); _line = null; if (Control == null || e.NewElement == null) return; Control.BorderStyle = UITextBorderStyle.None; _line = new CALayer { BorderColor = UIColor.FromRGB(174, 174, 174).CGColor, BackgroundColor = UIColor.FromRGB(174, 174, 174).CGColor, Frame = new CGRect(0, Frame.Height / 2, Frame.Width * 2, 1f) }; Control.Layer.AddSublayer(_line); } } }
28.885714
82
0.622156
[ "MIT" ]
malikabaglan/FundriseApp
CampgaignPOC/CampgaignPOC.iOS/Resources/BorderlessEntryRenderer.cs
1,013
C#
// ------------------------------------------------------------------------ // Muragatte - A Toolkit for Observation of Swarm Behaviour // Core Library // // Copyright (C) 2012 Jiří Vejmola. // Developed under the MIT License. See the file license.txt for details. // // Muragatte on the internet: http://code.google.com/p/muragatte/ // ------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Muragatte.Common; namespace Muragatte.Core.Environment { public class RectangleObstacle : Obstacle { #region Constructors public RectangleObstacle() : base() { } public RectangleObstacle(int id, MultiAgentSystem model, Species species, double size) : base(id, model, species, size, size) { } public RectangleObstacle(int id, MultiAgentSystem model, Species species, double width, double height) : base(id, model, species, width, height) { } public RectangleObstacle(int id, MultiAgentSystem model, Vector2 position, Species species, double size) : base(id, model, position, species, size, size) { } public RectangleObstacle(int id, MultiAgentSystem model, Vector2 position, Species species, double width, double height) : base(id, model, position, species, width, height) { } protected RectangleObstacle(RectangleObstacle other, MultiAgentSystem model) : base(other, model) { } #endregion #region Properties public override double Radius { get { return Math.Sqrt(_dWidth * _dWidth + _dHeight * _dHeight) / 2.0; } } public override string Name { get { return CreateName("Or"); } } #endregion #region Methods public override Element CloneTo(MultiAgentSystem model) { return new RectangleObstacle(this, model); } #endregion } }
31.621212
129
0.57978
[ "MIT" ]
yuqiora/muragatte
MuragatteCore/src/Core.Environment/RectangleObstacle.cs
2,091
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Plugin.Permissions; using Plugin.Permissions.Abstractions; using Permission = Android.Content.PM.Permission; namespace QiMata.AlternativeInterfaces.Droid { [Activity(Label = "QiMata.AlternativeInterfaces", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
32.567568
205
0.720332
[ "Apache-2.0" ]
QiMata/Alternative-Device-Interfaces-and-Machine-Learning
src/QiMata.AlternativeInterfaces/Android/MainActivity.cs
1,207
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("DOFSetupB2SFixup")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DOFSetupB2SFixup")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3942cb54-55a5-4858-8317-39e0e5e6f2a0")] // 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.777778
85
0.730659
[ "MIT" ]
Ashram56/DirectOutput
DOFSetupB2SFixup/Properties/AssemblyInfo.cs
1,397
C#
using Content.Server.Cuffs.Components; using Content.Server.Hands.Components; using Content.Shared.ActionBlocker; using Content.Shared.Cuffs; using Content.Shared.Hands.Components; using Content.Shared.MobState.Components; using Content.Shared.Popups; using Content.Shared.Verbs; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; namespace Content.Server.Cuffs { [UsedImplicitly] public sealed class CuffableSystem : SharedCuffableSystem { [Dependency] private readonly SharedPopupSystem _popupSystem = default!; [Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<HandCountChangedEvent>(OnHandCountChanged); SubscribeLocalEvent<UncuffAttemptEvent>(OnUncuffAttempt); SubscribeLocalEvent<CuffableComponent, GetVerbsEvent<Verb>>(AddUncuffVerb); } private void AddUncuffVerb(EntityUid uid, CuffableComponent component, GetVerbsEvent<Verb> args) { // Can the user access the cuffs, and is there even anything to uncuff? if (!args.CanAccess || component.CuffedHandCount == 0) return; // We only check can interact if the user is not uncuffing themselves. As a result, the verb will show up // when the user is incapacitated & trying to uncuff themselves, but TryUncuff() will still fail when // attempted. if (args.User != args.Target && !args.CanInteract) return; Verb verb = new(); verb.Act = () => component.TryUncuff(args.User); verb.Text = Loc.GetString("uncuff-verb-get-data-text"); //TODO VERB ICON add uncuffing symbol? may re-use the alert symbol showing that you are currently cuffed? args.Verbs.Add(verb); } private void OnUncuffAttempt(UncuffAttemptEvent args) { if (args.Cancelled) { return; } if (!EntityManager.EntityExists(args.User)) { // Should this even be possible? args.Cancel(); return; } // If the user is the target, special logic applies. // This is because the CanInteract blocking of the cuffs prevents self-uncuff. if (args.User == args.Target) { // This UncuffAttemptEvent check should probably be In MobStateSystem, not here? if (EntityManager.TryGetComponent<MobStateComponent?>(args.User, out var state)) { // Manually check this. if (state.IsIncapacitated()) { args.Cancel(); } } else { // Uh... let it go through??? // TODO CUFFABLE/STUN add UncuffAttemptEvent subscription to StunSystem } } else { // Check if the user can interact. if (!_actionBlockerSystem.CanInteract(args.User, args.Target)) { args.Cancel(); } } if (args.Cancelled) { _popupSystem.PopupEntity(Loc.GetString("cuffable-component-cannot-interact-message"), args.Target, Filter.Entities(args.User)); } } /// <summary> /// Check the current amount of hands the owner has, and if there's less hands than active cuffs we remove some cuffs. /// </summary> private void OnHandCountChanged(HandCountChangedEvent message) { var owner = message.Sender; if (!EntityManager.TryGetComponent(owner, out CuffableComponent? cuffable) || !cuffable.Initialized) return; var dirty = false; var handCount = EntityManager.GetComponentOrNull<HandsComponent>(owner)?.Count ?? 0; while (cuffable.CuffedHandCount > handCount && cuffable.CuffedHandCount > 0) { dirty = true; var container = cuffable.Container; var entity = container.ContainedEntities[^1]; container.Remove(entity); EntityManager.GetComponent<TransformComponent>(entity).WorldPosition = EntityManager.GetComponent<TransformComponent>(owner).WorldPosition; } if (dirty) { cuffable.CanStillInteract = handCount > cuffable.CuffedHandCount; cuffable.CuffedStateChanged(); Dirty(cuffable); } } } /// <summary> /// Event fired on the User when the User attempts to cuff the Target. /// Should generate popups on the User. /// </summary> public class UncuffAttemptEvent : CancellableEntityEventArgs { public readonly EntityUid User; public readonly EntityUid Target; public UncuffAttemptEvent(EntityUid user, EntityUid target) { User = user; Target = target; } } }
36.767123
155
0.583271
[ "MIT" ]
AzzyIsNotHere/space-station-14
Content.Server/Cuffs/CuffableSystem.cs
5,368
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SweetTooth.Models; using Microsoft.AspNetCore.Identity; namespace SweetTooth { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFrameworkMySql() .AddDbContext<SweetToothContext>(options => options .UseMySql(Configuration["ConnectionStrings:DefaultConnection"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<SweetToothContext>() .AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 0; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredUniqueChars = 1; }); } public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseDeveloperExceptionPage(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run(async (context) => { await context.Response.WriteAsync("Sorry, no sweets here!"); }); app.UseStaticFiles(); } } }
27.869565
74
0.678107
[ "MIT" ]
jamisoncozart/Sweet-Tooth
SweetTooth/Startup.cs
1,923
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CSharpWebResourceProjectTemplate")] [assembly: AssemblyDescription("CSharpWebResourceProjectTemplate")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("PhuocLe")] [assembly: AssemblyProduct("DynamicsCrm.DevKit")] [assembly: AssemblyCopyright("Copyright © PhuocLe 2016 - 2020")] [assembly: AssemblyTrademark("PhuocLe")] [assembly: AssemblyCulture("en")] [assembly: ComVisible(false)] [assembly: Guid("ae2c2285-298e-47cd-80eb-11f44b9f3d42")] [assembly: AssemblyVersion("2.12.31.0")] [assembly: AssemblyFileVersion("2.12.31.0")]
35.4
67
0.786723
[ "MIT" ]
Kayserheimer/Dynamics-Crm-DevKit
v2/ProjectTemplates/CSharp/05.WebResourceProjectTemplate/Properties/AssemblyInfo.cs
711
C#
// Copyright (c) 2019, WebsitePanel-Support.net. // Distributed by websitepanel-support.net // Build and fixed by Key4ce - IT Professionals // https://www.key4ce.com // // Original source: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use 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 Outercurve Foundation nor the names of its // 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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; namespace WebsitePanel.Providers.Virtualization { public class ReplicationDetailInfo { public VmReplicationMode Mode { get; set; } public ReplicationState State { get; set; } public ReplicationHealth Health { get; set; } public string HealthDetails { get; set; } public string PrimaryServerName { get; set; } public string ReplicaServerName { get; set; } public DateTime FromTime { get; set; } public DateTime ToTime { get; set; } public string AverageSize { get; set; } public string MaximumSize { get; set; } public TimeSpan AverageLatency { get; set; } public int Errors { get; set; } public int SuccessfulReplications { get; set; } public int MissedReplicationCount { get; set; } public string PendingSize { get; set; } public DateTime LastSynhronizedAt { get; set; } } }
47.864407
84
0.692989
[ "BSD-3-Clause" ]
Key4ce/Websitepanel
WebsitePanel/Sources/WebsitePanel.Providers.Base/Virtualization/Replication/ReplicationDetailInfo.cs
2,824
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Web; namespace Incubadora.Helpers.Exportacion { public class ListtoDataTableConverter { /// <summary> /// Esta clase se encarga de pintar las listas de objetos a un DataTable /// </summary> public DataTable ToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); //Get all the properties PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in Props) { //Setting column names as Property names dataTable.Columns.Add(prop.Name); } foreach (T item in items) { var values = new object[Props.Length]; for (int i = 0; i < Props.Length; i++) { //inserting property values to datatable rows values[i] = Props[i].GetValue(item, null); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; } } }
33.333333
108
0.512143
[ "MIT" ]
IncubadoraUniversidad/Incubadora
Incubadora/Helpers/Exportacion/ListtoDataTableConverter.cs
1,402
C#
using System; using System.Collections.Generic; namespace OpenRpg.AdviceEngine.Extensions { public static class IDisposableExtensions { public static void DisposeAll(this IEnumerable<IDisposable> disposables) { foreach(var disposable in disposables) { disposable.Dispose(); } } public static void DisposeAll<T>(this IDictionary<T, IDisposable> disposables) { foreach(var disposable in disposables.Values) { disposable.Dispose(); } } public static IDisposable AddTo(this IDisposable currentDisposable, ICollection<IDisposable> disposables) { disposables.Add(currentDisposable); return currentDisposable; } public static IDisposable AddTo<T>(this IDisposable currentDisposable, IDictionary<T, IDisposable> disposables, T key) { disposables.Add(key, currentDisposable); return currentDisposable; } } }
31.96875
126
0.638319
[ "MIT" ]
openrpg/OpenRpg.AdviceEngine
src/OpenRpg.AdviceEngine/Extensions/IDisposableExtensions.cs
1,025
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO.Pipelines; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.Http.Connections.Client { /// <summary> /// Used to make a connection to an ASP.NET Core ConnectionHandler using an HTTP-based transport. /// </summary> public partial class HttpConnection : ConnectionContext, IConnectionInherentKeepAliveFeature { // Not configurable on purpose, high enough that if we reach here, it's likely // a buggy server private static readonly int _maxRedirects = 100; private static readonly Task<string> _noAccessToken = Task.FromResult<string>(null); private static readonly TimeSpan HttpClientTimeout = TimeSpan.FromSeconds(120); #if !NETCOREAPP3_0 private static readonly Version Windows8Version = new Version(6, 2); #endif private readonly ILogger _logger; private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1, 1); private bool _started; private bool _disposed; private bool _hasInherentKeepAlive; private readonly HttpClient _httpClient; private readonly HttpConnectionOptions _httpConnectionOptions; private ITransport _transport; private readonly ITransportFactory _transportFactory; private string _connectionId; private readonly ConnectionLogScope _logScope; private readonly ILoggerFactory _loggerFactory; private Func<Task<string>> _accessTokenProvider; /// <inheritdoc /> public override IDuplexPipe Transport { get { CheckDisposed(); if (_transport == null) { throw new InvalidOperationException($"Cannot access the {nameof(Transport)} pipe before the connection has started."); } return _transport; } set => throw new NotSupportedException("The transport pipe isn't settable."); } /// <inheritdoc /> public override IFeatureCollection Features { get; } = new FeatureCollection(); /// <summary> /// Gets or sets the connection ID. /// </summary> /// <remarks> /// The connection ID is set when the <see cref="HttpConnection"/> is started and should not be set by user code. /// If the connection was created with <see cref="HttpConnectionOptions.SkipNegotiation"/> set to <c>true</c> /// then the connection ID will be <c>null</c>. /// </remarks> public override string ConnectionId { get => _connectionId; set => throw new InvalidOperationException("The ConnectionId is set internally and should not be set by user code."); } /// <inheritdoc /> public override IDictionary<object, object> Items { get; set; } = new ConnectionItems(); /// <inheritdoc /> bool IConnectionInherentKeepAliveFeature.HasInherentKeepAlive => _hasInherentKeepAlive; /// <summary> /// Initializes a new instance of the <see cref="HttpConnection"/> class. /// </summary> /// <param name="url">The URL to connect to.</param> public HttpConnection(Uri url) : this(url, HttpTransports.All) { } /// <summary> /// Initializes a new instance of the <see cref="HttpConnection"/> class. /// </summary> /// <param name="url">The URL to connect to.</param> /// <param name="transports">A bitmask combining one or more <see cref="HttpTransportType"/> values that specify what transports the client should use.</param> public HttpConnection(Uri url, HttpTransportType transports) : this(url, transports, loggerFactory: null) { } /// <summary> /// Initializes a new instance of the <see cref="HttpConnection"/> class. /// </summary> /// <param name="url">The URL to connect to.</param> /// <param name="transports">A bitmask combining one or more <see cref="HttpTransportType"/> values that specify what transports the client should use.</param> /// <param name="loggerFactory">The logger factory.</param> public HttpConnection(Uri url, HttpTransportType transports, ILoggerFactory loggerFactory) : this(CreateHttpOptions(url, transports), loggerFactory) { } private static HttpConnectionOptions CreateHttpOptions(Uri url, HttpTransportType transports) { if (url == null) { throw new ArgumentNullException(nameof(url)); } return new HttpConnectionOptions { Url = url, Transports = transports }; } /// <summary> /// Initializes a new instance of the <see cref="HttpConnection"/> class. /// </summary> /// <param name="httpConnectionOptions">The connection options to use.</param> /// <param name="loggerFactory">The logger factory.</param> public HttpConnection(HttpConnectionOptions httpConnectionOptions, ILoggerFactory loggerFactory) { if (httpConnectionOptions.Url == null) { throw new ArgumentException("Options does not have a URL specified.", nameof(httpConnectionOptions)); } _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; _logger = _loggerFactory.CreateLogger<HttpConnection>(); _httpConnectionOptions = httpConnectionOptions; if (!httpConnectionOptions.SkipNegotiation || httpConnectionOptions.Transports != HttpTransportType.WebSockets) { _httpClient = CreateHttpClient(); } _transportFactory = new DefaultTransportFactory(httpConnectionOptions.Transports, _loggerFactory, _httpClient, httpConnectionOptions, GetAccessTokenAsync); _logScope = new ConnectionLogScope(); Features.Set<IConnectionInherentKeepAliveFeature>(this); } // Used by unit tests internal HttpConnection(HttpConnectionOptions httpConnectionOptions, ILoggerFactory loggerFactory, ITransportFactory transportFactory) : this(httpConnectionOptions, loggerFactory) { _transportFactory = transportFactory; } /// <summary> /// Starts the connection. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous start.</returns> /// <remarks> /// A connection cannot be restarted after it has stopped. To restart a connection /// a new instance should be created using the same options. /// </remarks> public Task StartAsync(CancellationToken cancellationToken = default) { return StartAsync(TransferFormat.Binary, cancellationToken); } /// <summary> /// Starts the connection using the specified transfer format. /// </summary> /// <param name="transferFormat">The transfer format the connection should use.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous start.</returns> /// <remarks> /// A connection cannot be restarted after it has stopped. To restart a connection /// a new instance should be created using the same options. /// </remarks> public async Task StartAsync(TransferFormat transferFormat, CancellationToken cancellationToken = default) { using (_logger.BeginScope(_logScope)) { await StartAsyncCore(transferFormat, cancellationToken).ForceAsync(); } } private async Task StartAsyncCore(TransferFormat transferFormat, CancellationToken cancellationToken) { CheckDisposed(); if (_started) { Log.SkippingStart(_logger); return; } await _connectionLock.WaitAsync(); try { CheckDisposed(); if (_started) { Log.SkippingStart(_logger); return; } Log.Starting(_logger); await SelectAndStartTransport(transferFormat, cancellationToken); _started = true; Log.Started(_logger); } finally { _connectionLock.Release(); } } /// <summary> /// Disposes the connection. /// </summary> /// <returns>A <see cref="Task"/> that represents the asynchronous dispose.</returns> /// <remarks> /// A connection cannot be restarted after it has stopped. To restart a connection /// a new instance should be created using the same options. /// </remarks> public override async ValueTask DisposeAsync() { using (_logger.BeginScope(_logScope)) { await DisposeAsyncCore().ForceAsync(); } } private async Task DisposeAsyncCore() { if (_disposed) { return; } await _connectionLock.WaitAsync(); try { if (!_disposed && _started) { Log.DisposingHttpConnection(_logger); // Stop the transport, but we don't care if it throws. // The transport should also have completed the pipe with this exception. try { await _transport.StopAsync(); } catch (Exception ex) { Log.TransportThrewExceptionOnStop(_logger, ex); } Log.Disposed(_logger); } else { Log.SkippingDispose(_logger); } _httpClient?.Dispose(); } finally { // We want to do these things even if the WaitForWriterToComplete/WaitForReaderToComplete fails if (!_disposed) { _disposed = true; } _connectionLock.Release(); } } private async Task SelectAndStartTransport(TransferFormat transferFormat, CancellationToken cancellationToken) { var uri = _httpConnectionOptions.Url; // Set the initial access token provider back to the original one from options _accessTokenProvider = _httpConnectionOptions.AccessTokenProvider; var transportExceptions = new List<Exception>(); if (_httpConnectionOptions.SkipNegotiation) { if (_httpConnectionOptions.Transports == HttpTransportType.WebSockets) { Log.StartingTransport(_logger, _httpConnectionOptions.Transports, uri); await StartTransport(uri, _httpConnectionOptions.Transports, transferFormat, cancellationToken); } else { throw new InvalidOperationException("Negotiation can only be skipped when using the WebSocket transport directly."); } } else { NegotiationResponse negotiationResponse; var redirects = 0; do { negotiationResponse = await GetNegotiationResponseAsync(uri, cancellationToken); if (negotiationResponse.Url != null) { uri = new Uri(negotiationResponse.Url); } if (negotiationResponse.AccessToken != null) { string accessToken = negotiationResponse.AccessToken; // Set the current access token factory so that future requests use this access token _accessTokenProvider = () => Task.FromResult(accessToken); } redirects++; } while (negotiationResponse.Url != null && redirects < _maxRedirects); if (redirects == _maxRedirects && negotiationResponse.Url != null) { throw new InvalidOperationException("Negotiate redirection limit exceeded."); } // This should only need to happen once var connectUrl = CreateConnectUrl(uri, negotiationResponse.ConnectionId); // We're going to search for the transfer format as a string because we don't want to parse // all the transfer formats in the negotiation response, and we want to allow transfer formats // we don't understand in the negotiate response. var transferFormatString = transferFormat.ToString(); foreach (var transport in negotiationResponse.AvailableTransports) { if (!Enum.TryParse<HttpTransportType>(transport.Transport, out var transportType)) { Log.TransportNotSupported(_logger, transport.Transport); transportExceptions.Add(new TransportFailedException(transport.Transport, "The transport is not supported by the client.")); continue; } if (transportType == HttpTransportType.WebSockets && !IsWebSocketsSupported()) { Log.WebSocketsNotSupportedByOperatingSystem(_logger); transportExceptions.Add(new TransportFailedException("WebSockets", "The transport is not supported on this operating system.")); continue; } try { if ((transportType & _httpConnectionOptions.Transports) == 0) { Log.TransportDisabledByClient(_logger, transportType); transportExceptions.Add(new TransportFailedException(transportType.ToString(), "The transport is disabled by the client.")); } else if (!transport.TransferFormats.Contains(transferFormatString, StringComparer.Ordinal)) { Log.TransportDoesNotSupportTransferFormat(_logger, transportType, transferFormat); transportExceptions.Add(new TransportFailedException(transportType.ToString(), $"The transport does not support the '{transferFormat}' transfer format.")); } else { // The negotiation response gets cleared in the fallback scenario. if (negotiationResponse == null) { negotiationResponse = await GetNegotiationResponseAsync(uri, cancellationToken); connectUrl = CreateConnectUrl(uri, negotiationResponse.ConnectionId); } Log.StartingTransport(_logger, transportType, connectUrl); await StartTransport(connectUrl, transportType, transferFormat, cancellationToken); break; } } catch (Exception ex) { Log.TransportFailed(_logger, transportType, ex); transportExceptions.Add(new TransportFailedException(transportType.ToString(), ex.Message, ex)); // Try the next transport // Clear the negotiation response so we know to re-negotiate. negotiationResponse = null; } } } if (_transport == null) { if (transportExceptions.Count > 0) { throw new AggregateException("Unable to connect to the server with any of the available transports.", transportExceptions); } else { throw new NoTransportSupportedException("None of the transports supported by the client are supported by the server."); } } } private async Task<NegotiationResponse> NegotiateAsync(Uri url, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken) { try { // Get a connection ID from the server Log.EstablishingConnection(logger, url); var urlBuilder = new UriBuilder(url); if (!urlBuilder.Path.EndsWith("/")) { urlBuilder.Path += "/"; } urlBuilder.Path += "negotiate"; using (var request = new HttpRequestMessage(HttpMethod.Post, urlBuilder.Uri)) { // Corefx changed the default version and High Sierra curlhandler tries to upgrade request request.Version = new Version(1, 1); // ResponseHeadersRead instructs SendAsync to return once headers are read // rather than buffer the entire response. This gives a small perf boost. // Note that it is important to dispose of the response when doing this to // avoid leaving the connection open. using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) { response.EnsureSuccessStatusCode(); var responseBuffer = await response.Content.ReadAsByteArrayAsync(); var negotiateResponse = NegotiateProtocol.ParseResponse(responseBuffer); if (!string.IsNullOrEmpty(negotiateResponse.Error)) { throw new Exception(negotiateResponse.Error); } Log.ConnectionEstablished(_logger, negotiateResponse.ConnectionId); return negotiateResponse; } } } catch (Exception ex) { Log.ErrorWithNegotiation(logger, url, ex); throw; } } private static Uri CreateConnectUrl(Uri url, string connectionId) { if (string.IsNullOrWhiteSpace(connectionId)) { throw new FormatException("Invalid connection id."); } return Utils.AppendQueryString(url, "id=" + connectionId); } private async Task StartTransport(Uri connectUrl, HttpTransportType transportType, TransferFormat transferFormat, CancellationToken cancellationToken) { // Construct the transport var transport = _transportFactory.CreateTransport(transportType); // Start the transport, giving it one end of the pipe try { await transport.StartAsync(connectUrl, transferFormat, cancellationToken); } catch (Exception ex) { Log.ErrorStartingTransport(_logger, transportType, ex); _transport = null; throw; } // Disable keep alives for long polling _hasInherentKeepAlive = transportType == HttpTransportType.LongPolling; // We successfully started, set the transport properties (we don't want to set these until the transport is definitely running). _transport = transport; Log.TransportStarted(_logger, transportType); } private HttpClient CreateHttpClient() { var httpClientHandler = new HttpClientHandler(); HttpMessageHandler httpMessageHandler = httpClientHandler; if (_httpConnectionOptions != null) { if (_httpConnectionOptions.Proxy != null) { httpClientHandler.Proxy = _httpConnectionOptions.Proxy; } if (_httpConnectionOptions.Cookies != null) { httpClientHandler.CookieContainer = _httpConnectionOptions.Cookies; } // Only access HttpClientHandler.ClientCertificates if the user has configured client certs // Mono does not support client certs and will throw NotImplementedException // https://github.com/aspnet/SignalR/issues/2232 var clientCertificates = _httpConnectionOptions.ClientCertificates; if (clientCertificates?.Count > 0) { httpClientHandler.ClientCertificates.AddRange(clientCertificates); } if (_httpConnectionOptions.UseDefaultCredentials != null) { httpClientHandler.UseDefaultCredentials = _httpConnectionOptions.UseDefaultCredentials.Value; } if (_httpConnectionOptions.Credentials != null) { httpClientHandler.Credentials = _httpConnectionOptions.Credentials; } httpMessageHandler = httpClientHandler; if (_httpConnectionOptions.HttpMessageHandlerFactory != null) { httpMessageHandler = _httpConnectionOptions.HttpMessageHandlerFactory(httpClientHandler); if (httpMessageHandler == null) { throw new InvalidOperationException("Configured HttpMessageHandlerFactory did not return a value."); } } // Apply the authorization header in a handler instead of a default header because it can change with each request httpMessageHandler = new AccessTokenHttpMessageHandler(httpMessageHandler, this); } // Wrap message handler after HttpMessageHandlerFactory to ensure not overridden httpMessageHandler = new LoggingHttpMessageHandler(httpMessageHandler, _loggerFactory); var httpClient = new HttpClient(httpMessageHandler); httpClient.Timeout = HttpClientTimeout; // Start with the user agent header httpClient.DefaultRequestHeaders.UserAgent.Add(Constants.UserAgentHeader); // Apply any headers configured on the HttpConnectionOptions if (_httpConnectionOptions?.Headers != null) { foreach (var header in _httpConnectionOptions.Headers) { httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } } httpClient.DefaultRequestHeaders.Remove("X-Requested-With"); // Tell auth middleware to 401 instead of redirecting httpClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest"); return httpClient; } internal Task<string> GetAccessTokenAsync() { if (_accessTokenProvider == null) { return _noAccessToken; } return _accessTokenProvider(); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(HttpConnection)); } } private static bool IsWebSocketsSupported() { #if NETCOREAPP3_0 // .NET Core 2.1 and above has a managed implementation return true; #else var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (!isWindows) { // Assume other OSes have websockets return true; } else { // Windows 8 and above has websockets return Environment.OSVersion.Version >= Windows8Version; } #endif } private async Task<NegotiationResponse> GetNegotiationResponseAsync(Uri uri, CancellationToken cancellationToken) { var negotiationResponse = await NegotiateAsync(uri, _httpClient, _logger, cancellationToken); _connectionId = negotiationResponse.ConnectionId; _logScope.ConnectionId = _connectionId; return negotiationResponse; } } }
42.076299
183
0.576102
[ "Apache-2.0" ]
Deckhandfirststar01/AspNetCore
src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs
25,919
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Crosshair : MonoBehaviour { public float PosX = 0; public float PosY = 0; public Text debug; // Use this for initialization void Start () { } // Update is called once per frame void Update () { var mx = Input.GetAxis("Mouse X") * Time.deltaTime * 100.0f + PosX; var my = Input.GetAxis("Mouse Y") * Time.deltaTime * 100.0f + PosY; float dist = (mx * mx + my * my); if (dist > 2500) { dist = 50 / Mathf.Sqrt(dist); mx *= dist; my *= dist; } transform.Translate(mx - PosX, my - PosY, 0); PosX = mx; PosY = my; //debug.text = "x: " + PosX + " y: " + PosY; } }
23.771429
75
0.533654
[ "MIT" ]
azakhi/JASG
Assets/Scripts/Crosshair.cs
834
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using Xunit; using System.Threading.Tasks; using FluentAssertions; namespace Microsoft.DotNet.Kestrel.Tests { public class DotnetTest : TestBase { private const string KestrelSampleBase = "KestrelSample"; private const string KestrelPortable = "KestrelPortable"; private const string KestrelStandalone = "KestrelStandalone"; [Fact] public void ItRunsKestrelPortableAfterBuild() { TestInstance instance = TestAssetsManager.CreateTestInstance(KestrelSampleBase) .WithLockFiles(); var url = NetworkHelper.GetLocalhostUrlWithFreePort(); var args = $"{url} {Guid.NewGuid().ToString()}"; var dotnetCommand = new DotnetCommand(); var output = Build(Path.Combine(instance.TestRoot, KestrelPortable)); try { dotnetCommand.ExecuteAsync($"{output} {args}"); NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {KestrelPortable} @ {url}"); NetworkHelper.TestGetRequest(url, args); } finally { dotnetCommand.KillTree(); } } [Fact] public void ItRunsKestrelStandaloneAfterBuild() { TestInstance instance = TestAssetsManager.CreateTestInstance(KestrelSampleBase) .WithLockFiles(); var url = NetworkHelper.GetLocalhostUrlWithFreePort(); var args = $"{url} {Guid.NewGuid().ToString()}"; var dotnetCommand = new DotnetCommand(); var output = Build(Path.Combine(instance.TestRoot, KestrelStandalone)); try { dotnetCommand.ExecuteAsync($"{output} {args}"); NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {KestrelStandalone} @ {url}"); NetworkHelper.TestGetRequest(url, args); } finally { dotnetCommand.KillTree(); } } [Fact] public void ItRunsKestrelPortableAfterPublish() { TestInstance instance = TestAssetsManager.CreateTestInstance(KestrelSampleBase) .WithLockFiles(); var url = NetworkHelper.GetLocalhostUrlWithFreePort(); var args = $"{url} {Guid.NewGuid().ToString()}"; var dotnetCommand = new DotnetCommand(); var output = Publish(Path.Combine(instance.TestRoot, KestrelPortable), true); try { dotnetCommand.ExecuteAsync($"{output} {args}"); NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {KestrelPortable} @ {url}"); NetworkHelper.TestGetRequest(url, args); } finally { dotnetCommand.KillTree(); } } [Fact] public void ItRunsKestrelStandaloneAfterPublish() { TestInstance instance = TestAssetsManager.CreateTestInstance(KestrelSampleBase) .WithLockFiles(); var url = NetworkHelper.GetLocalhostUrlWithFreePort(); var args = $"{url} {Guid.NewGuid().ToString()}"; var output = Publish(Path.Combine(instance.TestRoot, KestrelStandalone), false); var command = new TestCommand(output); try { command.ExecuteAsync($"{args}"); NetworkHelper.IsServerUp(url).Should().BeTrue($"Unable to connect to kestrel server - {KestrelStandalone} @ {url}"); NetworkHelper.TestGetRequest(url, args); } finally { command.KillTree(); } } private static string Build(string testRoot) { string appName = Path.GetFileName(testRoot); var result = new BuildCommand( projectPath: testRoot) .ExecuteWithCapturedOutput(); result.Should().Pass(); // the correct build assembly is next to its deps.json file var depsJsonFile = Directory.EnumerateFiles(testRoot, appName + FileNameSuffixes.DepsJson, SearchOption.AllDirectories).First(); return Path.Combine(Path.GetDirectoryName(depsJsonFile), appName + ".dll"); } private static string Publish(string testRoot, bool isPortable) { string appName = Path.GetFileName(testRoot); var publishCmd = new PublishCommand(projectPath: testRoot, output: Path.Combine(testRoot, "bin")); var result = publishCmd.ExecuteWithCapturedOutput(); result.Should().Pass(); var publishDir = publishCmd.GetOutputDirectory(portable: isPortable).FullName; return Path.Combine(publishDir, appName + (isPortable ? ".dll" : FileNameSuffixes.CurrentPlatform.Exe)); } } }
38.78169
140
0.583802
[ "MIT" ]
crummel/dotnet_cli
test/Kestrel.Tests/DotnetTest.cs
5,509
C#
// <auto-generated /> using System; using JjOnlineStore.Data.EF; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace JjOnlineStore.Data.EF.Migrations { [DbContext(typeof(JjOnlineStoreDbContext))] [Migration("20180922172757_AddProducts")] partial class AddProducts { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.3-rtm-32065") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AspNetCoreTemplate.Data.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("IsDeleted"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("JjOnlineStore.Data.Entities.ApplicationRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("JjOnlineStore.Data.Entities.Category", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("JjOnlineStore.Data.Entities.Product", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Base64Image") .IsRequired(); b.Property<long>("CategoryId"); b.Property<string>("Color"); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<string>("Description") .IsRequired(); b.Property<string>("Details"); b.Property<bool>("IsAvailable"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .IsRequired(); b.Property<decimal>("Price"); b.Property<int>("Size"); b.Property<int>("Type"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Products"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("JjOnlineStore.Data.Entities.Product", b => { b.HasOne("JjOnlineStore.Data.Entities.Category", "Category") .WithMany("Products") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("JjOnlineStore.Data.Entities.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("AspNetCoreTemplate.Data.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("AspNetCoreTemplate.Data.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("JjOnlineStore.Data.Entities.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("AspNetCoreTemplate.Data.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("AspNetCoreTemplate.Data.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.135802
125
0.480832
[ "MIT" ]
profjordanov/JJ-Online-Store
Data/JjOnlineStore.Data.EF/Migrations/20180922172757_AddProducts.Designer.cs
11,062
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 datapipeline-2012-10-29.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.DataPipeline.Model; using Amazon.DataPipeline.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.DataPipeline { /// <summary> /// Implementation for accessing DataPipeline /// /// AWS Data Pipeline configures and manages a data-driven workflow called a pipeline. /// AWS Data Pipeline handles the details of scheduling and ensuring that data dependencies /// are met so that your application can focus on processing the data. /// /// /// <para> /// AWS Data Pipeline provides a JAR implementation of a task runner called AWS Data Pipeline /// Task Runner. AWS Data Pipeline Task Runner provides logic for common data management /// scenarios, such as performing database queries and running data analysis using Amazon /// Elastic MapReduce (Amazon EMR). You can use AWS Data Pipeline Task Runner as your /// task runner, or you can write your own task runner to provide custom data management. /// </para> /// /// <para> /// AWS Data Pipeline implements two main sets of functionality. Use the first set to /// create a pipeline and define data sources, schedules, dependencies, and the transforms /// to be performed on the data. Use the second set in your task runner application to /// receive the next task ready for processing. The logic for performing the task, such /// as querying the data, running data analysis, or converting the data from one format /// to another, is contained within the task runner. The task runner performs the task /// assigned to it by the web service, reporting progress to the web service as it does /// so. When the task is done, the task runner reports the final success or failure of /// the task to the web service. /// </para> /// </summary> public partial class AmazonDataPipelineClient : AmazonServiceClient, IAmazonDataPipeline { #region Constructors /// <summary> /// Constructs AmazonDataPipelineClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonDataPipelineClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataPipelineConfig()) { } /// <summary> /// Constructs AmazonDataPipelineClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonDataPipelineClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataPipelineConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataPipelineClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonDataPipelineClient Configuration Object</param> public AmazonDataPipelineClient(AmazonDataPipelineConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonDataPipelineClient(AWSCredentials credentials) : this(credentials, new AmazonDataPipelineConfig()) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonDataPipelineClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonDataPipelineConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Credentials and an /// AmazonDataPipelineClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param> public AmazonDataPipelineClient(AWSCredentials credentials, AmazonDataPipelineConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataPipelineConfig()) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataPipelineConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDataPipelineClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDataPipelineConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataPipelineConfig()) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataPipelineConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataPipelineClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDataPipelineClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonDataPipelineClient Configuration Object</param> public AmazonDataPipelineClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDataPipelineConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region ActivatePipeline /// <summary> /// Validates the specified pipeline and starts processing pipeline tasks. If the pipeline /// does not pass validation, activation fails. /// /// /// <para> /// If you need to pause the pipeline to investigate an issue with a component, such as /// a data source or script, call <a>DeactivatePipeline</a>. /// </para> /// /// <para> /// To activate a finished pipeline, modify the end date for the pipeline and then activate /// it. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ActivatePipeline service method.</param> /// /// <returns>The response from the ActivatePipeline service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">REST API Reference for ActivatePipeline Operation</seealso> public virtual ActivatePipelineResponse ActivatePipeline(ActivatePipelineRequest request) { var marshaller = ActivatePipelineRequestMarshaller.Instance; var unmarshaller = ActivatePipelineResponseUnmarshaller.Instance; return Invoke<ActivatePipelineRequest,ActivatePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ActivatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ActivatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">REST API Reference for ActivatePipeline Operation</seealso> public virtual Task<ActivatePipelineResponse> ActivatePipelineAsync(ActivatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ActivatePipelineRequestMarshaller.Instance; var unmarshaller = ActivatePipelineResponseUnmarshaller.Instance; return InvokeAsync<ActivatePipelineRequest,ActivatePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AddTags /// <summary> /// Adds or modifies tags for the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tags">The tags to add, as key/value pairs.</param> /// /// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso> public virtual AddTagsResponse AddTags(string pipelineId, List<Tag> tags) { var request = new AddTagsRequest(); request.PipelineId = pipelineId; request.Tags = tags; return AddTags(request); } /// <summary> /// Adds or modifies tags for the specified pipeline. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AddTags service method.</param> /// /// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso> public virtual AddTagsResponse AddTags(AddTagsRequest request) { var marshaller = AddTagsRequestMarshaller.Instance; var unmarshaller = AddTagsResponseUnmarshaller.Instance; return Invoke<AddTagsRequest,AddTagsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Adds or modifies tags for the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tags">The tags to add, as key/value pairs.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso> public virtual Task<AddTagsResponse> AddTagsAsync(string pipelineId, List<Tag> tags, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new AddTagsRequest(); request.PipelineId = pipelineId; request.Tags = tags; return AddTagsAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the AddTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddTags operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">REST API Reference for AddTags Operation</seealso> public virtual Task<AddTagsResponse> AddTagsAsync(AddTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = AddTagsRequestMarshaller.Instance; var unmarshaller = AddTagsResponseUnmarshaller.Instance; return InvokeAsync<AddTagsRequest,AddTagsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreatePipeline /// <summary> /// Creates a new, empty pipeline. Use <a>PutPipelineDefinition</a> to populate the pipeline. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreatePipeline service method.</param> /// /// <returns>The response from the CreatePipeline service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso> public virtual CreatePipelineResponse CreatePipeline(CreatePipelineRequest request) { var marshaller = CreatePipelineRequestMarshaller.Instance; var unmarshaller = CreatePipelineResponseUnmarshaller.Instance; return Invoke<CreatePipelineRequest,CreatePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso> public virtual Task<CreatePipelineResponse> CreatePipelineAsync(CreatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreatePipelineRequestMarshaller.Instance; var unmarshaller = CreatePipelineResponseUnmarshaller.Instance; return InvokeAsync<CreatePipelineRequest,CreatePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeactivatePipeline /// <summary> /// Deactivates the specified running pipeline. The pipeline is set to the <code>DEACTIVATING</code> /// state until the deactivation process completes. /// /// /// <para> /// To resume a deactivated pipeline, use <a>ActivatePipeline</a>. By default, the pipeline /// resumes from the last completed execution. Optionally, you can specify the date and /// time to resume the pipeline. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeactivatePipeline service method.</param> /// /// <returns>The response from the DeactivatePipeline service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">REST API Reference for DeactivatePipeline Operation</seealso> public virtual DeactivatePipelineResponse DeactivatePipeline(DeactivatePipelineRequest request) { var marshaller = DeactivatePipelineRequestMarshaller.Instance; var unmarshaller = DeactivatePipelineResponseUnmarshaller.Instance; return Invoke<DeactivatePipelineRequest,DeactivatePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeactivatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeactivatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">REST API Reference for DeactivatePipeline Operation</seealso> public virtual Task<DeactivatePipelineResponse> DeactivatePipelineAsync(DeactivatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeactivatePipelineRequestMarshaller.Instance; var unmarshaller = DeactivatePipelineResponseUnmarshaller.Instance; return InvokeAsync<DeactivatePipelineRequest,DeactivatePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeletePipeline /// <summary> /// Deletes a pipeline, its pipeline definition, and its run history. AWS Data Pipeline /// attempts to cancel instances associated with the pipeline that are currently being /// processed by task runners. /// /// /// <para> /// Deleting a pipeline cannot be undone. You cannot query or restore a deleted pipeline. /// To temporarily pause a pipeline instead of deleting it, call <a>SetStatus</a> with /// the status set to <code>PAUSE</code> on individual components. Components that are /// paused by <a>SetStatus</a> can be resumed. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeletePipeline service method.</param> /// /// <returns>The response from the DeletePipeline service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso> public virtual DeletePipelineResponse DeletePipeline(DeletePipelineRequest request) { var marshaller = DeletePipelineRequestMarshaller.Instance; var unmarshaller = DeletePipelineResponseUnmarshaller.Instance; return Invoke<DeletePipelineRequest,DeletePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeletePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso> public virtual Task<DeletePipelineResponse> DeletePipelineAsync(DeletePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeletePipelineRequestMarshaller.Instance; var unmarshaller = DeletePipelineResponseUnmarshaller.Instance; return InvokeAsync<DeletePipelineRequest,DeletePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeObjects /// <summary> /// Gets the object definitions for a set of objects associated with the pipeline. Object /// definitions are composed of a set of fields that define the properties of the object. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeObjects service method.</param> /// /// <returns>The response from the DescribeObjects service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">REST API Reference for DescribeObjects Operation</seealso> public virtual DescribeObjectsResponse DescribeObjects(DescribeObjectsRequest request) { var marshaller = DescribeObjectsRequestMarshaller.Instance; var unmarshaller = DescribeObjectsResponseUnmarshaller.Instance; return Invoke<DescribeObjectsRequest,DescribeObjectsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeObjects operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeObjects operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">REST API Reference for DescribeObjects Operation</seealso> public virtual Task<DescribeObjectsResponse> DescribeObjectsAsync(DescribeObjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeObjectsRequestMarshaller.Instance; var unmarshaller = DescribeObjectsResponseUnmarshaller.Instance; return InvokeAsync<DescribeObjectsRequest,DescribeObjectsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribePipelines /// <summary> /// Retrieves metadata about one or more pipelines. The information retrieved includes /// the name of the pipeline, the pipeline identifier, its current state, and the user /// account that owns the pipeline. Using account credentials, you can retrieve metadata /// about pipelines that you or your IAM users have created. If you are using an IAM user /// account, you can retrieve metadata about only those pipelines for which you have read /// permissions. /// /// /// <para> /// To retrieve the full pipeline definition instead of metadata about the pipeline, call /// <a>GetPipelineDefinition</a>. /// </para> /// </summary> /// <param name="pipelineIds">The IDs of the pipelines to describe. You can pass as many as 25 identifiers in a single call. To obtain pipeline IDs, call <a>ListPipelines</a>.</param> /// /// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso> public virtual DescribePipelinesResponse DescribePipelines(List<string> pipelineIds) { var request = new DescribePipelinesRequest(); request.PipelineIds = pipelineIds; return DescribePipelines(request); } /// <summary> /// Retrieves metadata about one or more pipelines. The information retrieved includes /// the name of the pipeline, the pipeline identifier, its current state, and the user /// account that owns the pipeline. Using account credentials, you can retrieve metadata /// about pipelines that you or your IAM users have created. If you are using an IAM user /// account, you can retrieve metadata about only those pipelines for which you have read /// permissions. /// /// /// <para> /// To retrieve the full pipeline definition instead of metadata about the pipeline, call /// <a>GetPipelineDefinition</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribePipelines service method.</param> /// /// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso> public virtual DescribePipelinesResponse DescribePipelines(DescribePipelinesRequest request) { var marshaller = DescribePipelinesRequestMarshaller.Instance; var unmarshaller = DescribePipelinesResponseUnmarshaller.Instance; return Invoke<DescribePipelinesRequest,DescribePipelinesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Retrieves metadata about one or more pipelines. The information retrieved includes /// the name of the pipeline, the pipeline identifier, its current state, and the user /// account that owns the pipeline. Using account credentials, you can retrieve metadata /// about pipelines that you or your IAM users have created. If you are using an IAM user /// account, you can retrieve metadata about only those pipelines for which you have read /// permissions. /// /// /// <para> /// To retrieve the full pipeline definition instead of metadata about the pipeline, call /// <a>GetPipelineDefinition</a>. /// </para> /// </summary> /// <param name="pipelineIds">The IDs of the pipelines to describe. You can pass as many as 25 identifiers in a single call. To obtain pipeline IDs, call <a>ListPipelines</a>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso> public virtual Task<DescribePipelinesResponse> DescribePipelinesAsync(List<string> pipelineIds, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new DescribePipelinesRequest(); request.PipelineIds = pipelineIds; return DescribePipelinesAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the DescribePipelines operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribePipelines operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">REST API Reference for DescribePipelines Operation</seealso> public virtual Task<DescribePipelinesResponse> DescribePipelinesAsync(DescribePipelinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribePipelinesRequestMarshaller.Instance; var unmarshaller = DescribePipelinesResponseUnmarshaller.Instance; return InvokeAsync<DescribePipelinesRequest,DescribePipelinesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region EvaluateExpression /// <summary> /// Task runners call <code>EvaluateExpression</code> to evaluate a string in the context /// of the specified object. For example, a task runner can evaluate SQL queries stored /// in Amazon S3. /// </summary> /// <param name="request">Container for the necessary parameters to execute the EvaluateExpression service method.</param> /// /// <returns>The response from the EvaluateExpression service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException"> /// The specified task was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">REST API Reference for EvaluateExpression Operation</seealso> public virtual EvaluateExpressionResponse EvaluateExpression(EvaluateExpressionRequest request) { var marshaller = EvaluateExpressionRequestMarshaller.Instance; var unmarshaller = EvaluateExpressionResponseUnmarshaller.Instance; return Invoke<EvaluateExpressionRequest,EvaluateExpressionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the EvaluateExpression operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EvaluateExpression operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">REST API Reference for EvaluateExpression Operation</seealso> public virtual Task<EvaluateExpressionResponse> EvaluateExpressionAsync(EvaluateExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = EvaluateExpressionRequestMarshaller.Instance; var unmarshaller = EvaluateExpressionResponseUnmarshaller.Instance; return InvokeAsync<EvaluateExpressionRequest,EvaluateExpressionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetPipelineDefinition /// <summary> /// Gets the definition of the specified pipeline. You can call <code>GetPipelineDefinition</code> /// to retrieve the pipeline definition that you provided using <a>PutPipelineDefinition</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetPipelineDefinition service method.</param> /// /// <returns>The response from the GetPipelineDefinition service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">REST API Reference for GetPipelineDefinition Operation</seealso> public virtual GetPipelineDefinitionResponse GetPipelineDefinition(GetPipelineDefinitionRequest request) { var marshaller = GetPipelineDefinitionRequestMarshaller.Instance; var unmarshaller = GetPipelineDefinitionResponseUnmarshaller.Instance; return Invoke<GetPipelineDefinitionRequest,GetPipelineDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetPipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">REST API Reference for GetPipelineDefinition Operation</seealso> public virtual Task<GetPipelineDefinitionResponse> GetPipelineDefinitionAsync(GetPipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = GetPipelineDefinitionRequestMarshaller.Instance; var unmarshaller = GetPipelineDefinitionResponseUnmarshaller.Instance; return InvokeAsync<GetPipelineDefinitionRequest,GetPipelineDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListPipelines /// <summary> /// Lists the pipeline identifiers for all active pipelines that you have permission to /// access. /// </summary> /// /// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso> public virtual ListPipelinesResponse ListPipelines() { return ListPipelines(new ListPipelinesRequest()); } /// <summary> /// Lists the pipeline identifiers for all active pipelines that you have permission to /// access. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPipelines service method.</param> /// /// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso> public virtual ListPipelinesResponse ListPipelines(ListPipelinesRequest request) { var marshaller = ListPipelinesRequestMarshaller.Instance; var unmarshaller = ListPipelinesResponseUnmarshaller.Instance; return Invoke<ListPipelinesRequest,ListPipelinesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Lists the pipeline identifiers for all active pipelines that you have permission to /// access. /// </summary> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso> public virtual Task<ListPipelinesResponse> ListPipelinesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListPipelinesAsync(new ListPipelinesRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListPipelines operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPipelines operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">REST API Reference for ListPipelines Operation</seealso> public virtual Task<ListPipelinesResponse> ListPipelinesAsync(ListPipelinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ListPipelinesRequestMarshaller.Instance; var unmarshaller = ListPipelinesResponseUnmarshaller.Instance; return InvokeAsync<ListPipelinesRequest,ListPipelinesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PollForTask /// <summary> /// Task runners call <code>PollForTask</code> to receive a task to perform from AWS Data /// Pipeline. The task runner specifies which tasks it can perform by setting a value /// for the <code>workerGroup</code> parameter. The task returned can come from any of /// the pipelines that match the <code>workerGroup</code> value passed in by the task /// runner and that was launched using the IAM user credentials specified by the task /// runner. /// /// /// <para> /// If tasks are ready in the work queue, <code>PollForTask</code> returns a response /// immediately. If no tasks are available in the queue, <code>PollForTask</code> uses /// long-polling and holds on to a poll connection for up to a 90 seconds, during which /// time the first newly scheduled task is handed to the task runner. To accomodate this, /// set the socket timeout in your task runner to 90 seconds. The task runner should not /// call <code>PollForTask</code> again on the same <code>workerGroup</code> until it /// receives a response, and this can take up to 90 seconds. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PollForTask service method.</param> /// /// <returns>The response from the PollForTask service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException"> /// The specified task was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">REST API Reference for PollForTask Operation</seealso> public virtual PollForTaskResponse PollForTask(PollForTaskRequest request) { var marshaller = PollForTaskRequestMarshaller.Instance; var unmarshaller = PollForTaskResponseUnmarshaller.Instance; return Invoke<PollForTaskRequest,PollForTaskResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PollForTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PollForTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">REST API Reference for PollForTask Operation</seealso> public virtual Task<PollForTaskResponse> PollForTaskAsync(PollForTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = PollForTaskRequestMarshaller.Instance; var unmarshaller = PollForTaskResponseUnmarshaller.Instance; return InvokeAsync<PollForTaskRequest,PollForTaskResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutPipelineDefinition /// <summary> /// Adds tasks, schedules, and preconditions to the specified pipeline. You can use <code>PutPipelineDefinition</code> /// to populate a new pipeline. /// /// /// <para> /// <code>PutPipelineDefinition</code> also validates the configuration as it adds it /// to the pipeline. Changes to the pipeline are saved unless one of the following three /// validation errors exists in the pipeline. /// </para> /// <ol> <li>An object is missing a name or identifier field.</li> <li>A string or reference /// field is empty.</li> <li>The number of objects in the pipeline exceeds the maximum /// allowed objects.</li> <li>The pipeline is in a FINISHED state.</li> </ol> /// <para> /// Pipeline object definitions are passed to the <code>PutPipelineDefinition</code> /// action and returned by the <a>GetPipelineDefinition</a> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutPipelineDefinition service method.</param> /// /// <returns>The response from the PutPipelineDefinition service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">REST API Reference for PutPipelineDefinition Operation</seealso> public virtual PutPipelineDefinitionResponse PutPipelineDefinition(PutPipelineDefinitionRequest request) { var marshaller = PutPipelineDefinitionRequestMarshaller.Instance; var unmarshaller = PutPipelineDefinitionResponseUnmarshaller.Instance; return Invoke<PutPipelineDefinitionRequest,PutPipelineDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutPipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutPipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">REST API Reference for PutPipelineDefinition Operation</seealso> public virtual Task<PutPipelineDefinitionResponse> PutPipelineDefinitionAsync(PutPipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = PutPipelineDefinitionRequestMarshaller.Instance; var unmarshaller = PutPipelineDefinitionResponseUnmarshaller.Instance; return InvokeAsync<PutPipelineDefinitionRequest,PutPipelineDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region QueryObjects /// <summary> /// Queries the specified pipeline for the names of objects that match the specified set /// of conditions. /// </summary> /// <param name="request">Container for the necessary parameters to execute the QueryObjects service method.</param> /// /// <returns>The response from the QueryObjects service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">REST API Reference for QueryObjects Operation</seealso> public virtual QueryObjectsResponse QueryObjects(QueryObjectsRequest request) { var marshaller = QueryObjectsRequestMarshaller.Instance; var unmarshaller = QueryObjectsResponseUnmarshaller.Instance; return Invoke<QueryObjectsRequest,QueryObjectsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the QueryObjects operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the QueryObjects operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">REST API Reference for QueryObjects Operation</seealso> public virtual Task<QueryObjectsResponse> QueryObjectsAsync(QueryObjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = QueryObjectsRequestMarshaller.Instance; var unmarshaller = QueryObjectsResponseUnmarshaller.Instance; return InvokeAsync<QueryObjectsRequest,QueryObjectsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RemoveTags /// <summary> /// Removes existing tags from the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tagKeys">The keys of the tags to remove.</param> /// /// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso> public virtual RemoveTagsResponse RemoveTags(string pipelineId, List<string> tagKeys) { var request = new RemoveTagsRequest(); request.PipelineId = pipelineId; request.TagKeys = tagKeys; return RemoveTags(request); } /// <summary> /// Removes existing tags from the specified pipeline. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RemoveTags service method.</param> /// /// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso> public virtual RemoveTagsResponse RemoveTags(RemoveTagsRequest request) { var marshaller = RemoveTagsRequestMarshaller.Instance; var unmarshaller = RemoveTagsResponseUnmarshaller.Instance; return Invoke<RemoveTagsRequest,RemoveTagsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Removes existing tags from the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tagKeys">The keys of the tags to remove.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso> public virtual Task<RemoveTagsResponse> RemoveTagsAsync(string pipelineId, List<string> tagKeys, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var request = new RemoveTagsRequest(); request.PipelineId = pipelineId; request.TagKeys = tagKeys; return RemoveTagsAsync(request, cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the RemoveTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemoveTags operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">REST API Reference for RemoveTags Operation</seealso> public virtual Task<RemoveTagsResponse> RemoveTagsAsync(RemoveTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = RemoveTagsRequestMarshaller.Instance; var unmarshaller = RemoveTagsResponseUnmarshaller.Instance; return InvokeAsync<RemoveTagsRequest,RemoveTagsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReportTaskProgress /// <summary> /// Task runners call <code>ReportTaskProgress</code> when assigned a task to acknowledge /// that it has the task. If the web service does not receive this acknowledgement within /// 2 minutes, it assigns the task in a subsequent <a>PollForTask</a> call. After this /// initial acknowledgement, the task runner only needs to report progress every 15 minutes /// to maintain its ownership of the task. You can change this reporting time from 15 /// minutes by specifying a <code>reportProgressTimeout</code> field in your pipeline. /// /// /// <para> /// If a task runner does not report its status after 5 minutes, AWS Data Pipeline assumes /// that the task runner is unable to process the task and reassigns the task in a subsequent /// response to <a>PollForTask</a>. Task runners should call <code>ReportTaskProgress</code> /// every 60 seconds. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ReportTaskProgress service method.</param> /// /// <returns>The response from the ReportTaskProgress service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException"> /// The specified task was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">REST API Reference for ReportTaskProgress Operation</seealso> public virtual ReportTaskProgressResponse ReportTaskProgress(ReportTaskProgressRequest request) { var marshaller = ReportTaskProgressRequestMarshaller.Instance; var unmarshaller = ReportTaskProgressResponseUnmarshaller.Instance; return Invoke<ReportTaskProgressRequest,ReportTaskProgressResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReportTaskProgress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReportTaskProgress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">REST API Reference for ReportTaskProgress Operation</seealso> public virtual Task<ReportTaskProgressResponse> ReportTaskProgressAsync(ReportTaskProgressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ReportTaskProgressRequestMarshaller.Instance; var unmarshaller = ReportTaskProgressResponseUnmarshaller.Instance; return InvokeAsync<ReportTaskProgressRequest,ReportTaskProgressResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReportTaskRunnerHeartbeat /// <summary> /// Task runners call <code>ReportTaskRunnerHeartbeat</code> every 15 minutes to indicate /// that they are operational. If the AWS Data Pipeline Task Runner is launched on a resource /// managed by AWS Data Pipeline, the web service can use this call to detect when the /// task runner application has failed and restart a new instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat service method.</param> /// /// <returns>The response from the ReportTaskRunnerHeartbeat service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">REST API Reference for ReportTaskRunnerHeartbeat Operation</seealso> public virtual ReportTaskRunnerHeartbeatResponse ReportTaskRunnerHeartbeat(ReportTaskRunnerHeartbeatRequest request) { var marshaller = ReportTaskRunnerHeartbeatRequestMarshaller.Instance; var unmarshaller = ReportTaskRunnerHeartbeatResponseUnmarshaller.Instance; return Invoke<ReportTaskRunnerHeartbeatRequest,ReportTaskRunnerHeartbeatResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReportTaskRunnerHeartbeat operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">REST API Reference for ReportTaskRunnerHeartbeat Operation</seealso> public virtual Task<ReportTaskRunnerHeartbeatResponse> ReportTaskRunnerHeartbeatAsync(ReportTaskRunnerHeartbeatRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ReportTaskRunnerHeartbeatRequestMarshaller.Instance; var unmarshaller = ReportTaskRunnerHeartbeatResponseUnmarshaller.Instance; return InvokeAsync<ReportTaskRunnerHeartbeatRequest,ReportTaskRunnerHeartbeatResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetStatus /// <summary> /// Requests that the status of the specified physical or logical pipeline objects be /// updated in the specified pipeline. This update might not occur immediately, but is /// eventually consistent. The status that can be set depends on the type of object (for /// example, DataNode or Activity). You cannot perform this operation on <code>FINISHED</code> /// pipelines and attempting to do so returns <code>InvalidRequestException</code>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SetStatus service method.</param> /// /// <returns>The response from the SetStatus service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">REST API Reference for SetStatus Operation</seealso> public virtual SetStatusResponse SetStatus(SetStatusRequest request) { var marshaller = SetStatusRequestMarshaller.Instance; var unmarshaller = SetStatusResponseUnmarshaller.Instance; return Invoke<SetStatusRequest,SetStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">REST API Reference for SetStatus Operation</seealso> public virtual Task<SetStatusResponse> SetStatusAsync(SetStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = SetStatusRequestMarshaller.Instance; var unmarshaller = SetStatusResponseUnmarshaller.Instance; return InvokeAsync<SetStatusRequest,SetStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetTaskStatus /// <summary> /// Task runners call <code>SetTaskStatus</code> to notify AWS Data Pipeline that a task /// is completed and provide information about the final status. A task runner makes this /// call regardless of whether the task was sucessful. A task runner does not need to /// call <code>SetTaskStatus</code> for tasks that are canceled by the web service during /// a call to <a>ReportTaskProgress</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the SetTaskStatus service method.</param> /// /// <returns>The response from the SetTaskStatus service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.TaskNotFoundException"> /// The specified task was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">REST API Reference for SetTaskStatus Operation</seealso> public virtual SetTaskStatusResponse SetTaskStatus(SetTaskStatusRequest request) { var marshaller = SetTaskStatusRequestMarshaller.Instance; var unmarshaller = SetTaskStatusResponseUnmarshaller.Instance; return Invoke<SetTaskStatusRequest,SetTaskStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetTaskStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetTaskStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">REST API Reference for SetTaskStatus Operation</seealso> public virtual Task<SetTaskStatusResponse> SetTaskStatusAsync(SetTaskStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = SetTaskStatusRequestMarshaller.Instance; var unmarshaller = SetTaskStatusResponseUnmarshaller.Instance; return InvokeAsync<SetTaskStatusRequest,SetTaskStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ValidatePipelineDefinition /// <summary> /// Validates the specified pipeline definition to ensure that it is well formed and can /// be run without error. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ValidatePipelineDefinition service method.</param> /// /// <returns>The response from the ValidatePipelineDefinition service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">REST API Reference for ValidatePipelineDefinition Operation</seealso> public virtual ValidatePipelineDefinitionResponse ValidatePipelineDefinition(ValidatePipelineDefinitionRequest request) { var marshaller = ValidatePipelineDefinitionRequestMarshaller.Instance; var unmarshaller = ValidatePipelineDefinitionResponseUnmarshaller.Instance; return Invoke<ValidatePipelineDefinitionRequest,ValidatePipelineDefinitionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ValidatePipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ValidatePipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">REST API Reference for ValidatePipelineDefinition Operation</seealso> public virtual Task<ValidatePipelineDefinitionResponse> ValidatePipelineDefinitionAsync(ValidatePipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ValidatePipelineDefinitionRequestMarshaller.Instance; var unmarshaller = ValidatePipelineDefinitionResponseUnmarshaller.Instance; return InvokeAsync<ValidatePipelineDefinitionRequest,ValidatePipelineDefinitionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
55.933538
221
0.676308
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/DataPipeline/Generated/_bcl45/AmazonDataPipelineClient.cs
90,892
C#
using DCL.Controllers; using DCL.Helpers; using DCL.Models; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; namespace DCL.Components { public class UIContainerStack : UIShape<UIContainerRectReferencesContainer, UIContainerStack.Model> { [System.Serializable] new public class Model : UIShape.Model { public Color color = Color.clear; public StackOrientation stackOrientation = StackOrientation.VERTICAL; public bool adaptWidth = true; public bool adaptHeight = true; public float spacing = 0; } public enum StackOrientation { VERTICAL, HORIZONTAL } public override string referencesContainerPrefabName => "UIContainerRect"; public Dictionary<string, GameObject> stackContainers = new Dictionary<string, GameObject>(); HorizontalOrVerticalLayoutGroup layoutGroup; public UIContainerStack(ParcelScene scene) : base(scene) { } public override void AttachTo(DecentralandEntity entity, System.Type overridenAttachedType = null) { Debug.LogError( "Aborted UIContainerStack attachment to an entity. UIShapes shouldn't be attached to entities."); } public override void DetachFrom(DecentralandEntity entity, System.Type overridenAttachedType = null) { } public override IEnumerator ApplyChanges(string newJson) { referencesContainer.image.color = new Color(model.color.r, model.color.g, model.color.b, model.color.a); if (model.stackOrientation == StackOrientation.VERTICAL && !(layoutGroup is VerticalLayoutGroup)) { Object.DestroyImmediate(layoutGroup, false); layoutGroup = childHookRectTransform.gameObject.AddComponent<VerticalLayoutGroup>(); } else if (model.stackOrientation == StackOrientation.HORIZONTAL && !(layoutGroup is HorizontalLayoutGroup)) { Object.DestroyImmediate(layoutGroup, false); layoutGroup = childHookRectTransform.gameObject.AddComponent<HorizontalLayoutGroup>(); } layoutGroup.childControlHeight = false; layoutGroup.childControlWidth = false; layoutGroup.childForceExpandWidth = false; layoutGroup.childForceExpandHeight = false; layoutGroup.spacing = model.spacing; referencesContainer.sizeFitter.adjustHeight = model.adaptHeight; referencesContainer.sizeFitter.adjustWidth = model.adaptWidth; RefreshAll(); return null; } void RefreshContainerForShape(BaseDisposable updatedComponent) { UIShape childComponent = updatedComponent as UIShape; Assert.IsTrue(childComponent != null, "This should never happen!!!!"); if (childComponent.model.parentComponent != id) { RefreshAll(); return; } GameObject stackContainer = null; if (!stackContainers.ContainsKey(childComponent.id)) { stackContainer = Object.Instantiate(Resources.Load("UIContainerStackChild")) as GameObject; #if UNITY_EDITOR stackContainer.name = "UIContainerStackChild - " + childComponent.id; #endif stackContainers.Add(childComponent.id, stackContainer); int oldSiblingIndex = childComponent.referencesContainer.transform.GetSiblingIndex(); childComponent.referencesContainer.transform.SetParent(stackContainer.transform, false); stackContainer.transform.SetParent(referencesContainer.childHookRectTransform, false); stackContainer.transform.SetSiblingIndex(oldSiblingIndex); } else { stackContainer = stackContainers[childComponent.id]; } RefreshAll(); } public override void OnChildAttached(UIShape parentComponent, UIShape childComponent) { RefreshContainerForShape(childComponent); childComponent.OnAppliedChanges -= RefreshContainerForShape; childComponent.OnAppliedChanges += RefreshContainerForShape; } public override void RefreshDCLLayoutRecursively(bool refreshSize = true, bool refreshAlignmentAndPosition = true) { base.RefreshDCLLayoutRecursively(refreshSize, refreshAlignmentAndPosition); referencesContainer.sizeFitter.RefreshRecursively(); } public override void OnChildDetached(UIShape parentComponent, UIShape childComponent) { if (parentComponent != this) { return; } if (stackContainers.ContainsKey(childComponent.id)) { Object.Destroy(stackContainers[childComponent.id]); stackContainers[childComponent.id].transform.SetParent(null); stackContainers[childComponent.id].name += "- Detached"; stackContainers.Remove(childComponent.id); } childComponent.OnAppliedChanges -= RefreshContainerForShape; RefreshDCLLayout(); } public override void Dispose() { if (referencesContainer != null) Utils.SafeDestroy(referencesContainer.gameObject); base.Dispose(); } } }
36.941176
118
0.636943
[ "Apache-2.0" ]
maraoz/explorer
unity-client/Assets/Scripts/MainScripts/DCL/Components/UI/UIContainer/UIContainerStack.cs
5,652
C#
using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Lambda.SQSEvents; namespace Xerris.DotNet.Core.Aws.Sqs { public abstract class SqsMessageProcessor<T> : IConsumeSqsMessages<T> where T : class { private readonly IConsumeSqsMessages<T> consumer; private readonly IPublishSqsMessages<T> publisher; protected SqsMessageProcessor(IConsumeSqsMessages<T> consumer, IPublishSqsMessages<T> publisher) { this.consumer = consumer; this.publisher = publisher; } public async Task Process(IEnumerable<SQSEvent.SQSMessage> messages) { await consumer.Process(messages); } public async Task SendMessageAsync(T message) { await publisher.SendMessageAsync(message); } public async Task SendMessagesAsync(IEnumerable<T> messages) { await publisher.SendMessagesAsync(messages); } } }
29.787879
104
0.660224
[ "MIT" ]
xerris/Xerris.DotNet.Core.Aws
src/Xerris.DotNet.Core.Aws/Sqs/SqsMessageProcessor.cs
983
C#
/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved * * This source is subject to the Microsoft Permissive License. * Please see the License.txt file for more information. * All other rights reserved. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ using System; using System.Diagnostics; using System.Globalization; namespace HtmlToOpenXml { /// <summary> /// Logging class to trace debugging information during the conversion process. /// </summary> static class Logging { private const string TraceSourceName = "html2openxml"; private static TraceSource traceSource; private static bool enabled; static Logging() { Initialize(); } #region PrintError public static void PrintError(string method, String message) { if (!ValidateSettings(TraceEventType.Error)) return; PrintLine(TraceEventType.Error, 0, "Exception in the " + method + " - " + message); } public static void PrintError(string method, Exception exception) { if (!ValidateSettings(TraceEventType.Error)) return; PrintLine(TraceEventType.Error, 0, "Exception in the " + method + " - " + exception.Message); if (!String.IsNullOrEmpty(exception.StackTrace)) PrintLine(TraceEventType.Error, 0, exception.StackTrace); } #endregion #region PrintVerbose public static void PrintVerbose(string msg) { if (!ValidateSettings(TraceEventType.Verbose)) return; PrintLine(TraceEventType.Verbose, 0, msg); } #endregion // Private Implementation #region Initialize /// <summary> /// Initialize the logger from the app.config. /// </summary> private static void Initialize() { #if NETSTANDARD1_3 || NETSTANDARD2_0 || NETCORE3_1 traceSource = new TraceSource(TraceSourceName); enabled = traceSource.Switch.Level != SourceLevels.Off; #else try { traceSource = new TraceSource(TraceSourceName); enabled = traceSource.Switch.Level != SourceLevels.Off; } catch (System.Configuration.ConfigurationException) { // app.config has an error enabled = false; } if (enabled) { AppDomain appDomain = AppDomain.CurrentDomain; appDomain.DomainUnload += OnDomainUnload; appDomain.ProcessExit += OnDomainUnload; } #endif } #endregion #region PrintLine /// <summary> /// Core method to write in the log. /// </summary> private static void PrintLine(TraceEventType eventType, int id, string msg) { if (!ValidateSettings(eventType)) return; traceSource.TraceEvent(eventType, id, msg); } #endregion #region OnDomainUnload /// <summary> /// Event handler to close properly the trace source when the program is shut down. /// </summary> private static void OnDomainUnload(object sender, EventArgs e) { traceSource.Close(); enabled = false; } #endregion #region ValidateSettings /// <summary> /// Ensure the type of event should be traced, regarding the configuration. /// </summary> private static bool ValidateSettings(TraceEventType traceLevel) { if (!enabled) return false; if (traceSource == null || !traceSource.Switch.ShouldTrace(traceLevel)) return false; return true; } #endregion //____________________________________________________________________ // /// <summary> /// Gets whether the tracing is enabled or not. /// </summary> public static bool On { get { return enabled; } } } }
25.153846
97
0.654179
[ "MIT" ]
Avnio/html2openxml
src/Html2OpenXml/Utilities/Logging.cs
3,926
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.ConfidentialLedger.V20210513Preview { public static class GetLedger { /// <summary> /// Confidential Ledger. Contains the properties of Confidential Ledger Resource. /// </summary> public static Task<GetLedgerResult> InvokeAsync(GetLedgerArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetLedgerResult>("azure-native:confidentialledger/v20210513preview:getLedger", args ?? new GetLedgerArgs(), options.WithVersion()); } public sealed class GetLedgerArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the Confidential Ledger /// </summary> [Input("ledgerName", required: true)] public string LedgerName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetLedgerArgs() { } } [OutputType] public sealed class GetLedgerResult { /// <summary> /// Fully qualified resource Id for the resource. /// </summary> public readonly string Id; /// <summary> /// The Azure location where the Confidential Ledger is running. /// </summary> public readonly string? Location; /// <summary> /// Name of the Resource. /// </summary> public readonly string Name; /// <summary> /// Properties of Confidential Ledger Resource. /// </summary> public readonly Outputs.LedgerPropertiesResponse Properties; /// <summary> /// Metadata pertaining to creation and last modification of the resource /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Additional tags for Confidential Ledger /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// The type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private GetLedgerResult( string id, string? location, string name, Outputs.LedgerPropertiesResponse properties, Outputs.SystemDataResponse systemData, ImmutableDictionary<string, string>? tags, string type) { Id = id; Location = location; Name = name; Properties = properties; SystemData = systemData; Tags = tags; Type = type; } } }
30.49
185
0.596917
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ConfidentialLedger/V20210513Preview/GetLedger.cs
3,049
C#
using AgendaContatos.Models; using System.Collections.Generic; using System.Web.Mvc; namespace AgendaContatos.Controllers { public class ContatosController : Controller { // GET: Contatos/AdicionarContato public ActionResult AdicionarContato() { var contato = new Contato(); return View(contato); } // GET: Contatos/RemoverContato public ActionResult RemoverContato() { var contato = new Contato(); return View(contato); } // GET: Contatos/EditarContato public ActionResult EditarContato() { var contato = new Contato(); return View(contato); } // GET: Contatos/ListarContatos public ActionResult ListarContatos() { var contatos = GetContatos(); return View(contatos); } private IEnumerable<Contato> GetContatos() { return new List<Contato> { new Contato {Id = 1, Nome = "Roberto", Numero = "35997054048"}, new Contato {Id = 2, Nome = "Felipe", Numero = "35998003141"} }; } } }
26.326087
79
0.546656
[ "Apache-2.0" ]
MSavioti/Estudo-AgendaContatos
AgendaContatos/Controllers/ContatosController.cs
1,213
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.CSharp { internal sealed class NameofBinder : Binder { private readonly SyntaxNode _nameofArgument; public NameofBinder(SyntaxNode nameofArgument, Binder next) : base(next) { _nameofArgument = nameofArgument; } protected override SyntaxNode EnclosingNameofArgument => _nameofArgument; } }
32.411765
161
0.709619
[ "Apache-2.0" ]
0x53A/roslyn
src/Compilers/CSharp/Portable/Binder/NameofBinder.cs
553
C#
using System; using System.Collections.Generic; using Reloaded.Messaging.Interfaces; namespace Reloaded.Messaging { /// <summary> /// Class which provides, client-side the ability to override serializers and compressors for specified types. /// Use either for testing or benchmarking. /// </summary> public static class Overrides { public static Dictionary<Type, ISerializer> SerializerOverride { get; } = new Dictionary<Type, ISerializer>(); public static Dictionary<Type, ICompressor> CompressorOverride { get; } = new Dictionary<Type, ICompressor>(); } }
35.588235
118
0.715702
[ "MIT" ]
Reloaded-Project/Reloaded.Messaging
Source/Reloaded.Messaging/Overrides.cs
607
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.Cdn.AfdHelpers; using Microsoft.Azure.Commands.Cdn.AfdModels; using Microsoft.Azure.Commands.Cdn.Common; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Cdn; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using System.Management.Automation; namespace Microsoft.Azure.Commands.Cdn.AfdProfile { [Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "AfdProfile", DefaultParameterSetName = FieldsParameterSet, SupportsShouldProcess = true), OutputType(typeof(bool))] public class RemoveAzAfdProfile : AzureCdnCmdletBase { [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = HelpMessageConstants.AfdProfileObject, ParameterSetName = ObjectParameterSet)] [ValidateNotNull] public PSAfdProfile Profile { get; set; } [Parameter(Mandatory = true, HelpMessage = HelpMessageConstants.AfdProfileName, ParameterSetName = FieldsParameterSet)] public string ProfileName { get; set; } [Parameter(Mandatory = true, HelpMessage = HelpMessageConstants.ResourceGroupName, ParameterSetName = FieldsParameterSet)] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter(Mandatory = true, HelpMessage = HelpMessageConstants.ResourceId, ParameterSetName = ResourceIdParameterSet)] public string ResourceId { get; set; } [Parameter(Mandatory = false)] public SwitchParameter PassThru { get; set; } public override void ExecuteCmdlet() { // when using FieldsParameterSet, this.ProfileName and this.ResourceGroupName are provided // Hence no need for a FieldsParamterSet case switch(ParameterSetName) { case ObjectParameterSet: this.ObjectParameterSetCmdlet(); break; case ResourceIdParameterSet: this.ResourceIdParameterSetCmdlet(); break; } ConfirmAction(AfdResourceProcessMessage.AfdProfileDeleteMessage, this.ProfileName, this.DeleteAfdProfile); } private void DeleteAfdProfile() { try { PSAfdProfile profile = this.CdnManagementClient.Profiles.Get(this.ResourceGroupName, this.ProfileName).ToPSAfdProfile(); if (!AfdUtilities.IsAfdProfile(profile)) { throw new PSArgumentException($"You are attempting to delete a {profile.Sku} profile. Please use Remove-AzCdnProfile instead."); } this.CdnManagementClient.Profiles.Delete(this.ResourceGroupName, this.ProfileName); } catch (Microsoft.Azure.Management.Cdn.Models.AfdErrorResponseException errorResponseException) { throw new PSArgumentException(errorResponseException.Response.Content); } if(this.PassThru.IsPresent) { WriteObject(true); } } private void ObjectParameterSetCmdlet() { ResourceIdentifier parsedAfdProfileResourceId = new ResourceIdentifier(this.Profile.Id); this.ProfileName = parsedAfdProfileResourceId.ResourceName; this.ResourceGroupName = parsedAfdProfileResourceId.ResourceGroupName; } private void ResourceIdParameterSetCmdlet() { ResourceIdentifier parsedAfdProfileResourceId = new ResourceIdentifier(this.ResourceId); this.ProfileName = parsedAfdProfileResourceId.ResourceName; this.ResourceGroupName = parsedAfdProfileResourceId.ResourceGroupName; } } }
45.656863
195
0.648701
[ "MIT" ]
BurgerZ/azure-powershell
src/Cdn/Cdn/AfdProfile/RemoveAzAfdProfile.cs
4,558
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved. * */ #endregion namespace Krypton.Toolkit { /// <summary> /// Implementation for the fixed close button for krypton form. /// </summary> public class ButtonSpecFormWindowClose : ButtonSpecFormFixed { #region Identity /// <summary> /// Initialize a new instance of the ButtonSpecFormWindowClose class. /// </summary> /// <param name="form">Reference to owning krypton form instance.</param> public ButtonSpecFormWindowClose(KryptonForm form) : base(form, PaletteButtonSpecStyle.FormClose) { } #endregion #region IButtonSpecValues /// <summary> /// Gets the button visible value. /// </summary> /// <param name="palette">Palette to use for inheriting values.</param> /// <returns>Button visibility.</returns> public override bool GetVisible(IPalette palette) { // We do not show if the custom chrome is combined with composition, // in which case the form buttons are handled by the composition if (KryptonForm.ApplyComposition && KryptonForm.ApplyCustomChrome) { return false; } // Have all buttons been turned off? return KryptonForm.ControlBox; } /// <summary> /// Gets the button enabled state. /// </summary> /// <param name="palette">Palette to use for inheriting values.</param> /// <returns>Button enabled state.</returns> public override ButtonEnabled GetEnabled(IPalette palette) => ButtonEnabled.True; /// <summary> /// Gets the button checked state. /// </summary> /// <param name="palette">Palette to use for inheriting values.</param> /// <returns>Button checked state.</returns> public override ButtonCheckState GetChecked(IPalette palette) => // Close button is never shown as checked ButtonCheckState.NotCheckButton; #endregion #region Protected Overrides /// <summary> /// Raises the Click event. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnClick(EventArgs e) { // Only if associated view is enabled to we perform an action if (GetViewEnabled()) { // If we do not provide an inert form if (!KryptonForm.InertForm) { // Only if the mouse is still within the button bounds do we perform action MouseEventArgs mea = (MouseEventArgs)e; if (GetView().ClientRectangle.Contains(mea.Location)) { PropertyInfo pi = typeof(Form).GetProperty("CloseReason", BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.NonPublic); // Update form with the reason for the close pi.SetValue(KryptonForm, CloseReason.UserClosing, null); // Convert screen position to LPARAM format of WM_SYSCOMMAND message Point screenPos = Control.MousePosition; IntPtr lParam = (IntPtr)(PI.MAKELOWORD(screenPos.X) | PI.MAKEHIWORD(screenPos.Y)); // Request the form be closed down KryptonForm.SendSysCommand(PI.SC_.CLOSE, lParam); // Let base class fire any other attached events base.OnClick(e); } } } } #endregion } }
39.873874
119
0.546317
[ "BSD-3-Clause" ]
Krypton-Suite/Standard-Toolkit
Source/Krypton Components/Krypton.Toolkit/ButtonSpec/ButtonSpecFormWindowClose.cs
4,429
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System; using System.Diagnostics.Contracts; using Sportradar.OddsFeed.SDK.Common.Internal; using Sportradar.OddsFeed.SDK.Entities.REST.Internal.DTO; using Sportradar.OddsFeed.SDK.Entities.REST.Internal.Mapping; using Sportradar.OddsFeed.SDK.Messages.Internal.REST; namespace Sportradar.OddsFeed.SDK.Entities.REST.Internal { /// <summary> /// A <see cref="IDataProvider{ISportEventsSchedule}"/> used to retrieve sport events scheduled for a specified date /// or currently live sport events /// </summary> /// <seealso cref="DataProvider{scheduleType, EntityList}" /> /// <seealso cref="IDataProvider{EntityList}" /> public class DateScheduleProvider : DataProvider<scheduleEndpoint, EntityList<SportEventSummaryDTO>> { /// <summary> /// An address format used to retrieve live sport events /// </summary> private readonly string _liveScheduleUriFormat; /// <summary> /// Initializes a new instance of the <see cref="DateScheduleProvider"/> class. /// </summary> /// <param name="liveScheduleUriFormat">An address format used to retrieve live sport events</param> /// <param name="dateScheduleUriFormat">An address format used to retrieve sport events for a specified date</param> /// <param name="fetcher">A <see cref="IDataFetcher" /> used to fetch the data</param> /// <param name="deserializer">A <see cref="IDeserializer{scheduleType}" /> used to deserialize the fetch data</param> /// <param name="mapperFactory">A <see cref="ISingleTypeMapperFactory{scheduleType, EntityList}" /> used to construct instances of <see cref="ISingleTypeMapper{ISportEventsSchedule}" /></param> public DateScheduleProvider( string liveScheduleUriFormat, string dateScheduleUriFormat, IDataFetcher fetcher, IDeserializer<scheduleEndpoint> deserializer, ISingleTypeMapperFactory<scheduleEndpoint, EntityList<SportEventSummaryDTO>> mapperFactory) :base(dateScheduleUriFormat, fetcher, deserializer, mapperFactory) { Contract.Requires(!string.IsNullOrEmpty(liveScheduleUriFormat)); Contract.Requires(!string.IsNullOrWhiteSpace(dateScheduleUriFormat)); Contract.Requires(fetcher != null); Contract.Requires(deserializer != null); Contract.Requires(mapperFactory != null); _liveScheduleUriFormat = liveScheduleUriFormat; } /// <summary> /// Defines object invariants used by the code contracts /// </summary> [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(!string.IsNullOrWhiteSpace(_liveScheduleUriFormat)); } /// <summary> /// Constructs and returns an <see cref="Uri"/> instance used to retrieve resource with specified <code>id</code> /// </summary> /// <param name="identifiers">Identifiers uniquely identifying the data to fetch</param> /// <returns>an <see cref="Uri"/> instance used to retrieve resource with specified <code>identifiers</code></returns> protected override Uri GetRequestUri(params object[] identifiers) { return identifiers.Length == 1 ? new Uri(string.Format(_liveScheduleUriFormat, identifiers)) : base.GetRequestUri(identifiers); } } }
47.333333
201
0.677465
[ "Apache-2.0" ]
Furti87/UnifiedOddsSdkNet
src/Sportradar.OddsFeed.SDK.Entities.REST/Internal/DateScheduleProvider.cs
3,552
C#
using Quaver.Server.Common.Objects.Multiplayer; using Quaver.Shared.Online; using Wobble.Graphics; namespace Quaver.Shared.Screens.Result.UI.Multiplayer { public class ResultMultiplayerContainer : Container { /// <summary> /// </summary> private ResultScreen Screen { get; } /// <summary> /// </summary> private ResultMultiplayerScoreboard Scoreboard { get; } /// <summary> /// </summary> private ResultMultiplayerTeamPanel TeamPanel { get; } /// <summary> /// </summary> /// <param name="screen"></param> public ResultMultiplayerContainer(ResultScreen screen) { Screen = screen; if (OnlineManager.CurrentGame.Ruleset == MultiplayerGameRuleset.Team) { TeamPanel = new ResultMultiplayerTeamPanel(screen) { Parent = this, Alignment = Alignment.TopCenter, Y = 208 }; } Scoreboard = new ResultMultiplayerScoreboard(screen.MultiplayerScores) { Parent = this, Alignment = Alignment.TopCenter, Y = 212 }; if (TeamPanel != null) Scoreboard.Y = TeamPanel.Y + TeamPanel.Height + 16; } } }
28.265306
82
0.530686
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Adrriii/Quaver
Quaver.Shared/Screens/Result/UI/Multiplayer/ResultMultiplayerContainer.cs
1,385
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Assertions; namespace ViewerOption { public enum EyeOption { Left, Right, Both }; public enum HandOption { Right, Left }; } public class ViewerOptionSelector : MonoBehaviour { public string[] handednessString; public string[] viewingEyeString; public SphereeTrackerCalibrationTransformer trackerTransformerController; public FlyingClawController clawController; public Dropdown handednessDropdown; public Dropdown viewingEyeDropdown; void Start() { setupDropdown(handednessDropdown, handednessString); setupDropdown(viewingEyeDropdown, viewingEyeString); handednessDropdown.onValueChanged.AddListener(delegate { OnHandDropdownChange(); }); viewingEyeDropdown.onValueChanged.AddListener(delegate { OnEyeDropdownChange(); }); OnEyeDropdownChange(); //default OnHandDropdownChange(); //default } void Destroy() { handednessDropdown.onValueChanged.RemoveAllListeners(); viewingEyeDropdown.onValueChanged.RemoveAllListeners(); } public ViewerOption.EyeOption eyeOption { get { return eyeoption; } set { eyeoption = value; } } public ViewerOption.HandOption handOption { get { return handoption; } set { handoption = value; } } private ViewerOption.EyeOption eyeoption; private ViewerOption.HandOption handoption; private void setupDropdown(Dropdown dropdown, string[] dd_names) { Assert.IsNotNull(dropdown, "Scene dropdown cannot be null. Please specify an object in the Editor."); dropdown.ClearOptions(); dropdown.AddOptions(new List<string>(dd_names)); dropdown.RefreshShownValue(); } public void OnEyeDropdownChange() { eyeOption = (ViewerOption.EyeOption)viewingEyeDropdown.value; trackerTransformerController.setOffSet(eyeOption); Debug.logger.Log(string.Format("<t><time>{0}</time>\r\n<eye>{1}</eye></t>", Time.time.ToString("F3"), Enum.GetName(typeof(ViewerOption.EyeOption), eyeOption))); } public void OnHandDropdownChange() { handOption = (ViewerOption.HandOption)handednessDropdown.value; clawController.setHandedOption(handOption); Debug.logger.Log(string.Format("<t><time>{0}</time>\r\n<hand>{1}</hand></t>", Time.time.ToString("F3"), Enum.GetName(typeof(ViewerOption.HandOption), handOption))); } }
29.655556
109
0.675909
[ "MIT" ]
GeometricFishTankVR/ViewpointCalibration
Unity_Projects/cubee-user-calibration/Assets/Spheree/Scripts/ViewerOptionSelector.cs
2,671
C#