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 |
|---|---|---|---|---|---|---|---|---|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataBox.V20180101.Outputs
{
[OutputType]
public sealed class DataBoxHeavyAccountCopyLogDetailsResponse
{
/// <summary>
/// Destination account name.
/// </summary>
public readonly string AccountName;
/// <summary>
/// Indicates the type of job details.
/// Expected value is 'DataBoxHeavy'.
/// </summary>
public readonly string CopyLogDetailsType;
/// <summary>
/// Link for copy logs.
/// </summary>
public readonly ImmutableArray<string> CopyLogLink;
[OutputConstructor]
private DataBoxHeavyAccountCopyLogDetailsResponse(
string accountName,
string copyLogDetailsType,
ImmutableArray<string> copyLogLink)
{
AccountName = accountName;
CopyLogDetailsType = copyLogDetailsType;
CopyLogLink = copyLogLink;
}
}
}
| 28.818182 | 81 | 0.637224 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataBox/V20180101/Outputs/DataBoxHeavyAccountCopyLogDetailsResponse.cs | 1,268 | C# |
using System;
using System.Runtime.Serialization;
namespace Jumpcutter_dot_net
{
[Serializable]
public class JCException : Exception
{
public JCException()
{
}
public JCException(string message) : base(message)
{
}
public JCException(string message, Exception innerException) : base(message, innerException)
{
}
protected JCException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} | 21.2 | 101 | 0.616981 | [
"MIT"
] | mt025/jumpcutter | Jumpcutter_dot_net/JCException.cs | 532 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PinballX.Table2RomMapping
{
/// <summary>
/// Simple class containing the mappinging between tablename and romname
/// </summary>
public class Mapping
{
/// <summary>
/// Gets or sets the name of the table.
/// This is not necessarly the same as the name of the table file. Use fuzzy text matching to find the right TableName.
/// </summary>
/// <value>
/// The name of the table.
/// </value>
public string TableName { get; set; }
/// <summary>
/// Gets or sets the name of the rom of the table. Typically the property will contain the short romname of the table (same as in the ini files).
/// </summary>
/// <value>
/// The name of the rom.
/// </value>
public string RomName { get; set; }
}
}
| 32.689655 | 154 | 0.570675 | [
"MIT"
] | Ashram56/DirectOutput | DirectOutput PinballX Plugin/Table2RomMapping/Mapping.cs | 950 | C# |
namespace EditorsLibrary
{
partial class BXDAEditorPane
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.FullRowSelect = true;
this.treeView1.HideSelection = false;
this.treeView1.LineColor = System.Drawing.Color.DarkSlateGray;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(800, 723);
this.treeView1.TabIndex = 0;
this.treeView1.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseDoubleClick);
//
// BXDAEditorPane
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
this.Controls.Add(this.treeView1);
this.Name = "BXDAEditorPane";
this.Size = new System.Drawing.Size(800, 723);
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.TreeView treeView1;
}
}
| 36.31746 | 144 | 0.586538 | [
"Apache-2.0"
] | NWalker1208/synthesis | exporters/robot_exporter/EditorsLibrary/BXDAEditorPane.Designer.cs | 2,290 | C# |
using System.Runtime.Serialization;
namespace Service.Liquidity.ConverterMarkups.Grpc.Models
{
[DataContract]
public class UpsertMarkupSettingsResponse
{
[DataMember(Order = 1)] public bool Success { get; set; }
[DataMember(Order = 2)] public string ErrorMessage { get; set; }
}
} | 28.454545 | 72 | 0.696486 | [
"MIT"
] | MyJetWallet/Service.Liquidity.ConverterMarkups | src/Service.Liquidity.ConverterMarkups.Grpc/Models/UpsertMarkupSettingsResponse.cs | 313 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Hl7.Fhir.Model;
using Microsoft.Health.Fhir.Tests.Common;
using Microsoft.Health.Fhir.Tests.Common.FixtureParameters;
using Microsoft.Health.Fhir.Tests.E2E.Common;
using Microsoft.Health.Fhir.Web;
using Xunit;
using FhirClient = Microsoft.Health.Fhir.Tests.E2E.Common.FhirClient;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Health.Fhir.Tests.E2E.Rest
{
/// <summary>
/// NOTE: These tests will fail if security is disabled..
/// </summary>
[Trait(Traits.Category, Categories.Authorization)]
[HttpIntegrationFixtureArgumentSets(DataStore.CosmosDb, Format.Json)]
public class BasicAuthTests : IClassFixture<HttpIntegrationTestFixture<Startup>>
{
private const string ForbiddenMessage = "Forbidden: Authorization failed.";
private const string UnauthorizedMessage = "Unauthorized: Authentication failed.";
private const string Invalidtoken = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImNmNWRmMGExNzY5ZWIzZTFkOGRiNWIxMGZiOWY3ZTk0IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NDQ2ODQ1NzEsImV4cCI6MTU0NDY4ODE3MSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNDgiLCJhdWQiOlsiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNDgvcmVzb3VyY2VzIiwiZmhpci1haSJdLCJjbGllbnRfaWQiOiJzZXJ2aWNlY2xpZW50Iiwicm9sZXMiOiJhZG1pbiIsImFwcGlkIjoic2VydmljZWNsaWVudCIsInNjb3BlIjpbImZoaXItYWkiXX0.SKSvy6Jxzwsv1ZSi0PO4Pdq6QDZ6mBJIRxUPgoPlz2JpiB6GMXu5u0n1IpS6zOXihGkGhegjtcqj-6TKE6Ou5uhQ0VTnmf-NxcYKFl48aDihcGem--qa2V8GC7na549Ctj1PLXoYUbovV4LB27Kj3X83sZVnWdHqg_G0AKo4xm7hr23VUvJ1D73lEcYaGd5K9GXHNgUrJO5v288y0uCXZ5ByNDJ-K6Xi7_68dLdshlIiHaeIBuC3rhchSf2hdglkQgOyo4g4gT_HfKjwdrrpGzepNXOPQEwtUs_o2uriXAd7FfbL_Q4ORiDWPXkmwBXqo7uUfg-2SnT3DApc3PuA0";
public BasicAuthTests(HttpIntegrationTestFixture<Startup> fixture)
{
Client = fixture.FhirClient;
}
protected FhirClient Client { get; set; }
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenGettingAResource_GivenAUserWithNoReadPermissions_TheServerShouldReturnForbidden()
{
await Client.RunAsClientApplication(TestApplications.ServiceClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
await Client.RunAsUser(TestUsers.WriteOnlyUser, TestApplications.NativeClient);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.ReadAsync<Observation>(ResourceType.Observation, createdResource.Id));
Assert.Equal(ForbiddenMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Forbidden, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenCreatingAResource_GivenAUserWithNoCreatePermissions_TheServerShouldReturnForbidden()
{
await Client.RunAsUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.CreateAsync(Samples.GetDefaultObservation()));
Assert.Equal(ForbiddenMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Forbidden, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenUpdatingAResource_GivenAUserWithNoWritePermissions_TheServerShouldReturnForbidden()
{
await Client.RunAsUser(TestUsers.WriteOnlyUser, TestApplications.NativeClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
await Client.RunAsUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.UpdateAsync(createdResource));
Assert.Equal(ForbiddenMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Forbidden, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenHardDeletingAResource_GivenAUserWithNoHardDeletePermissions_TheServerShouldReturnForbidden()
{
await Client.RunAsUser(TestUsers.WriteOnlyUser, TestApplications.NativeClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.HardDeleteAsync(createdResource));
Assert.Equal(ForbiddenMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Forbidden, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenHardDeletingAResource_GivenAUserWithHardDeletePermissions_TheServerShouldReturnSuccess()
{
await Client.RunAsUser(TestUsers.WriteOnlyUser, TestApplications.NativeClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
await Client.RunAsUser(TestUsers.HardDeleteUser, TestApplications.NativeClient);
// Hard-delete the resource.
await Client.HardDeleteAsync(createdResource);
await Client.RunAsUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient);
// Getting the resource should result in NotFound.
await ExecuteAndValidateNotFoundStatus(() => Client.ReadAsync<Observation>(ResourceType.Observation, createdResource.Id));
async Task<FhirException> ExecuteAndValidateNotFoundStatus(Func<Task> action)
{
FhirException exception = await Assert.ThrowsAsync<FhirException>(action);
Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
return exception;
}
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenUpdatingAResource_GivenAUserWithUpdatePermissions_TheServerShouldReturnSuccess()
{
await Client.RunAsUser(TestUsers.AdminUser, TestApplications.NativeClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
await Client.RunAsUser(TestUsers.ReadWriteUser, TestApplications.NativeClient);
FhirResponse<Observation> updateResponse = await Client.UpdateAsync(createdResource);
Assert.Equal(System.Net.HttpStatusCode.OK, updateResponse.StatusCode);
Observation updatedResource = updateResponse.Resource;
Assert.NotNull(updatedResource);
Assert.Equal(createdResource.Id, updatedResource.Id);
Assert.NotEqual(createdResource.Meta.VersionId, updatedResource.Meta.VersionId);
Assert.NotEqual(createdResource.Meta.LastUpdated, updatedResource.Meta.LastUpdated);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenCreatingAResource_GivenAClientWithNoAuthToken_TheServerShouldReturnUnauthorized()
{
await Client.RunAsClientApplication(TestApplications.InvalidClient);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.CreateAsync(Samples.GetDefaultObservation()));
Assert.Equal(UnauthorizedMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Unauthorized, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenCreatingAResource_GivenAClientWithInvalidAuthToken_TheServerShouldReturnUnauthorized()
{
await Client.RunAsClientApplication(TestApplications.InvalidClient);
Client.HttpClient.SetBearerToken(Invalidtoken);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.CreateAsync(Samples.GetDefaultObservation()));
Assert.Equal(UnauthorizedMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Unauthorized, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenCreatingAResource_GivenAClientWithWrongAudience_TheServerShouldReturnUnauthorized()
{
await Client.RunAsClientApplication(TestApplications.WrongAudienceClient);
FhirException fhirException = await Assert.ThrowsAsync<FhirException>(async () => await Client.CreateAsync(Samples.GetDefaultObservation()));
Assert.Equal(UnauthorizedMessage, fhirException.Message);
Assert.Equal(HttpStatusCode.Unauthorized, fhirException.StatusCode);
}
[Fact]
[Trait(Traits.Priority, Priority.One)]
public async Task WhenGettingAResource_GivenAUserWithReadPermissions_TheServerShouldReturnSuccess()
{
await Client.RunAsClientApplication(TestApplications.ServiceClient);
Observation createdResource = await Client.CreateAsync(Samples.GetDefaultObservation());
await Client.RunAsUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient);
FhirResponse<Observation> readResponse = await Client.ReadAsync<Observation>(ResourceType.Observation, createdResource.Id);
Observation readResource = readResponse.Resource;
Assert.Equal(createdResource.Id, readResource.Id);
Assert.Equal(createdResource.Meta.VersionId, readResource.Meta.VersionId);
Assert.Equal(createdResource.Meta.LastUpdated, readResource.Meta.LastUpdated);
}
}
}
| 55.274725 | 760 | 0.726839 | [
"MIT"
] | javier-alvarez/fhir-server | test/Microsoft.Health.Fhir.Tests.E2E/Rest/BasicAuthTests.cs | 10,062 | C# |
using System.Reflection;
using MongoDB.Configuration.Builders;
namespace System
{
internal static class MongoBuilder
{
private static readonly MethodInfo _mapMethod = typeof(MappingStoreBuilder).GetMethod("Map", Type.EmptyTypes);
public static void MapType(Type type, MappingStoreBuilder mapping)
{
_mapMethod.MakeGenericMethod(type)
.Invoke(mapping, new object[] { });
}
}
} | 30.866667 | 119 | 0.652268 | [
"Apache-2.0",
"MIT"
] | Grimace1975/bclcontrib | Core/Quality/System.Core.Quality_Mongo/MongoBuilder.cs | 465 | C# |
using AspectInjector.Broker;
using AspectInjector.Rules;
using FluentIL;
using FluentIL.Extensions;
using FluentIL.Logging;
using Mono.Cecil;
using System.Collections.Generic;
using System.Linq;
namespace AspectInjector.Core.Models
{
public class AspectDefinition
{
private MethodDefinition _factoryMethod;
public TypeDefinition Host { get; set; }
public List<Effect> Effects { get; set; }
public Scope Scope { get; set; }
public TypeReference Factory { get; set; }
public MethodReference GetFactoryMethod()
{
if (_factoryMethod == null)
{
if (Factory != null)
{
_factoryMethod = Factory.Resolve().Methods.FirstOrDefault(m =>
m.IsStatic && m.IsPublic
&& m.Name == Constants.AspectFactoryMethodName
&& m.ReturnType.Match(StandardTypes.Object)
&& m.Parameters.Count == 1 && m.Parameters[0].ParameterType.Match(StandardTypes.Type)
);
}
else
_factoryMethod = Host.Methods.FirstOrDefault(m => m.IsConstructor && !m.IsStatic && m.IsPublic && !m.HasParameters);
}
return _factoryMethod;
}
public bool Validate(ILogger log)
{
var result = true;
if (Scope != Scope.Global && Scope != Scope.PerInstance)
log.Log(GeneralRules.UnknownCompilationOption, Host, GeneralRules.Literals.UnknownAspectScope(Scope.ToString()));
if (!Effects.Any())
log.Log(AspectRules.AspectShouldContainEffect, Host, Host.Name);
if (Host.HasGenericParameters)
{
log.Log(AspectRules.AspectMustHaveValidSignature, Host, Host.Name, AspectRules.Literals.HasGenericParams);
result = false;
}
if (!Host.IsPublic && !Host.IsNestedPublic)
{
log.Log(AspectRules.AspectMustHaveValidSignature, Host, Host.Name, AspectRules.Literals.IsNotPublic);
result = false;
}
if (Host.IsAbstract)
{
if (Host.IsSealed)
log.Log(AspectRules.AspectMustHaveValidSignature, Host, Host.Name, AspectRules.Literals.IsStatic);
else
log.Log(AspectRules.AspectMustHaveValidSignature, Host, Host.Name, AspectRules.Literals.IsAbstract);
result = false;
}
if (GetFactoryMethod() == null)
{
if (Factory != null)
log.Log(AspectRules.AspectFactoryMustContainFactoryMethod, Host, Factory.Name);
else
log.Log(AspectRules.AspectMustHaveContructorOrFactory, Host, Host.Name);
result = false;
}
var effectsValid = Effects.All(e => e.Validate(this, log));
return result && effectsValid;
}
}
} | 33.659341 | 136 | 0.561867 | [
"Apache-2.0"
] | stevenknox/aspect-injector | src/AspectInjector.Core/Models/AspectDefinition.cs | 3,065 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Network.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VirtualNetworkGatewaysOperations.
/// </summary>
public static partial class VirtualNetworkGatewaysOperationsExtensions
{
/// <summary>
/// Creates or updates a virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> CreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGatewayInner parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified virtual network gateway by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> GetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates a virtual network gateway tags.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='tags'>
/// Resource tags.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> UpdateTagsAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateTagsWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayInner>> ListAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayConnectionListEntityInner>> ListConnectionsAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListConnectionsWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Resets the primary of the virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of the
/// active-active feature enabled gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> ResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Resets the VPN client shared key of the virtual network gateway in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ResetVpnClientSharedKeyAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ResetVpnClientSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Generates VPN client package for P2S client of the virtual network gateway
/// in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN client
/// package operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> GeneratevpnclientpackageAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway in the
/// specified resource group. Used for IKEV2 and radius based authentication.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN client
/// package operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> GenerateVpnProfileAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GenerateVpnProfileWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual network
/// gateway in the specified resource group. The profile needs to be generated
/// first using generateVpnProfile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> GetVpnProfilePackageUrlAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVpnProfilePackageUrlWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP peers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BgpPeerStatusListResultInner> GetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a xml format representation for supported vpn devices.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> SupportedVpnDevicesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SupportedVpnDevicesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// This operation retrieves a list of routes the virtual network gateway has
/// learned, including routes learned from BGP peers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayRouteListResultInner> GetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// This operation retrieves a list of routes the virtual network gateway is
/// advertising to the specified peer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayRouteListResultInner> GetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy
/// for P2S client of virtual network gateway in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='vpnclientIpsecParams'>
/// Parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual
/// Network Gateway P2S client operation through Network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientIPsecParametersInner> SetVpnclientIpsecParametersAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SetVpnclientIpsecParametersWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Get VpnclientIpsecParameters operation retrieves information about the
/// vpnclient ipsec policy for P2S client of virtual network gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The virtual network gateway name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientIPsecParametersInner> GetVpnclientIpsecParametersAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVpnclientIpsecParametersWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a xml format representation for vpn device configuration script.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection for which the
/// configuration script is generated.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate vpn device script operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> VpnDeviceConfigurationScriptAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.VpnDeviceConfigurationScriptWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Starts packet capture on virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='filterData'>
/// Start Packet capture parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> StartPacketCaptureAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string filterData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StartPacketCaptureWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, filterData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops packet capture on virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='sasUrl'>
/// SAS url for packet capture on virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> StopPacketCaptureAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string sasUrl = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.StopPacketCaptureWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, sasUrl, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get VPN client connection health detail per P2S client connection of the
/// virtual network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientConnectionHealthDetailListResultInner> GetVpnclientConnectionHealthAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVpnclientConnectionHealthWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGatewayInner parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates a virtual network gateway tags.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='tags'>
/// Resource tags.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> BeginUpdateTagsAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, IDictionary<string, string> tags = default(IDictionary<string, string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateTagsWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Resets the primary of the virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of the
/// active-active feature enabled gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayInner> BeginResetAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginResetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, gatewayVip, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Resets the VPN client shared key of the virtual network gateway in the
/// specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginResetVpnClientSharedKeyAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginResetVpnClientSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Generates VPN client package for P2S client of the virtual network gateway
/// in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN client
/// package operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> BeginGeneratevpnclientpackageAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGeneratevpnclientpackageWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway in the
/// specified resource group. Used for IKEV2 and radius based authentication.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN client
/// package operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> BeginGenerateVpnProfileAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGenerateVpnProfileWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual network
/// gateway in the specified resource group. The profile needs to be generated
/// first using generateVpnProfile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> BeginGetVpnProfilePackageUrlAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetVpnProfilePackageUrlWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP peers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<BgpPeerStatusListResultInner> BeginGetBgpPeerStatusAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetBgpPeerStatusWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// This operation retrieves a list of routes the virtual network gateway has
/// learned, including routes learned from BGP peers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayRouteListResultInner> BeginGetLearnedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetLearnedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// This operation retrieves a list of routes the virtual network gateway is
/// advertising to the specified peer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayRouteListResultInner> BeginGetAdvertisedRoutesAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string peer, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetAdvertisedRoutesWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, peer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy
/// for P2S client of virtual network gateway in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='vpnclientIpsecParams'>
/// Parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual
/// Network Gateway P2S client operation through Network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientIPsecParametersInner> BeginSetVpnclientIpsecParametersAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginSetVpnclientIpsecParametersWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Get VpnclientIpsecParameters operation retrieves information about the
/// vpnclient ipsec policy for P2S client of virtual network gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The virtual network gateway name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientIPsecParametersInner> BeginGetVpnclientIpsecParametersAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetVpnclientIpsecParametersWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Starts packet capture on virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='filterData'>
/// Start Packet capture parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> BeginStartPacketCaptureAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string filterData = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStartPacketCaptureWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, filterData, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Stops packet capture on virtual network gateway in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='sasUrl'>
/// SAS url for packet capture on virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> BeginStopPacketCaptureAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, string sasUrl = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginStopPacketCaptureWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, sasUrl, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get VPN client connection health detail per P2S client connection of the
/// virtual network gateway in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VpnClientConnectionHealthDetailListResultInner> BeginGetVpnclientConnectionHealthAsync(this IVirtualNetworkGatewaysOperations operations, string resourceGroupName, string virtualNetworkGatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetVpnclientConnectionHealthWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayInner>> ListNextAsync(this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayConnectionListEntityInner>> ListConnectionsNextAsync(this IVirtualNetworkGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListConnectionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 52.516899 | 335 | 0.594185 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/Network/Generated/VirtualNetworkGatewaysOperationsExtensions.cs | 52,832 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace companion.Services
{
public class SignalRService : ISignalRService
{
private HubConnection connection;
private string url = "http://localhost:55344/hub";
public event Action<string, string> NewTextMessage;
public void Connect()
{
try
{
connection = new HubConnectionBuilder().WithUrl(url).Build();
connection.On<string, string>("SendMessage", (n, m) => NewTextMessage?.Invoke(n, m));
ServicePointManager.DefaultConnectionLimit = 10;
connection.StartAsync();
}
catch (Exception ex)
{
throw;
}
}
public void SendMessage(string id, string msg)
{
connection.InvokeAsync("SendMessage", id, msg);
}
}
}
| 25.341463 | 101 | 0.585178 | [
"MIT"
] | maxpavlov/desktop-integration-demo | companion/Services/SignalRService.cs | 1,041 | C# |
using UnityEngine;
[CreateAssetMenu(fileName = "OnRemovePlayer", menuName = "GameEvents/RemovePlayer")]
public class RemovePlayerFunction : GameFunction<PlayerRemoval> { }
| 34.8 | 84 | 0.798851 | [
"Apache-2.0"
] | Nickeron/DoubleRoom | Assets/Scripts/EventSystem/EventTypes/RemovePlayerFunction.cs | 176 | C# |
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
namespace BoardGameGeek.Dungeon.Extensions
{
public static class Utf8JsonWriterExtensions
{
public static void WriteEnum<T>(this Utf8JsonWriter writer, string propertyName, T value) where T : struct, Enum => writer.WriteString(propertyName, value.ToString());
public static void WriteDateTime(this Utf8JsonWriter writer, string propertyName, DateTime value) => writer.WriteString(propertyName, value);
public static void WriteDateTimeOffset(this Utf8JsonWriter writer, string propertyName, DateTimeOffset value) => writer.WriteString(propertyName, value);
public static void WriteTimeSpan(this Utf8JsonWriter writer, string propertyName, TimeSpan value) => writer.WriteString(propertyName, value.ToString(null, CultureInfo.InvariantCulture));
public static void WriteNullableBoolean(this Utf8JsonWriter writer, string propertyName, bool? value) => writer.WriteNull(propertyName, value)?.WriteBoolean(propertyName, value!.Value);
public static void WriteNullableNumber(this Utf8JsonWriter writer, string propertyName, int? value) => writer.WriteNull(propertyName, value)?.WriteNumber(propertyName, value!.Value);
public static void WriteNullableEnum<T>(this Utf8JsonWriter writer, string propertyName, T? value) where T : struct, Enum => writer.WriteNull(propertyName, value)?.WriteEnum(propertyName, value!.Value);
public static void WriteNullableDateTime(this Utf8JsonWriter writer, string propertyName, DateTime? value) => writer.WriteNull(propertyName, value)?.WriteDateTime(propertyName, value!.Value);
public static void WriteNullableDateTimeOffset(this Utf8JsonWriter writer, string propertyName, DateTimeOffset? value) => writer.WriteNull(propertyName, value)?.WriteDateTimeOffset(propertyName, value!.Value);
public static void WriteNullableTimeSpan(this Utf8JsonWriter writer, string propertyName, TimeSpan? value) => writer.WriteNull(propertyName, value)?.WriteTimeSpan(propertyName, value!.Value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Utf8JsonWriter WriteNull<T>(this Utf8JsonWriter writer, string propertyName, T? value) where T : struct
{
if (!value.HasValue)
{
writer.WriteNull(propertyName);
return null;
}
return writer;
}
}
}
| 59.333333 | 217 | 0.750401 | [
"MIT"
] | gitfool/BoardGameGeek.Dungeon | Application/Extensions/Utf8JsonWriterExtensions.cs | 2,492 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayEcoBasicRouterSendResponse.
/// </summary>
public class AlipayEcoBasicRouterSendResponse : AopResponse
{
/// <summary>
/// 路由返回的数据
/// </summary>
[XmlElement("res")]
public string Res { get; set; }
}
}
| 21.277778 | 64 | 0.563969 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Response/AlipayEcoBasicRouterSendResponse.cs | 397 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_ImportExport_Controls_Import___objects__ {
/// <summary>
/// pnlWarning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlWarning;
/// <summary>
/// lblWarning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblWarning;
/// <summary>
/// pnlInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlInfo;
/// <summary>
/// lblInfo2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblInfo2;
/// <summary>
/// lblInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblInfo;
/// <summary>
/// pnlSelection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlSelection;
/// <summary>
/// headSelection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedHeading headSelection;
/// <summary>
/// lnkSelectDefault control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSButton lnkSelectDefault;
/// <summary>
/// lnkSelectAll control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSButton lnkSelectAll;
/// <summary>
/// lnkSelectNew control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSButton lnkSelectNew;
/// <summary>
/// lnkSelectNone control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSButton lnkSelectNone;
/// <summary>
/// pnlMacroResigning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlMacroResigning;
/// <summary>
/// headMacroResigning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedHeading headMacroResigning;
/// <summary>
/// lblMacroResigning control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblMacroResigning;
/// <summary>
/// lblMacroResigningUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedLabel lblMacroResigningUser;
/// <summary>
/// userSelectorMacroResigningUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_Membership_FormControls_Users_SelectUser userSelectorMacroResigningUser;
/// <summary>
/// pnlCheck control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlCheck;
/// <summary>
/// headSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.LocalizedHeading headSettings;
/// <summary>
/// plcSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcSite;
/// <summary>
/// plcExistingSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcExistingSite;
/// <summary>
/// chkUpdateSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkUpdateSite;
/// <summary>
/// chkBindings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkBindings;
/// <summary>
/// chkRunSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkRunSite;
/// <summary>
/// chkDeleteSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkDeleteSite;
/// <summary>
/// chkSkipOrfans control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkSkipOrfans;
/// <summary>
/// chkImportTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkImportTasks;
/// <summary>
/// chkLogSync control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkLogSync;
/// <summary>
/// chkLogInt control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkLogInt;
/// <summary>
/// chkCopyFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkCopyFiles;
/// <summary>
/// chkCopyCodeFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkCopyCodeFiles;
/// <summary>
/// chkCopyAssemblies control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkCopyAssemblies;
/// <summary>
/// chkCopyGlobalFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkCopyGlobalFiles;
/// <summary>
/// plcSiteFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder plcSiteFiles;
/// <summary>
/// chkCopySiteFiles control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.Base.Web.UI.CMSCheckBox chkCopySiteFiles;
/// <summary>
/// ltlScript control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltlScript;
}
| 32.097264 | 105 | 0.616383 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/ImportExport/Controls/Import/__objects__.ascx.designer.cs | 10,562 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.IO.Tests
{
[ActiveIssue("https://github.com/dotnet/runtime/issues/58707", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowserOnWindows), nameof(PlatformDetection.IsMonoAOT))]
public class FileInfo_CopyTo_str : File_Copy_str_str
{
protected override void Copy(string source, string dest)
{
new FileInfo(source).CopyTo(dest);
}
}
public class FileInfo_CopyTo_str_b : File_Copy_str_str_b
{
protected override void Copy(string source, string dest)
{
new FileInfo(source).CopyTo(dest, false);
}
protected override void Copy(string source, string dest, bool overwrite)
{
new FileInfo(source).CopyTo(dest, overwrite);
}
}
}
| 31.133333 | 177 | 0.673448 | [
"MIT"
] | 333fred/runtime | src/libraries/System.IO.FileSystem/tests/FileInfo/CopyTo.cs | 934 | C# |
namespace FilterLists.Data.Entities
{
public interface IDeleteSoftly
{
bool? IsDeleted { get; set; }
}
} | 17.857143 | 37 | 0.632 | [
"MIT"
] | Yuki2718/FilterLists | server/src/FilterLists.Data/Entities/IDeleteSoftly.cs | 127 | 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("20.InfiniteConvergentSeries")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("20.InfiniteConvergentSeries")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c05c5900-54c3-40a8-8e8a-66cf7a3bb38f")]
// 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.054054 | 84 | 0.752249 | [
"MIT"
] | baretata/CSharpOOP | 03.ExtensionMethods-Delegates-Lambda-LINQ/20.InfiniteConvergentSeries/Properties/AssemblyInfo.cs | 1,448 | C# |
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Auth0
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new Views.LoginPageView();
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
| 15.689655 | 49 | 0.520879 | [
"MIT"
] | exendahal/Auth0 | Auth0/Auth0/App.xaml.cs | 457 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) The DotNetty Project (Microsoft). All rights reserved.
*
* https://github.com/azure/dotnetty
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Transport.Channels.Embedded
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DotNetty.Common;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Internal;
using DotNetty.Common.Utilities;
using Thread = DotNetty.Common.Concurrency.XThread;
sealed class EmbeddedEventLoop : AbstractScheduledEventExecutor, IEventLoop
{
readonly Deque<IRunnable> _tasks = new Deque<IRunnable>(2);
public new IEventLoop GetNext() => this;
public Task RegisterAsync(IChannel channel) => channel.Unsafe.RegisterAsync(this);
public override bool IsShuttingDown => false;
public override Task TerminationCompletion => throw ThrowHelper.GetNotSupportedException();
public override bool IsShutdown => false;
public override bool IsTerminated => false;
public new IEventLoopGroup Parent => (IEventLoopGroup)base.Parent;
protected override IEnumerable<IEventExecutor> GetItems() => new[] { this };
public new IEnumerable<IEventLoop> Items => new[] { this };
public override bool IsInEventLoop(Thread thread) => true;
public override void Execute(IRunnable command)
{
if (command is null)
{
ThrowHelper.ThrowNullReferenceException_Command();
}
_tasks.AddLast(command);
}
public override Task ShutdownGracefullyAsync(TimeSpan quietPeriod, TimeSpan timeout)
{
throw ThrowHelper.GetNotSupportedException();
}
internal long NextScheduledTask() => NextScheduledTaskNanos();
internal void RunTasks()
{
while (_tasks.TryRemoveFirst(out var task))
{
task.Run();
}
}
internal long RunScheduledTasks()
{
var time = PreciseTime.NanoTime();
while (true)
{
IRunnable task = PollScheduledTask(time);
if (task is null)
{
return NextScheduledTaskNanos();
}
task.Run();
}
}
internal new void CancelScheduledTasks() => base.CancelScheduledTasks();
public override bool WaitTermination(TimeSpan timeout)
{
return false;
}
}
} | 32.394495 | 101 | 0.648541 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | sekkit/Fenix | src/DotNetty.Transport/Channels/Embedded/EmbeddedEventLoop.cs | 3,535 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.System.Preview
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum HingeState
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Unknown,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Closed,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Concave,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Flat,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Convex,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Full,
#endif
}
#endif
}
| 35.1875 | 99 | 0.703375 | [
"Apache-2.0"
] | Abhishek-Sharma-Msft/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System.Preview/HingeState.cs | 1,126 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// 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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.SecretManager.V1.Snippets
{
using Google.Cloud.SecretManager.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedSecretManagerServiceClientStandaloneSnippets
{
/// <summary>Snippet for DeleteSecretAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteSecretAsync()
{
// Create client
SecretManagerServiceClient secretManagerServiceClient = await SecretManagerServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/secrets/[SECRET]";
// Make the request
await secretManagerServiceClient.DeleteSecretAsync(name);
}
}
}
| 38.475 | 115 | 0.698506 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/secretmanager/v1/google-cloud-secretmanager-v1-csharp/Google.Cloud.SecretManager.V1.StandaloneSnippets/SecretManagerServiceClient.DeleteSecretAsyncSnippet.g.cs | 1,539 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace RomanPort.LibSDR.Components.IO.USB
{
public unsafe class UsbBuffer : IDisposable
{
public UsbBuffer(int length)
{
this.length = length;
buffer = UnsafeBuffer.Create(length, out bytePtr);
}
public static UsbBuffer FromValue<T>(T value) where T : unmanaged
{
UsbBuffer buffer = new UsbBuffer(sizeof(T));
Utils.Memcpy(buffer.AsPtr(), &value, sizeof(T));
return buffer;
}
public static UsbBuffer FromValue<T>(T* value) where T : unmanaged
{
UsbBuffer buffer = new UsbBuffer(sizeof(T));
Utils.Memcpy(buffer.AsPtr(), value, sizeof(T));
return buffer;
}
private int length;
private UnsafeBuffer buffer;
private byte* bytePtr;
public int ByteLength { get => length; }
public byte* AsPtr()
{
return bytePtr;
}
public byte[] AsArray(out int offset)
{
offset = buffer.bufferAlignmentOffset;
return buffer.buffer;
}
public void Dispose()
{
buffer.Dispose();
}
}
}
| 24.423077 | 74 | 0.551181 | [
"MIT"
] | Roman-Port/LibSDR | RomanPort.LibSDR/Components/IO/USB/UsbBuffer.cs | 1,272 | C# |
namespace dropkick.Tasks.Files
{
using System.IO;
using DeploymentModel;
using Path = FileSystem.Path;
public class EmptyFolderTask : Task
{
string _to;
Path _path;
public EmptyFolderTask(string to, Path path)
{
_to = to;
_path = path;
}
public string Name
{
get { return "Creating new empty folder '{0}'".FormatWith(_to); }
}
public DeploymentResult VerifyCanRun()
{
var result = new DeploymentResult();
var to = _path.GetFullPath(_to);
//TODO figure out a good verify step...
result.AddGood(Directory.Exists(to) ? "'{0}' already exists.".FormatWith(to) : Name);
return result;
}
public DeploymentResult Execute()
{
var result = new DeploymentResult();
var to = _path.GetFullPath(_to);
if (Directory.Exists(to))
result.AddGood("'{0}' already exists.".FormatWith(to));
else
{
result.AddGood(Name);
Directory.CreateDirectory(to);
}
return result;
}
}
} | 26.458333 | 98 | 0.493701 | [
"Apache-2.0"
] | chucknorris/dropkick | product/dropkick/Tasks/Files/EmptyFolderTask.cs | 1,272 | C# |
namespace CAP_report_analysis_tool
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.buttonLoadIdeal = new System.Windows.Forms.Button();
this.buttonLoadCurrent = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// buttonLoadIdeal
//
this.buttonLoadIdeal.Location = new System.Drawing.Point(70, 83);
this.buttonLoadIdeal.Name = "buttonLoadIdeal";
this.buttonLoadIdeal.Size = new System.Drawing.Size(166, 23);
this.buttonLoadIdeal.TabIndex = 0;
this.buttonLoadIdeal.Text = "buttonLoadIdeal";
this.buttonLoadIdeal.UseVisualStyleBackColor = true;
this.buttonLoadIdeal.Click += new System.EventHandler(this.buttonLoadIdeal_Click);
//
// buttonLoadCurrent
//
this.buttonLoadCurrent.Location = new System.Drawing.Point(362, 82);
this.buttonLoadCurrent.Name = "buttonLoadCurrent";
this.buttonLoadCurrent.Size = new System.Drawing.Size(148, 23);
this.buttonLoadCurrent.TabIndex = 1;
this.buttonLoadCurrent.Text = "LoadCurrent";
this.buttonLoadCurrent.UseVisualStyleBackColor = true;
this.buttonLoadCurrent.Click += new System.EventHandler(this.buttonLoadCurrent_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(294, 131);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(264, 29);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 3;
this.label1.Text = "label1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(717, 171);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.buttonLoadCurrent);
this.Controls.Add(this.buttonLoadIdeal);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button buttonLoadIdeal;
private System.Windows.Forms.Button buttonLoadCurrent;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Label label1;
}
}
| 41.772727 | 108 | 0.573885 | [
"MIT"
] | Energizer73/CAP-report-analysis-tool | CAP_report_analysis_tool/Form1.Designer.cs | 4,597 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace NativeMediaPlayer.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 23.285714 | 91 | 0.638037 | [
"MIT"
] | ShravanJ/FormsNativeMediaPlayer | iOS/Main.cs | 491 | C# |
using SaTeatar.Model.Models;
using SaTeatar.Model.Requests;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace SaTeatar.Mobile.ViewModels
{
class PreporucenePredstaveViewModel : BaseViewModel
{
private readonly APIService _kupciService = new APIService("kupci");
private readonly APIService _predstaveService = new APIService("predstava");
private readonly APIService _tipovipredstavaService = new APIService("tipoviPredstava");
private readonly APIService _predstaveDjelatniciService = new APIService("PredstaveDjelatnici");
private readonly APIService _vrstedjelatnikaService = new APIService("vrsteDjelatnika");
public PreporucenePredstaveViewModel()
{
InitCommand = new Command(async () => await Init());
}
public ObservableCollection<PreporucenePredstaveClass> PreporucenePredstave { get; set; } = new ObservableCollection<PreporucenePredstaveClass>();
public class PreporucenePredstaveClass
{
public int PredstavaId { get; set; }
public string Naziv { get; set; }
public int TipId { get; set; }
public string Tip { get; set; }
public string Opis { get; set; }
public byte[] Slika { get; set; }
public string GlumciStr { get; set; }
public string Rezija { get; set; }
}
public ICommand InitCommand { get; set; }
bool _nemaPredstava = false;
public bool NemaPredstava
{
get { return _nemaPredstava; }
set { SetProperty(ref _nemaPredstava, value); }
}
string _poruka = string.Empty;
public string Poruka
{
get { return _poruka; }
set { SetProperty(ref _poruka, value); }
}
public async Task Init()
{
NemaPredstava = true;
var search = new rKupciSearch() { KorisnickoIme = APIService.Username };
var kupci = await _kupciService.Get<List<mKupci>>(search);
var idkupca = kupci[0].KupacId;
List<mPredstave> predstave = await _predstaveService.Recommend<List<mPredstave>>(idkupca);
PreporucenePredstave.Clear();
if (predstave.Count>0)
{
NemaPredstava = false;
foreach (var item in predstave)
{
var tip = await _tipovipredstavaService.GetById<mTipoviPredstava>(item.TipPredstaveId);
var searchg = new rPredstaveDjelatnicSearch() { PredstavaId = item.PredstavaId };
var listaglumaca = await _predstaveDjelatniciService.Get<List<mPredstaveDjelatnici>>(searchg);
string lgstr = "";
string rezija = "";
foreach (var g in listaglumaca)
{
if (g.Djelatnik.VrstaDjelatnikaId==2)
{
lgstr += $"{g.DjelatnikIme} {g.DjelatnikPrezime}\n";
}
else
{
rezija = $"{g.DjelatnikIme} {g.DjelatnikPrezime}";
}
}
PreporucenePredstave.Add(new PreporucenePredstaveClass()
{
PredstavaId = item.PredstavaId,
Naziv = item.Naziv,
Opis = item.Opis,
TipId = item.TipPredstaveId,
Tip = tip.Naziv.ToUpper(),
GlumciStr =lgstr,
Slika = item.Slika,
Rezija=rezija
}) ;
}
}
else
{
Poruka = "Nismo u mogucnosti da preporucimo predstave.";
}
}
}
}
| 35.652542 | 155 | 0.523413 | [
"MIT"
] | eminafit/SaTeatar | SaTeatar.Mobile/SaTeatar.Mobile/ViewModels/PreporucenePredstaveViewModel.cs | 4,209 | 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.Iot.Transform;
using Aliyun.Acs.Iot.Transform.V20180120;
namespace Aliyun.Acs.Iot.Model.V20180120
{
public class BatchGetEdgeDriverRequest : RpcAcsRequest<BatchGetEdgeDriverResponse>
{
public BatchGetEdgeDriverRequest()
: base("Iot", "2018-01-20", "BatchGetEdgeDriver", "Iot", "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);
}
}
private List<string> driverIdss = new List<string>(){ };
private string iotInstanceId;
public List<string> DriverIdss
{
get
{
return driverIdss;
}
set
{
driverIdss = value;
for (int i = 0; i < driverIdss.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"DriverIds." + (i + 1) , driverIdss[i]);
}
}
}
public string IotInstanceId
{
get
{
return iotInstanceId;
}
set
{
iotInstanceId = value;
DictionaryUtil.Add(QueryParameters, "IotInstanceId", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override BatchGetEdgeDriverResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return BatchGetEdgeDriverResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 29.747126 | 134 | 0.680062 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-iot/Iot/Model/V20180120/BatchGetEdgeDriverRequest.cs | 2,588 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialAssigner : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 15.842105 | 52 | 0.631229 | [
"MIT"
] | mareklinka/blazing-roller | src/Unity/Assets/ThirdParty/Dice/MaterialAssigner.cs | 303 | C# |
// -----------------------------------------------------------------------
// <copyright file="HealthEventType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Explorer.Logic
{
/// <summary>
/// Enumeration description possible health event types.
/// </summary>
public enum HealthEventType
{
/// <summary>
/// The health event is from Azure Insights.
/// </summary>
Azure,
/// <summary>
/// The health event is from Office 365 Service Communications API.
/// </summary>
Office
}
} | 31 | 75 | 0.485215 | [
"MIT"
] | Bhaskers-Blu-Org2/Partner-Center-Explorer | src/Explorer/Logic/HealthEventType.cs | 746 | C# |
//
// DO NOT MODIFY. THIS IS AUTOMATICALLY GENERATED FILE.
//
#nullable enable
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
using System;
using System.Collections.Generic;
namespace CefNet.DevTools.Protocol.Network
{
public sealed class RequestWillBeSentEventArgs
: System.EventArgs
{
/// <summary>Request identifier.</summary>
public CefNet.DevTools.Protocol.Network.RequestId RequestId { get; set; }
/// <summary>
/// Loader identifier. Empty string if the request is fetched from worker.
/// </summary>
public CefNet.DevTools.Protocol.Network.LoaderId LoaderId { get; set; }
/// <summary>
/// URL of the document this request is loaded for.
/// </summary>
public string DocumentURL { get; set; }
/// <summary>Request data.</summary>
public CefNet.DevTools.Protocol.Network.Request Request { get; set; }
/// <summary>Timestamp.</summary>
public CefNet.DevTools.Protocol.Network.MonotonicTime Timestamp { get; set; }
/// <summary>Timestamp.</summary>
public CefNet.DevTools.Protocol.Network.TimeSinceEpoch WallTime { get; set; }
/// <summary>Request initiator.</summary>
public CefNet.DevTools.Protocol.Network.Initiator Initiator { get; set; }
/// <summary>Redirect response data.</summary>
public CefNet.DevTools.Protocol.Network.Response? RedirectResponse { get; set; }
/// <summary>Type of this resource.</summary>
public CefNet.DevTools.Protocol.Network.ResourceType? Type { get; set; }
/// <summary>Frame identifier.</summary>
public CefNet.DevTools.Protocol.Page.FrameId? FrameId { get; set; }
/// <summary>
/// Whether the request is initiated by a user gesture. Defaults to false.
/// </summary>
public bool? HasUserGesture { get; set; }
}
}
| 37.092593 | 140 | 0.658512 | [
"MIT"
] | CefNet/CefNet.DevTools.Protocol | CefNet.DevTools.Protocol/Generated/Network/RequestWillBeSentEventArgs.g.cs | 2,003 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponChangeScript : MonoBehaviour
{
private Quaternion customWeaponRotation;
private Vector3 customWeaponScale = new Vector3(0.75f, 0.65f, 0.75f);
private Vector3 bias = new Vector3(0, 0, 0.05f);
// Start is called before the first frame update
private void Awake()
{
Vector3 rot = new Vector3(270f, 180f, 0f);
customWeaponRotation = Quaternion.Euler(rot);
LevelEvents.levelEvents.onOnhandWeaponChangeTriggerEnter += OnOnhandSwitch;
}
private void OnOnhandSwitch(WeaponScript newOnhand, bool prevWasNull)
{
if (prevWasNull && newOnhand != null)
{
// transform.GetChild(0).gameObject.SetActive(false);
this.transform.GetChild(0).gameObject.GetComponent<MeshRenderer>().enabled = false;
GameObject _obj = new GameObject();
_obj.AddComponent<MeshFilter>();
_obj.AddComponent<MeshRenderer>();
_obj.GetComponent<MeshFilter>().mesh = newOnhand.gameObject.GetComponent<MeshFilter>().mesh;
_obj.GetComponent<MeshRenderer>().material = newOnhand.gameObject.GetComponent<MeshRenderer>().material;
_obj.transform.localScale = customWeaponScale;
_obj.transform.localRotation = customWeaponRotation;
Instantiate(_obj, this.transform);
Destroy(_obj);
}
else if (prevWasNull && newOnhand == null)
{
return;
}
else if (newOnhand == null && !prevWasNull)
{
//transform.GetChild(0).gameObject.SetActive(true);
this.transform.GetChild(0).gameObject.GetComponent<MeshRenderer>().enabled = true;
Destroy(this.transform.GetChild(1).gameObject);
}
else
{
Destroy(this.transform.GetChild(1).gameObject);
GameObject _obj = new GameObject();
_obj.AddComponent<MeshFilter>();
_obj.AddComponent<MeshRenderer>();
_obj.GetComponent<MeshFilter>().mesh = newOnhand.gameObject.GetComponent<MeshFilter>().mesh;
_obj.GetComponent<MeshRenderer>().material = newOnhand.gameObject.GetComponent<MeshRenderer>().material;
_obj.transform.localScale = customWeaponScale;
_obj.transform.localRotation = customWeaponRotation;
Instantiate(_obj, this.transform);
Destroy(_obj);
}
}
private void OnDestroy()
{
LevelEvents.levelEvents.onOnhandWeaponChangeTriggerEnter -= OnOnhandSwitch;
}
} | 40.307692 | 116 | 0.648855 | [
"MIT"
] | lamnguyenkhoa/JhoVengeance | Assets/Scripts/WeaponChangeScript.cs | 2,620 | 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderingQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Represents operators AsOrdered and AsUnordered. In the current implementation, it
/// simply turns on preservation globally in the query.
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class OrderingQueryOperator<TSource> : QueryOperator<TSource>
{
private QueryOperator<TSource> _child;
private OrdinalIndexState _ordinalIndexState;
public OrderingQueryOperator(QueryOperator<TSource> child, bool orderOn)
: base(orderOn, child.SpecifiedQuerySettings)
{
_child = child;
_ordinalIndexState = _child.OrdinalIndexState;
}
internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
{
return _child.Open(settings, preferStriping);
}
internal override IEnumerator<TSource> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation)
{
ScanQueryOperator<TSource> childAsScan = _child as ScanQueryOperator<TSource>;
if (childAsScan != null)
{
return childAsScan.Data.GetEnumerator();
}
return base.GetEnumerator(mergeOptions, suppressOrderPreservation);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
return _child.AsSequentialQuery(token);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _child.LimitsParallelism; }
}
internal override OrdinalIndexState OrdinalIndexState
{
get { return _ordinalIndexState; }
}
}
}
| 36.364865 | 128 | 0.570048 | [
"MIT"
] | 2E0PGS/corefx | src/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Options/OrderingQueryOperator.cs | 2,691 | C# |
using System;
using System.Collections.Generic;
namespace UnityEngine.XR.ARFoundation
{
/// <summary>
/// Container for the changed <c>ARHumanBody</c> of the event.
/// </summary>
public struct ARHumanBodiesChangedEventArgs : IEquatable<ARHumanBodiesChangedEventArgs>
{
/// <summary>
/// The list of <see cref="ARHumanBody"/>s added since the last event.
/// </summary>
public List<ARHumanBody> added { get; private set; }
/// <summary>
/// The list of <see cref="ARHumanBody"/>s udpated since the last event.
/// </summary>
public List<ARHumanBody> updated { get; private set; }
/// <summary>
/// The list of <see cref="ARHumanBody"/>s removed since the last event.
/// </summary>
public List<ARHumanBody> removed { get; private set; }
/// <summary>
/// Constructs an <see cref="ARPlaneChangedEventArgs"/>.
/// </summary>
/// <param name="added">The list of <see cref="ARHumanBody"/>s added since the last event.</param>
/// <param name="updated">The list of <see cref="ARHumanBody"/>s updated since the last event.</param>
/// <param name="removed">The list of <see cref="ARHumanBody"/>s removed since the last event.</param>
public ARHumanBodiesChangedEventArgs(
List<ARHumanBody> added,
List<ARHumanBody> updated,
List<ARHumanBody> removed)
{
this.added = added;
this.updated = updated;
this.removed = removed;
}
public override int GetHashCode()
{
unchecked
{
int hash = 0;
hash = hash * 486187739 + (added == null ? 0 : added.GetHashCode());
hash = hash * 486187739 + (updated == null ? 0 : updated.GetHashCode());
hash = hash * 486187739 + (removed == null ? 0 : removed.GetHashCode());
return hash;
}
}
public bool Equals(ARHumanBodiesChangedEventArgs other)
{
return
ReferenceEquals(added, other.added) &&
ReferenceEquals(updated, other.updated) &&
ReferenceEquals(removed, other.removed);
}
public override bool Equals(object obj)
{
return ((obj is ARHumanBodiesChangedEventArgs) && Equals((ARHumanBodiesChangedEventArgs)obj));
}
public static bool operator ==(ARHumanBodiesChangedEventArgs lhs, ARHumanBodiesChangedEventArgs rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(ARHumanBodiesChangedEventArgs lhs, ARHumanBodiesChangedEventArgs rhs)
{
return !lhs.Equals(rhs);
}
public override string ToString()
{
return string.Format("Added: {0}, Updated: {1}, Removed: {2}",
added == null ? 0 : added.Count,
updated == null ? 0 : updated.Count,
removed == null ? 0 : removed.Count);
}
}
}
| 35.666667 | 110 | 0.565582 | [
"Unlicense"
] | 23SAMY23/Smart-Kid | SmartKid/Library/PackageCache/com.unity.xr.arfoundation@3.0.0-preview.3/Runtime/AR/ARHumanBodiesChangedEventArgs.cs | 3,103 | C# |
using System;
using System.Threading.Tasks;
using LambdaSharp;
using LambdaSharp.CustomResource;
namespace Legacy.ModuleV080.MyCustomResourceFunction {
public class ResourceProperties {
//--- Properties ---
// TO-DO: add request resource properties
}
public class ResourceAttributes {
//--- Properties ---
// TO-DO: add response resource attributes
}
public sealed class Function : ALambdaCustomResourceFunction<ResourceProperties, ResourceAttributes> {
//--- Methods ---
public override async Task InitializeAsync(LambdaConfig config) {
// TO-DO: add function initialization and reading configuration settings
}
public override async Task<Response<ResourceAttributes>> ProcessCreateResourceAsync(Request<ResourceProperties> request) {
// TO-DO: create custom resource using resource properties from request
return new Response<ResourceAttributes> {
// TO-DO: assign a physical resource ID for custom resource
PhysicalResourceId = "MyResource:123",
// TO-DO: set response attributes
Attributes = new ResourceAttributes { }
};
}
public override async Task<Response<ResourceAttributes>> ProcessDeleteResourceAsync(Request<ResourceProperties> request) {
// TO-DO: delete custom resource identified by PhysicalResourceId in request
return new Response<ResourceAttributes>();
}
public override async Task<Response<ResourceAttributes>> ProcessUpdateResourceAsync(Request<ResourceProperties> request) {
// TO-DO: update custom resource using resource properties from request
return new Response<ResourceAttributes> {
// TO-DO: optionally assign a new physical resource ID to trigger deletion of the previous custom resource
PhysicalResourceId = "MyResource:123",
// TO-DO: set response attributes
Attributes = new ResourceAttributes { }
};
}
}
}
| 32.19697 | 130 | 0.657882 | [
"Apache-2.0"
] | LambdaSharp/LambdaSharpTool | Tests/Legacy/v0.8.0/MyCustomResourceFunction/Function.cs | 2,125 | C# |
using System;
namespace ILStripTest
{
public class CustomAttribute: Attribute
{
}
}
| 11.111111 | 42 | 0.66 | [
"MIT-0"
] | BrokenEvent/ILStrip | ILStripTestLib/CustomAttribute.cs | 102 | C# |
using System;
namespace MementoPattern
{
internal class GameRole
{
public GameRole()
{
Vitality = 100;
Attack = 100;
Defense = 100;
}
/// <summary>
/// 生命力
/// </summary>
public int Vitality { get; set; }
/// <summary>
/// 攻击力
/// </summary>
public int Attack { get; set; }
/// <summary>
/// 防御力
/// </summary>
public int Defense { get; set; }
public void StateDisplay()
{
Console.WriteLine("角色当前状态:");
Console.WriteLine($"生命力:{Vitality}");
Console.WriteLine($"攻击力:{Attack}");
Console.WriteLine($"防御力:{Defense}");
Console.WriteLine();
}
public void FightWithBoss()
{
Vitality = 1;
Attack = 10;
Defense = 0;
}
public RoleStateMemento SaveState()
{
return new RoleStateMemento(Vitality, Attack, Defense);
}
public void RecoveryState(RoleStateMemento memento)
{
Vitality = memento.Vitality;
Attack = memento.Attack;
Defense = memento.Defense;
}
}
}
| 21.775862 | 67 | 0.465558 | [
"MIT"
] | devilcry11/DesignPatterns | BehaviorPattern/MementoPattern/GameRole.cs | 1,321 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace Prism.Behaviors
{
/// <summary>
/// Behavior class that enable using <see cref="ICommand" /> to react on events raised by <see cref="BindableObject" /> bindable.
/// </summary>
/// <para>
/// There are multiple ways to pass a parameter to the <see cref="ICommand.Execute"/> method.
/// Setting the <see cref="CommandParameter"/> will always result in that value will be sent.
/// The <see cref="EventArgsParameterPath"/> will walk the property path on the instance of <see cref="EventArgs"/> for the event and, if any property found, pass that parameter.
/// The <see cref="EventArgsConverter"/> will call the <see cref="IValueConverter.Convert"/> method with the <see cref="EventArgsConverterParameter"/> and pass the result as parameter.
/// </para>
/// <para>
/// The order of evaluation for the parameter to be sent to the <see cref="ICommand.Execute"/> method is
/// 1. <see cref="CommandParameter"/>
/// 2. <see cref="EventArgsParameterPath"/>
/// 3. <see cref="EventArgsConverter"/>
/// and as soon as a non-<c>null</c> value is found, the evaluation is stopped.
/// </para>
/// <example>
/// <ListView>
/// <ListView.Behaviors>
/// <behaviors:EventToCommandBehavior EventName="ItemTapped" Command={Binding ItemTappedCommand} />
/// </ListView.Behaviors>
/// </ListView>
/// </example>
// This is a modified version of https://anthonysimmon.com/eventtocommand-in-xamarin-forms-apps/
public class EventToCommandBehavior : BehaviorBase<BindableObject>
{
/// <summary>
/// Bindable property for Name of the event that will be forwarded to
/// <see cref="EventToCommandBehavior.Command"/>
/// </summary>
public static readonly BindableProperty EventNameProperty =
BindableProperty.Create(nameof(EventName), typeof(string), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property for Command to execute
/// </summary>
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property for Argument sent to <see cref="ICommand.Execute(object)"/>
/// </summary>
public static readonly BindableProperty CommandParameterProperty =
BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set instance of <see cref="IValueConverter" /> to convert the <see cref="EventArgs" /> for <see cref="EventName" />
/// </summary>
public static readonly BindableProperty EventArgsConverterProperty =
BindableProperty.Create(nameof(EventArgsConverter), typeof(IValueConverter), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set Argument passed as parameter to <see cref="IValueConverter.Convert" />
/// </summary>
public static readonly BindableProperty EventArgsConverterParameterProperty =
BindableProperty.Create(nameof(EventArgsConverterParameter), typeof(object), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set Parameter path to extract property from <see cref="EventArgs"/> instance to pass to <see cref="ICommand.Execute"/>
/// </summary>
public static readonly BindableProperty EventArgsParameterPathProperty =
BindableProperty.Create(
nameof(EventArgsParameterPath),
typeof(string),
typeof(EventToCommandBehavior));
/// <summary>
/// <see cref="EventInfo"/>
/// </summary>
protected EventInfo _eventInfo;
/// <summary>
/// Delegate to Invoke when event is raised
/// </summary>
protected Delegate _handler;
/// <summary>
/// Parameter path to extract property from <see cref="EventArgs"/> instance to pass to <see cref="ICommand.Execute"/>
/// </summary>
public string EventArgsParameterPath
{
get { return (string)GetValue(EventArgsParameterPathProperty); }
set { SetValue(EventArgsParameterPathProperty, value); }
}
/// <summary>
/// Name of the event that will be forwarded to <see cref="Command" />
/// </summary>
/// <remarks>
/// An event that is invalid for the attached <see cref="View" /> will result in <see cref="ArgumentException" /> thrown.
/// </remarks>
public string EventName
{
get { return (string)GetValue(EventNameProperty); }
set { SetValue(EventNameProperty, value); }
}
/// <summary>
/// The command to execute
/// </summary>
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
/// <summary>
/// Argument sent to <see cref="ICommand.Execute" />
/// </summary>
/// <para>
/// If <see cref="EventArgsConverter" /> and <see cref="EventArgsConverterParameter" /> is set then the result of the
/// conversion
/// will be sent.
/// </para>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Instance of <see cref="IValueConverter" /> to convert the <see cref="EventArgs" /> for <see cref="EventName" />
/// </summary>
public IValueConverter EventArgsConverter
{
get { return (IValueConverter)GetValue(EventArgsConverterProperty); }
set { SetValue(EventArgsConverterProperty, value); }
}
/// <summary>
/// Argument passed as parameter to <see cref="IValueConverter.Convert" />
/// </summary>
public object EventArgsConverterParameter
{
get { return GetValue(EventArgsConverterParameterProperty); }
set { SetValue(EventArgsConverterParameterProperty, value); }
}
/// <summary>
/// Subscribes to the event <see cref="BindableObject"/> object
/// </summary>
/// <param name="bindable">Bindable object that is source of event to Attach</param>
/// <exception cref="ArgumentException">Thrown if no matching event exists on
/// <see cref="BindableObject"/></exception>
protected override void OnAttachedTo(BindableObject bindable)
{
base.OnAttachedTo(bindable);
_eventInfo = AssociatedObject
.GetType()
.GetRuntimeEvent(EventName);
if (_eventInfo == null)
{
throw new ArgumentException(
$"No matching event '{EventName}' on attached type '{bindable.GetType().Name}'");
}
AddEventHandler(_eventInfo, AssociatedObject, OnEventRaised);
}
/// <summary>
/// Unsubscribes from the event on <paramref name="bindable"/>
/// </summary>
/// <param name="bindable"><see cref="BindableObject"/> that is source of event</param>
protected override void OnDetachingFrom(BindableObject bindable)
{
if (_handler != null)
{
_eventInfo.RemoveEventHandler(AssociatedObject, _handler);
}
_handler = null;
_eventInfo = null;
base.OnDetachingFrom(bindable);
}
private void AddEventHandler(EventInfo eventInfo, object item, Action<object, EventArgs> action)
{
var eventParameters = eventInfo.EventHandlerType
.GetRuntimeMethods().First(m => m.Name == "Invoke")
.GetParameters()
.Select(p => Expression.Parameter(p.ParameterType))
.ToArray();
var actionInvoke = action.GetType()
.GetRuntimeMethods().First(m => m.Name == "Invoke");
_handler = Expression.Lambda(
eventInfo.EventHandlerType,
Expression.Call(Expression.Constant(action), actionInvoke, eventParameters[0], eventParameters[1]),
eventParameters)
.Compile();
eventInfo.AddEventHandler(item, _handler);
}
/// <summary>
/// Method called when event is raised
/// </summary>
/// <param name="sender">Source of that raised the event</param>
/// <param name="eventArgs">Arguments of the raised event</param>
protected virtual void OnEventRaised(object sender, EventArgs eventArgs)
{
if (Command == null)
{
return;
}
var parameter = CommandParameter;
if (parameter == null && !string.IsNullOrEmpty(EventArgsParameterPath))
{
//Walk the ParameterPath for nested properties.
var propertyPathParts = EventArgsParameterPath.Split('.');
object propertyValue = eventArgs;
foreach (var propertyPathPart in propertyPathParts)
{
var propInfo = propertyValue.GetType().GetRuntimeProperty(propertyPathPart);
if (propInfo == null)
throw new MissingMemberException($"Unable to find {EventArgsParameterPath}");
propertyValue = propInfo.GetValue(propertyValue);
if (propertyValue == null)
{
break;
}
}
parameter = propertyValue;
}
if (parameter == null && eventArgs != null && eventArgs != EventArgs.Empty && EventArgsConverter != null)
{
parameter = EventArgsConverter.Convert(eventArgs, typeof(object), EventArgsConverterParameter,
CultureInfo.CurrentUICulture);
}
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
}
| 41.762846 | 188 | 0.597672 | [
"MIT"
] | Adam--/Prism | src/Forms/Prism.Forms/Behaviors/EventToCommandBehavior.cs | 10,568 | C# |
using System;
using System.Xml.Serialization;
namespace Bonsai.Design.Visualizers
{
/// <summary>
/// Provides the non-generic abstract base class used to wrap any
/// <see cref="DialogTypeVisualizer"/> into a <see cref="MashupTypeVisualizer"/>.
/// </summary>
public abstract class MashupVisualizer : MashupTypeVisualizer
{
/// <summary>
/// Gets the type of the underlying visualizer object.
/// </summary>
public abstract Type VisualizerType { get; }
}
/// <summary>
/// Provides a wrapper to convert any <see cref="DialogTypeVisualizer"/> into a
/// <see cref="MashupTypeVisualizer"/>.
/// </summary>
/// <typeparam name="TVisualizer">The type of the visualizer to be wrapped in the mashup.</typeparam>
[XmlRoot("MashupSettings")]
public class MashupVisualizer<TVisualizer> : MashupVisualizer where TVisualizer : DialogTypeVisualizer, new()
{
/// <summary>
/// Gets the underlying visualizer object.
/// </summary>
[XmlElement("VisualizerSettings")]
public TVisualizer Visualizer { get; set; }
/// <summary>
/// Gets the type of the underlying visualizer object.
/// </summary>
public override Type VisualizerType => typeof(TVisualizer);
/// <inheritdoc/>
public override void Load(IServiceProvider provider)
{
Visualizer ??= new TVisualizer();
Visualizer.Load(provider);
}
/// <inheritdoc/>
public override void Show(object value)
{
Visualizer.Show(value);
}
/// <inheritdoc/>
public override void Unload()
{
Visualizer.Unload();
}
/// <inheritdoc/>
public override IObservable<object> Visualize(IObservable<IObservable<object>> source, IServiceProvider provider)
{
return Visualizer.Visualize(source, provider);
}
/// <inheritdoc/>
public override void SequenceCompleted()
{
Visualizer.SequenceCompleted();
}
}
}
| 30.84058 | 121 | 0.600564 | [
"MIT"
] | glopesdev/bonsai | Bonsai.Design.Visualizers/MashupVisualizer.cs | 2,130 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace Tools
{
public static class GenerateAst
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: generate_ast <output directory>");
Environment.Exit(64);
}
string outputDir = args[0];
DefineAst(outputDir, "Expression", new List<string>()
{
"Assign : Token name, Expression value",
"Binary : Expression left, Token op, Expression right",
"Call : Expression callee, Token parenthesis, List<Expression> arguments",
"Grouping : Expression expression",
"Literal : object value",
"Logical : Expression left, Token op, Expression right",
"Unary : Token op, Expression right",
"Variable : Token name"
}
);
DefineAst(outputDir, "Statement", new List<string>()
{
"Block : List<LoxLangInCSharp.Statement> statements",
"Break : ",
"Continue : ",
"Expression : LoxLangInCSharp.Expression expression",
"Function : Token name, List<Token> parameters, List<LoxLangInCSharp.Statement> body",
"If : LoxLangInCSharp.Expression condition, LoxLangInCSharp.Statement thenBranch, LoxLangInCSharp.Statement elseBranch",
"Print : LoxLangInCSharp.Expression expression",
"Return : Token keyword, LoxLangInCSharp.Expression value",
"Var : Token name, LoxLangInCSharp.Expression initialiser",
"While : LoxLangInCSharp.Expression condition, LoxLangInCSharp.Statement body",
});
}
private static void DefineAst(string outputDir, string baseName, List<string> types)
{
string path = $"{outputDir}/{baseName}.cs";
using StreamWriter writer = new StreamWriter(path);
writer.WriteLine("using System;");
writer.WriteLine("using System.Collections.Generic;");
writer.WriteLine();
writer.WriteLine("namespace LoxLangInCSharp {");
writer.WriteLine($"public abstract class {baseName} {{");
DefineVisitor(writer, baseName, types);
foreach (string type in types)
{
string className = type.Split(":")[0].Trim();
string fields = type.Split(":")[1].Trim();
DefineType(writer, baseName, className, fields);
}
//The base accept() method.
writer.WriteLine();
writer.WriteLine($"public abstract T Accept<T> (IVisitor<T> visitor);");
writer.WriteLine("}");
writer.WriteLine("}");
writer.Close();
}
private static void DefineVisitor(StreamWriter writer, string baseName, List<string> types)
{
writer.WriteLine($"public interface IVisitor<T> {{");
foreach (string type in types)
{
string typeName = type.Split(':')[0].Trim();
writer.WriteLine($"public T Visit{typeName}{baseName} ({typeName} {baseName.ToLower()});");
}
writer.WriteLine("}");
}
private static void DefineType(StreamWriter writer, string baseName, string className, string fieldList)
{
writer.WriteLine($"public class {className} : {baseName} {{");
//Constructor
writer.WriteLine($"public {className} ({fieldList}) {{");
// Store parameters.
List<string> fields = new List<string>();
if (fieldList.Length > 0)
{
fields.AddRange(fieldList.Split(", "));
}
foreach (string field in fields)
{
string name = field.Split(" ")[1];
writer.WriteLine($"this.{name} = {name};");
}
writer.WriteLine("}");
// Visitor pattern.
writer.WriteLine();
writer.WriteLine($"public override T Accept<T> (IVisitor<T> visitor) {{");
writer.WriteLine($"return visitor.Visit{className}{baseName}(this);");
writer.WriteLine("}");
// Fields.
writer.WriteLine();
foreach (string field in fields)
{
writer.WriteLine($"public readonly {field};");
}
writer.WriteLine("}");
}
}
}
| 37.547619 | 144 | 0.525259 | [
"MIT"
] | HuyNguyenAu/LoxLangInCSharp | tools/GenerateAst.cs | 4,733 | C# |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.VisualStudioTools.TestUtilities.SharedProject {
/// <summary>
/// Defines a project type definition, an instance of this gets exported:
///
/// [Export]
/// [ProjectExtension(".njsproj")] // required
/// [ProjectTypeGuid("577B58BB-F149-4B31-B005-FC17C8F4CE7C")] // required
/// [CodeExtension(".js")] // required
/// [SampleCode("console.log('hi');")] // optional
/// internal static ProjectTypeDefinition ProjectTypeDefinition = new ProjectTypeDefinition();
/// </summary>
public sealed class ProjectTypeDefinition {
}
}
| 43.625 | 98 | 0.674785 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/VisualStudio-TestHost | VSTestUtilities/Utilities/SharedProject/ProjectTypeDefinition.cs | 1,398 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Bootstrapper.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Aupli
{
using System.Threading.Tasks;
using Aupli.ApplicationServices;
using Aupli.DomainServices;
using Aupli.Logging.Serilog.ApplicationServices.Player;
using Aupli.Logging.Serilog.ApplicationServices.Volume;
using Aupli.Logging.Serilog.SundewBase;
using Aupli.Logging.Serilog.SystemBoundaries.MusicControl;
using Aupli.Logging.Serilog.SystemBoundaries.Pi;
using Aupli.Logging.Serilog.SystemBoundaries.Pi.Amplifier;
using Aupli.Logging.Serilog.SystemBoundaries.SystemServices;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface.Display;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface.Input;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface.Player;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface.Shutdown;
using Aupli.Logging.Serilog.SystemBoundaries.UserInterface.Volume;
using Aupli.Logging.Serilog.TextView.ApplicationFramework.Input;
using Aupli.Logging.Serilog.TextView.ApplicationFramework.ViewRendering;
using Aupli.SystemBoundaries;
using Aupli.SystemBoundaries.Api;
using Aupli.SystemBoundaries.Bridges.Controls;
using Aupli.SystemBoundaries.MusicControl;
using Aupli.SystemBoundaries.Persistence;
using Aupli.SystemBoundaries.Persistence.Api;
using Aupli.SystemBoundaries.Pi;
using Aupli.SystemBoundaries.SystemServices;
using Aupli.SystemBoundaries.UserInterface;
using Aupli.SystemBoundaries.UserInterface.Ari;
using Pi.IO.GeneralPurpose;
using Serilog;
using Serilog.Events;
using Sundew.Base.Disposal;
using Sundew.Base.Numeric;
using Sundew.TextView.ApplicationFramework;
/// <summary>
/// Bootstraps the application.
/// </summary>
public class Bootstrapper
{
private readonly IApplication application;
private readonly ILogger logger;
private readonly DisposableLogger disposableLogger;
private Disposer? disposer;
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper" /> class.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="logger">The logger.</param>
public Bootstrapper(IApplication application, ILogger logger)
{
this.application = application;
this.logger = logger.ForContext<Bootstrapper>();
this.disposableLogger = new DisposableLogger(this.logger);
}
/// <summary>
/// Starts the asynchronous.
/// </summary>
/// <param name="allowShutdown">if set to <c>true</c> [allow shutdown].</param>
/// <returns>
/// An async task.
/// </returns>
public async Task StartAsync(bool allowShutdown)
{
this.logger.Verbose("Create GpioConnectionDriverFactory");
var gpioConnectionDriverFactory = this.CreateGpioConnectionDriverFactory();
// Create Startup Module
this.logger.Verbose("Create Startup module");
var startupModuleFactory = this.CreateStartupModule(this.application, gpioConnectionDriverFactory);
var startupModule = await startupModuleFactory.StartupModule.ConfigureAwait(false);
this.logger.Verbose("Navigate to Startup view");
await startupModule.NavigateToStartupViewAsync().ConfigureAwait(false);
// Create required ApplicationServices-required system boundaries modules
this.logger.Verbose("Create Repositories Module");
var repositoriesModule = this.CreateRepositoriesModule();
this.logger.Verbose("Initialize Repositories Module");
var repositoriesModuleTask = repositoriesModule.InitializeAsync().ConfigureAwait(false);
// Create domain required application modules
this.logger.Verbose("Create LastPlaylist Module");
var lastPlaylistModule = new LastPlaylistModule(repositoriesModule.LastPlaylistRepository);
// Create domain modules
this.logger.Verbose("Create Playlist Module");
var playlistModule = new PlaylistModule(lastPlaylistModule.LastPlaylistChangeHandler);
// Create application required system boundaries modules
this.logger.Verbose("Create Controls Module");
var controlsModuleFactory = this.CreateControlsModule(gpioConnectionDriverFactory);
var controlsModule = await controlsModuleFactory.ControlsModule;
// Create music control module.
var musicControlModule = this.CreateMusicControlModule();
await musicControlModule.InitializeAsync().ConfigureAwait(false);
this.logger.Verbose("Create System services");
var systemServicesModule = this.CreateSystemServicesModule();
await systemServicesModule.InitializeAsync().ConfigureAwait(false);
// Create application modules
this.logger.Verbose("Create Player Module");
var playerModule = this.CreatePlayerModule(repositoriesModule, playlistModule, musicControlModule);
await playerModule.InitializeAsync().ConfigureAwait(false);
this.logger.Verbose("Create Volume Module");
var volumeModule = new VolumeModule(
controlsModule.Amplifier,
musicControlModule.MusicPlayer,
musicControlModule.MusicPlayer,
repositoriesModule.VolumeRepository,
new Percentage(0.05),
new VolumeServiceLogger(this.logger));
await repositoriesModuleTask;
await volumeModule.InitializeAsync().ConfigureAwait(false);
// Create user interface modules
this.logger.Verbose("Create UserInterface Module");
var userInterfaceModule = new UserInterfaceModule(
this.application,
startupModule,
controlsModule,
musicControlModule.MusicPlayer,
playerModule,
volumeModule,
allowShutdown,
startupModule.LifecycleConfiguration,
await repositoriesModule.ConfigurationRepository.GetConfigurationAsync().ConfigureAwait(false),
new Reporters(
new InteractionControllerLogger(this.logger),
new SystemActivityAggregatorLogger(this.logger),
new IdleMonitorLogger(this.logger),
new PlayerControllerLogger(this.logger),
new VolumeControllerLogger(this.logger),
new ShutdownControllerLogger(this.logger),
new ViewNavigatorLogger(this.logger),
new DisplayStateControllerLogger(this.logger),
this.disposableLogger));
this.disposer = new Disposer(
this.disposableLogger,
new DisposeAction(async () => await repositoriesModule.PlaylistRepository.SaveAsync().ConfigureAwait(false)),
userInterfaceModule,
musicControlModule,
controlsModuleFactory,
startupModuleFactory,
gpioConnectionDriverFactory);
this.logger.Verbose("Initialize Playlist Module");
await playlistModule.InitializeAsync().ConfigureAwait(false);
this.logger.Verbose("Initialize UserInterface Module");
await userInterfaceModule.InitializeAsync().ConfigureAwait(false);
await userInterfaceModule.ViewNavigator.NavigateToPlayerViewAsync().ConfigureAwait(false);
}
/// <summary>
/// Stops the asynchronous.
/// </summary>
/// <returns>An async task.</returns>
public Task StopAsync()
{
this.disposer?.Dispose();
return Task.CompletedTask;
}
/// <summary>
/// Creates the startup module.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="gpioConnectionDriverFactory">The gpio connection driver factory.</param>
/// <returns>
/// The startup module.
/// </returns>
protected virtual IStartupModuleFactory CreateStartupModule(IApplication application, IGpioConnectionDriverFactory gpioConnectionDriverFactory)
{
return new StartupModuleFactory(
application,
gpioConnectionDriverFactory,
"name.val",
"pin26-feature.val",
"greetings.csv",
"last-greeting.val",
new TextViewRendererLogger(this.logger),
new InputManagerLogger(this.logger),
this.disposableLogger,
new TimeIntervalSynchronizerLogger(this.logger));
}
/// <summary>
/// Creates the gpio connection driver factory.
/// </summary>
/// <returns>
/// A <see cref="GpioConnectionDriverFactory" />.
/// </returns>
protected virtual IGpioConnectionDriverFactory CreateGpioConnectionDriverFactory()
{
return new GpioConnectionDriverFactory(false);
}
/// <summary>
/// Gets the repositories.
/// </summary>
/// <returns>The repositories.</returns>
protected virtual IRepositoriesModule CreateRepositoriesModule()
{
return new RepositoriesModule("volume.val", "playlists.json", "last-playlist.json", "configuration.json");
}
/// <summary>
/// Creates the controls module.
/// </summary>
/// <param name="gpioConnectionDriverFactory">The gpio connection driver factory.</param>
/// <returns>A <see cref="ControlsModuleFactory"/>.</returns>
protected virtual IControlsModuleFactory CreateControlsModule(IGpioConnectionDriverFactory gpioConnectionDriverFactory)
{
return new ControlsModuleFactory(
gpioConnectionDriverFactory,
new AmplifierLogger(this.logger, LogEventLevel.Debug),
this.disposableLogger);
}
/// <summary>
/// Creates the music control module.
/// </summary>
/// <returns>A <see cref="MusicControlModule"/>.</returns>
protected virtual MusicControlModule CreateMusicControlModule()
{
return new MusicControlModule(new MusicPlayerLogger(this.logger));
}
/// <summary>Creates the system services module.</summary>
/// <returns>A <see cref="SystemServicesModule"/>.</returns>
protected virtual SystemServicesModule CreateSystemServicesModule()
{
return new SystemServicesModule(
new SystemServicesAwaiterLogger(this.logger),
new WifiConnecterLogger(this.logger));
}
/// <summary>
/// Creates the player module.
/// </summary>
/// <param name="repositoriesModule">The repositories module.</param>
/// <param name="playlistModule">The playlist module.</param>
/// <param name="musicControlModule">The music control module.</param>
/// <returns>A <see cref="PlayerModule"/>.</returns>
protected virtual PlayerModule CreatePlayerModule(IRepositoriesModule repositoriesModule, PlaylistModule playlistModule, MusicControlModule musicControlModule)
{
return new PlayerModule(
repositoriesModule.PlaylistRepository,
playlistModule.LastPlaylistService,
musicControlModule.MusicPlayer,
new PlayerServiceLogger(this.logger));
}
}
} | 45.776119 | 167 | 0.639387 | [
"MIT"
] | hugener/Aupli | Source/Aupli/Bootstrapper.cs | 12,270 | C# |
namespace CleanArchitecture.Web.Endpoints.ToDoItems
{
public class ToDoItemResponse
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsDone { get; set; }
}
} | 26.9 | 52 | 0.613383 | [
"MIT"
] | Kadens/CleanArchitectures | src/CleanArchitecture.Web/Endpoints/ToDoItems/GetById.ToDoItemResponse.cs | 271 | C# |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// Types declaration for SharpDX.X3DAudio namespace.
// This code was generated by a tool.
// Date : 30/06/2015 16:02:47
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#if DESKTOP_APP
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace SharpDX.X3DAudio {
#pragma warning disable 419
#pragma warning disable 1587
#pragma warning disable 1574
/// <summary>
/// Functions
/// </summary>
/// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.X3DAudio.X3DAudio']/*"/>
internal class X3DAudio17 {
/// <summary>
/// <p>Calculates DSP settings with respect to 3D parameters.</p>
/// </summary>
/// <param name="instance"><dd> <p>3D audio instance handle. Call <strong><see cref="SharpDX.X3DAudio.X3DAudio.X3DAudioInitialize"/></strong> to get this handle.</p> </dd></param>
/// <param name="listenerRef"><dd> <p>Pointer to an <strong><see cref="SharpDX.X3DAudio.Listener"/></strong> representing the point of reception.</p> </dd></param>
/// <param name="emitterRef"><dd> <p>Pointer to an <strong><see cref="SharpDX.X3DAudio.Emitter"/></strong> representing the sound source.</p> </dd></param>
/// <param name="flags"><dd> <table> <tr><th>Value</th><th>Description</th></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.Matrix"/></td><td>Enables matrix coefficient table calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.Delay"/></td><td>Enables delay time array calculation (stereo only).?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.LpfDirect"/></td><td>Enables low pass filter (LPF) direct-path coefficient calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.LpfReverb"/></td><td>Enables LPF reverb-path coefficient calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.Reverb"/></td><td>Enables reverb send level calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.Doppler"/></td><td>Enables Doppler shift factor calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.EmitterAngle"/></td><td>Enables emitter-to-listener interior angle calculation.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.ZeroCenter"/></td><td>Fills the center channel with silence. This flag allows you to keep a 6-channel matrix so you do not have to remap the channels, but the center channel will be silent. This flag is only valid if you also set <see cref="SharpDX.X3DAudio.CalculateFlags.Matrix"/>.?</td></tr> <tr><td><see cref="SharpDX.X3DAudio.CalculateFlags.RedirectToLfe"/></td><td> Applies an equal mix of all source channels to a low frequency effect (LFE) destination channel. It only applies to matrix calculations with a source that does not have an LFE channel and a destination that does have an LFE channel. This flag is only valid if you also set <see cref="SharpDX.X3DAudio.CalculateFlags.Matrix"/>.?</td></tr> </table> <p>?</p> </dd></param>
/// <param name="dSPSettingsRef"><dd> <p>Pointer to an <strong><see cref="SharpDX.X3DAudio.DspSettings"/></strong> structure that receives the calculation results.</p> </dd></param>
/// <remarks>
/// <p>You typically call <strong><see cref="SharpDX.X3DAudio.X3DAudio.X3DAudioCalculate"/></strong> once for each pair of emitting objects and listeners in the scene. After each call, to apply the 3D effects, the app manually applies the calculation results at <em>pDSPSettings</em> to the XAUDIO2 graph. For more info, see How to: Integrate X3DAudio with XAudio2.</p><p><strong>Important</strong>?? The listener and emitter values must be valid. Floating-point specials (NaN, QNaN, +INF, -INF) can cause the entire audio output to go silent if introduced into a running audio graph.</p>
/// </remarks>
/// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='X3DAudioCalculate']/*"/>
/// <msdn-id>microsoft.directx_sdk.x3daudio.x3daudiocalculate</msdn-id>
/// <unmanaged>void X3DAudioCalculate([In] const X3DAUDIOHANDLE* Instance,[In] const X3DAUDIO_LISTENER* pListener,[In] const X3DAUDIO_EMITTER* pEmitter,[In] X3DAudioCalculateFlags Flags,[In] void* pDSPSettings)</unmanaged>
/// <unmanaged-short>X3DAudioCalculate</unmanaged-short>
public static void X3DAudioCalculate(ref SharpDX.X3DAudio.X3DAudioHandle instance, SharpDX.X3DAudio.Listener listenerRef, SharpDX.X3DAudio.Emitter emitterRef, SharpDX.X3DAudio.CalculateFlags flags, System.IntPtr dSPSettingsRef) {
unsafe {
var listenerRef_ = new SharpDX.X3DAudio.Listener.__Native();
listenerRef.__MarshalTo(ref listenerRef_);
var emitterRef_ = new SharpDX.X3DAudio.Emitter.__Native();
emitterRef.__MarshalTo(ref emitterRef_);
fixed (void* instance_ = &instance)
X3DAudioCalculate_(instance_, &listenerRef_, &emitterRef_, unchecked((int)flags), (void*)dSPSettingsRef);
listenerRef.__MarshalFree(ref listenerRef_);
emitterRef.__MarshalFree(ref emitterRef_);
}
}
[DllImport("X3DAudio1_7.dll", EntryPoint = "X3DAudioCalculate", CallingConvention = CallingConvention.Cdecl)]
private unsafe static extern void X3DAudioCalculate_(void* arg0,void* arg1,void* arg2,int arg3,void* arg4);
/// <summary>
/// <p>Sets all global 3D audio constants.</p>
/// </summary>
/// <param name="speakerChannelMask"><dd> <p>Assignment of channels to speaker positions. This value must not be zero. The only permissible value on Xbox 360 is SPEAKER_XBOX.</p> </dd></param>
/// <param name="speedOfSound"><dd> <p>Speed of sound, in user-defined world units per second. Use this value only for doppler calculations. It must be greater than or equal to FLT_MIN.</p> </dd></param>
/// <param name="instance"><dd> <p>3D audio instance handle. Use this handle when you call <strong><see cref="SharpDX.X3DAudio.X3DAudio.X3DAudioCalculate"/></strong>.</p> </dd></param>
/// <returns><p>This function does not return a value.</p></returns>
/// <remarks>
/// <p><strong>X3DAUDIO_HANDLE</strong> is an opaque data structure. Because the operating system doesn't allocate any additional storage for the 3D audio instance handle, you don't need to free or close it.</p>
/// </remarks>
/// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='X3DAudioInitialize']/*"/>
/// <msdn-id>microsoft.directx_sdk.x3daudio.x3daudioinitialize</msdn-id>
/// <unmanaged>HRESULT X3DAudioInitialize([In] SPEAKER_FLAGS SpeakerChannelMask,[In] float SpeedOfSound,[Out] X3DAUDIOHANDLE* Instance)</unmanaged>
/// <unmanaged-short>X3DAudioInitialize</unmanaged-short>
public static void X3DAudioInitialize(SharpDX.Multimedia.Speakers speakerChannelMask, float speedOfSound, out SharpDX.X3DAudio.X3DAudioHandle instance) {
unsafe {
instance = new SharpDX.X3DAudio.X3DAudioHandle();
SharpDX.Result __result__;
fixed (void* instance_ = &instance)
__result__=
X3DAudioInitialize_(unchecked((int)speakerChannelMask), speedOfSound, instance_);
__result__.CheckError();
}
}
[DllImport("X3DAudio1_7.dll", EntryPoint = "X3DAudioInitialize", CallingConvention = CallingConvention.Cdecl)]
private unsafe static extern int X3DAudioInitialize_(int arg0,float arg1,void* arg2);
}
}
#endif | 87.27619 | 1,809 | 0.686272 | [
"MIT"
] | RobJellinghaus/SharpDX | Source/SharpDX.XAudio2/X3DAudio/X3DAudio17.cs | 9,164 | 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.Linq;
using Xunit;
namespace System.Collections.Tests
{
public abstract partial class Stack_Generic_Tests<T> : IGenericSharedAPI_Tests<T>
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Stack_Generic_TryPop_AllElements(int count)
{
Stack<T> stack = GenericStackFactory(count);
List<T> elements = stack.ToList();
foreach (T element in elements)
{
T result;
Assert.True(stack.TryPop(out result));
Assert.Equal(element, result);
}
}
[Fact]
public void Stack_Generic_TryPop_EmptyStack_ReturnsFalse()
{
T result;
Assert.False(new Stack<T>().TryPop(out result));
Assert.Equal(default(T), result);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Stack_Generic_TryPeek_AllElements(int count)
{
Stack<T> stack = GenericStackFactory(count);
List<T> elements = stack.ToList();
foreach (T element in elements)
{
T result;
Assert.True(stack.TryPeek(out result));
Assert.Equal(element, result);
stack.Pop();
}
}
[Fact]
public void Stack_Generic_TryPeek_EmptyStack_ReturnsFalse()
{
T result;
Assert.False(new Stack<T>().TryPeek(out result));
Assert.Equal(default(T), result);
}
}
}
| 30.45 | 85 | 0.573071 | [
"MIT"
] | 2E0PGS/corefx | src/System.Collections/tests/Generic/Stack/Stack.Generic.Tests.netcoreapp.cs | 1,829 | C# |
// Project: Aguafrommars/TheIdServer
// Copyright (c) 2020 @Olivier Lefebvre
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace Aguacongas.TheIdServer.BlazorApp.Components.Form
{
public class ButtonBase : ComponentBase
{
[Parameter]
public string CssSubClass { get; set; }
[Parameter]
public string Type { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> Clicked { get; set; }
}
}
| 25.043478 | 66 | 0.673611 | [
"Apache-2.0"
] | markjohnnah/TheIdServer | src/BlazorApp/Aguacongas.TheIdServer.BlazorApp.Components/Form/ButtonBase.cs | 578 | C# |
namespace bstrkr.core.config
{
public interface IConfigManager
{
BusTrackerConfig GetConfig();
}
} | 17 | 37 | 0.663866 | [
"BSD-2-Clause"
] | dkataskin/bstrkr | bstrkr.mobile/bstrkr.core/Config/IConfigManager.cs | 121 | C# |
namespace AngleSharp.Extensions
{
using AngleSharp.Attributes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
/// <summary>
/// Some methods for working with bare objects.
/// </summary>
[DebuggerStepThrough]
static class ObjectExtensions
{
/// <summary>
/// Transforms the values of the object into a dictionary of strings.
/// </summary>
/// <param name="values">The object instance to convert.</param>
/// <returns>A dictionary mapping field names to values.</returns>
public static Dictionary<String, String> ToDictionary(this Object values)
{
var symbols = new Dictionary<String, String>();
if (values != null)
{
var properties = values.GetType().GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(values, null) ?? String.Empty;
symbols.Add(property.Name, value.ToString());
}
}
return symbols;
}
/// <summary>
/// Tries to obtain the given key, otherwise returns the default value.
/// </summary>
/// <typeparam name="T">The struct type.</typeparam>
/// <param name="values">The dictionary for the lookup.</param>
/// <param name="key">The key to look for.</param>
/// <returns>A nullable struct type.</returns>
public static T? TryGet<T>(this IDictionary<String, Object> values, String key)
where T : struct
{
var value = default(Object);
if (values.TryGetValue(key, out value) && value is T)
{
return (T)value;
}
return null;
}
/// <summary>
/// Tries to obtain the given key, otherwise returns null.
/// </summary>
/// <param name="values">The dictionary for the lookup.</param>
/// <param name="key">The key to look for.</param>
/// <returns>An object instance or null.</returns>
public static Object TryGet(this IDictionary<String, Object> values, String key)
{
var value = default(Object);
if (values.TryGetValue(key, out value))
{
return value;
}
return null;
}
/// <summary>
/// Gets the value of the given key, otherwise the provided default
/// value.
/// </summary>
/// <typeparam name="T">The type of the keys.</typeparam>
/// <typeparam name="U">The type of the value.</typeparam>
/// <param name="values">The dictionary for the lookup.</param>
/// <param name="key">The key to look for.</param>
/// <param name="defaultValue">The provided fallback value.</param>
/// <returns>The value or the provided fallback.</returns>
public static U GetOrDefault<T, U>(this IDictionary<T, U> values, T key, U defaultValue)
{
U value;
return values.TryGetValue(key, out value) ? value : defaultValue;
}
/// <summary>
/// Constraints the given value between the min and max values.
/// </summary>
/// <param name="value">The value to limit.</param>
/// <param name="min">The lower boundary.</param>
/// <param name="max">The upper boundary.</param>
/// <returns>The value in the [min, max] range.</returns>
public static Double Constraint(this Double value, Double min, Double max)
{
return value < min ? min : (value > max ? max : value);
}
/// <summary>
/// Retrieves a string describing the error of a given error code.
/// </summary>
/// <param name="code">A specific error code.</param>
/// <returns>The description of the error.</returns>
public static String GetMessage<T>(this T code)
where T : struct
{
var type = typeof(T).GetTypeInfo();
var field = type.GetDeclaredField(code.ToString());
var attr = field.GetCustomAttribute<DomDescriptionAttribute>();
if (attr != null)
{
return attr.Description;
}
return "An unknown error occurred.";
}
}
}
| 35.608 | 96 | 0.550887 | [
"MIT"
] | forprog/AngleSharp | src/AngleSharp/Extensions/ObjectExtensions.cs | 4,453 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Is.Net.Helpers
{
public class TextHelper
{
public static Lazy<TextHelper> Instance = new Lazy<TextHelper>(() => new TextHelper());
#region PrivateMethods
private bool RegexMatch(string value, string pattern)
{
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
//TODO do we need null check? we can throw exception here.
return !string.IsNullOrEmpty(value) && reg.IsMatch(value);
}
#endregion
public bool IsSpace(string value)
{
return value == " ";
}
public bool IsSpace(char value)
{
return value == ' ';
}
public bool IsURL(string value)
{
return RegexMatch(value, @"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$");
}
public bool IsSocialSecurityNumber(string value)
{
return RegexMatch(value, @"^\d{3}-\d{2}-\d{4}$");
}
public bool IsEmail(string value)
{
return RegexMatch(value, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
}
public bool IsName(string value, int limit = 40)
{
//TODO do we need turkish characters or this method
return RegexMatch(value, @"^[a-zA-Z''-'\sçÇöÖşŞıİğĞüÜ]{1," + limit + "}$");
}
public bool IsTurkishIdentity(string value)
{
bool result = false;
if (!string.IsNullOrEmpty(value) && value.Length == 11)
{
long ATCNO, BTCNO, identity;
long C1, C2, C3, C4, C5, C6, C7, C8, C9, Q1, Q2;
identity = long.Parse(value);
ATCNO = identity / 100;
BTCNO = identity / 100;
C1 = ATCNO % 10; ATCNO = ATCNO / 10;
C2 = ATCNO % 10; ATCNO = ATCNO / 10;
C3 = ATCNO % 10; ATCNO = ATCNO / 10;
C4 = ATCNO % 10; ATCNO = ATCNO / 10;
C5 = ATCNO % 10; ATCNO = ATCNO / 10;
C6 = ATCNO % 10; ATCNO = ATCNO / 10;
C7 = ATCNO % 10; ATCNO = ATCNO / 10;
C8 = ATCNO % 10; ATCNO = ATCNO / 10;
C9 = ATCNO % 10; ATCNO = ATCNO / 10;
Q1 = ((10 - ((((C1 + C3 + C5 + C7 + C9) * 3) + (C2 + C4 + C6 + C8)) % 10)) % 10);
Q2 = ((10 - (((((C2 + C4 + C6 + C8) + Q1) * 3) + (C1 + C3 + C5 + C7 + C9)) % 10)) % 10);
result = ((BTCNO * 100) + (Q1 * 10) + Q2 == identity);
}
return result;
}
public bool IsConfirmation(string value)
{
List<string> words = new List<string> {
"true", "evet", "e", "ok", "okay", "yes", "y", "si", "oui", "ja", "sim", "ken", "sea", "jes", "hai", "ndiyo", "gee", "ano", "igen", "da"
};
return words.Contains(value.ToLowerInvariant());
}
public bool IsIP(string value)
{
System.Net.IPAddress ip = null;
return !string.IsNullOrEmpty(value) && System.Net.IPAddress.TryParse(value, out ip);
}
public bool IsCreditCard(string value)
{
int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 };
int checksum = 0;
char[] chars = value.ToCharArray();
for (int i = chars.Length - 1; i > -1; i--)
{
int j = ((int)chars[i]) - 48;
checksum += j;
if (((i - chars.Length) % 2) == 0)
checksum += DELTAS[j];
}
return ((checksum % 10) == 0);
}
public bool IsAlphaNumeric(string value)
{
return RegexMatch(value, @"^[a-zA-Z0-9çÇöÖşŞıİğĞüÜ]*$");
}
public bool IsPalindrome(string value)
{
bool retVal = true;
for (int i = 0; i < value.Length / 2; i++)
{
if (value[i] != value[value.Length - i - 1])
{
retVal = false;
break;
}
}
return retVal;
}
}
}
| 32.737226 | 221 | 0.441918 | [
"MIT"
] | olcay/Is.Net | Is.Net/Helpers/TextHelper.cs | 4,511 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class PlayerAnimator : CharacterAnimator {
public WeaponAnimation[] weaponAnimations;
private WeaponAnimation currentWeaponAnimation;
void Awake() {
currentWeaponAnimation = weaponAnimations [0];
}
protected override void Start() {
base.Start ();
}
protected override void OnAttack() {
if (currentWeaponAnimation != null) {
int attackIndex = Random.Range (0, currentWeaponAnimation.numAnimations);
animator.SetFloat ("Attack Index", attackIndex);
animator.SetFloat ("Weapon Index", currentWeaponAnimation.weaponIndex);
}
base.OnAttack ();
}
[System.Serializable]
public class WeaponAnimation {
public int weaponIndex;
public int numAnimations;
}
}
| 21.648649 | 76 | 0.751561 | [
"Apache-2.0"
] | Bananenschnitte/Tales-of-Osh | Tales of Osh/Assets/Scripts/Anim/PlayerAnimator.cs | 803 | C# |
// -----------------------------------------------------------------------
// <copyright file="ILayoutRoot.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Layout
{
public interface ILayoutRoot : ILayoutable
{
Size ClientSize { get; }
ILayoutManager LayoutManager { get; }
}
}
| 28.9375 | 75 | 0.455724 | [
"MIT"
] | GeorgeHahn/Perspex | Perspex.Layout/ILayoutRoot.cs | 465 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Models.Entities
{
[Table("Fisicos")]
public class Fisico
{
[Key]
[Column("IdFisico")]
public int Id { get; set; }
[Column("areaTerreno", TypeName = "decimal(9,2)")]
public decimal AreaTerreno { get; set; }
[Column("areaEdificada", TypeName = "decimal(9,2)")]
public decimal AreaEdificada { get; set; }
[Column("idFaceQuadra")]
public int FaceQuadraId { get; set; }
public virtual FaceQuadra FaceQuadra { get; set; }
public virtual ICollection<RoteiroSelecaoItemFisico> RoteiroSelecaoItens { get; set; }
}
}
| 27.107143 | 94 | 0.645586 | [
"MIT"
] | Vitor-Xavier/CalculationEngine | src/Models/Entities/Fisico.cs | 761 | C# |
using System;
using System.ComponentModel;
using Maoui.Forms.Extensions;
using Xamarin.Forms;
namespace Maoui.Forms.Renderers
{
public class ScrollViewRenderer : VisualElementRenderer<ScrollView>
{
bool disposed = false;
protected override void OnElementChanged(ElementChangedEventArgs<ScrollView> e)
{
if (e.OldElement != null)
e.OldElement.ScrollToRequested -= Element_ScrollToRequested;
if (e.NewElement != null)
{
Style.Overflow = "scroll";
e.NewElement.ScrollToRequested += Element_ScrollToRequested;
}
base.OnElementChanged(e);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && !disposed)
{
if (Element != null)
Element.ScrollToRequested -= Element_ScrollToRequested;
disposed = true;
}
}
void Element_ScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
var oe = (ITemplatedItemsListScrollToRequestedEventArgs)e;
var item = oe.Item;
var group = oe.Group;
if (e.Mode == ScrollToMode.Position)
{
Send(Maoui.Message.Set(Id, "scrollTop", e.ScrollY));
Send(Maoui.Message.Set(Id, "scrollLeft", e.ScrollX));
}
else
{
switch (e.Position)
{
case ScrollToPosition.Start:
Send(Maoui.Message.Set(Id, "scrollTop", 0));
break;
case ScrollToPosition.End:
Send(Maoui.Message.Set(Id, "scrollTop", new Maoui.Message.PropertyReference { TargetId = Id, Key = "scrollHeight" }));
break;
}
}
}
}
}
| 30.921875 | 142 | 0.522486 | [
"MIT"
] | mrmandrake/maoui | Maoui.Forms/Renderers/ScrollViewRenderer.cs | 1,981 | C# |
namespace NetworkOperator.CommunicationInterfaces.ParallelMultiTypeStreaming.ParallelStreaming.InterleavingStreaming.ScheduledStreaming
{
public interface IStreamScheduler
{
IDataSplitter DataSplitter { get; }
IPacketProcessor PacketProcessor { get; }
int MaxParallelTransfers { get; }
}
}
| 32.7 | 136 | 0.75841 | [
"MIT"
] | vabalcar/NetworkOperator | Sources/CommunicationInterfaces/ParallelNetworkStream/ParallelMultiTypeStreaming/ParallelStreaming/InterleavingStreaming/ScheduledStreaming/IStreamScheduler.cs | 329 | C# |
using System.Reactive;
using System.Reflection;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.X11;
using MessageCommunicator.TestGui.ViewServices;
using ReactiveUI;
namespace MessageCommunicator.TestGui.Views
{
public class ReleaseCheckViewModel : OwnViewModelBase
{
private string _statusText;
private Image? _icon;
public string StatusText
{
get => _statusText;
set
{
if (_statusText != value)
{
_statusText = value;
this.RaisePropertyChanged(nameof(this.StatusText));
}
}
}
public Image? Icon
{
get => _icon;
set
{
if (!ReferenceEquals(_icon, value))
{
_icon = value;
this.RaisePropertyChanged(nameof(this.Icon));
}
}
}
public ReactiveCommand<Unit, Unit> Command_GoToReleases
{
get;
}
public ReleaseCheckViewModel()
{
_statusText = "Checking for newer releases...";
this.Command_GoToReleases = ReactiveCommand.Create(() =>
{
CommonUtil.OpenUrlInBrowser("https://github.com/RolandKoenig/MessageCommunicator/releases");
});
}
/// <summary>
/// Triggers the request for latest release.
/// </summary>
public void TriggerRequest()
{
ReleaseInformation? latestReleaseInfo = null;
var taskQueryReleaseInfo = ReleaseOverview.TryGetLatestReleaseAsync()
.ContinueWith(task =>
{
if (!task.IsFaulted)
{
latestReleaseInfo = task.Result;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
// Try request latest release info for a maximum of 5 seconds
Task.WhenAny(taskQueryReleaseInfo, Task.Delay(5000))
.ContinueWith(task =>
{
this.ProcessLatestReleaseInfo(latestReleaseInfo);
}, TaskScheduler.FromCurrentSynchronizationContext());
this.TrySetIcon("IconRefresh");
}
/// <summary>
/// Sets the given <see cref="ReleaseInformation"/> as the latest release.
/// </summary>
public void ProcessLatestReleaseInfo(ReleaseInformation? releaseInfo)
{
if (releaseInfo == null)
{
this.StatusText = "Unable to check for newer releases";
this.TrySetIcon("IconWarning");
return;
}
var currentVersion = Assembly.GetExecutingAssembly().GetName().Version!;
if (releaseInfo.Version > currentVersion)
{
this.StatusText = $"You are running an older release (newest version is {releaseInfo.Version.ToString(3)}";
this.TrySetIcon("IconWarning");
}
else if (releaseInfo.Version == currentVersion)
{
this.StatusText = $"You are running the newest release";
this.TrySetIcon("IconCheck");
}
else
{
// Should only be possible in development environment
this.StatusText = "This is a development build";
this.TrySetIcon("IconLab");
}
}
private void TrySetIcon(string iconResourceName)
{
var iconResource = this.GetViewService<IViewResourceService>().TryGetViewResource(iconResourceName) as Drawing;
if (iconResource == null)
{
this.Icon = null;
return;
}
this.Icon = new Image()
{
Width = 16.0,
Height = 16.0,
Margin = new Thickness(2.0),
Source = new VectorIconDrawingImage(){ Drawing = iconResource}
};
}
}
} | 31.522388 | 123 | 0.518229 | [
"MIT"
] | RolandKoenig/MessageCommunicator | src/MessageCommunicator.TestGui/Views/_ReleaseCheck/ReleaseCheckViewModel.cs | 4,226 | C# |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Model = Discord.API.Connection;
namespace Discord.Rest
{
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestConnection : IConnection
{
/// <inheritdoc />
public string Id { get; private set; }
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public string Type { get; private set; }
/// <inheritdoc />
public bool? IsRevoked { get; private set; }
/// <inheritdoc />
public IReadOnlyCollection<IIntegration> Integrations { get; private set; }
/// <inheritdoc />
public bool Verified { get; private set; }
/// <inheritdoc />
public bool FriendSync { get; private set; }
/// <inheritdoc />
public bool ShowActivity { get; private set; }
/// <inheritdoc />
public ConnectionVisibility Visibility { get; private set; }
internal BaseDiscordClient Discord { get; }
internal RestConnection(BaseDiscordClient discord) {
Discord = discord;
}
internal static RestConnection Create(BaseDiscordClient discord, Model model)
{
var entity = new RestConnection(discord);
entity.Update(model);
return entity;
}
internal void Update(Model model)
{
Id = model.Id;
Name = model.Name;
Type = model.Type;
IsRevoked = model.Revoked.IsSpecified ? model.Revoked.Value : null;
Integrations = model.Integrations.IsSpecified ?model.Integrations.Value
.Select(intergration => RestIntegration.Create(Discord, null, intergration)).ToImmutableArray() : null;
Verified = model.Verified;
FriendSync = model.FriendSync;
ShowActivity = model.ShowActivity;
Visibility = model.Visibility;
}
/// <summary>
/// Gets the name of the connection.
/// </summary>
/// <returns>
/// Name of the connection.
/// </returns>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}, {Type}{(IsRevoked.GetValueOrDefault() ? ", Revoked" : "")})";
}
}
| 34.985507 | 119 | 0.590721 | [
"MIT"
] | EpicOfficer/Discord.Net | src/Discord.Net.Rest/Entities/Users/RestConnection.cs | 2,414 | 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 rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Rekognition.Model
{
/// <summary>
/// Container for the parameters to the StartContentModeration operation.
/// Starts asynchronous detection of unsafe content in a stored video.
///
///
/// <para>
/// Amazon Rekognition Video can moderate content in a video stored in an Amazon S3 bucket.
/// Use <a>Video</a> to specify the bucket name and the filename of the video. <code>StartContentModeration</code>
/// returns a job identifier (<code>JobId</code>) which you use to get the results of
/// the analysis. When unsafe content analysis is finished, Amazon Rekognition Video publishes
/// a completion status to the Amazon Simple Notification Service topic that you specify
/// in <code>NotificationChannel</code>.
/// </para>
///
/// <para>
/// To get the results of the unsafe content analysis, first check that the status value
/// published to the Amazon SNS topic is <code>SUCCEEDED</code>. If so, call <a>GetContentModeration</a>
/// and pass the job identifier (<code>JobId</code>) from the initial call to <code>StartContentModeration</code>.
///
/// </para>
///
/// <para>
/// For more information, see Detecting Unsafe Content in the Amazon Rekognition Developer
/// Guide.
/// </para>
/// </summary>
public partial class StartContentModerationRequest : AmazonRekognitionRequest
{
private string _clientRequestToken;
private string _jobTag;
private float? _minConfidence;
private NotificationChannel _notificationChannel;
private Video _video;
/// <summary>
/// Gets and sets the property ClientRequestToken.
/// <para>
/// Idempotent token used to identify the start request. If you use the same token with
/// multiple <code>StartContentModeration</code> requests, the same <code>JobId</code>
/// is returned. Use <code>ClientRequestToken</code> to prevent the same job from being
/// accidently started more than once.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string ClientRequestToken
{
get { return this._clientRequestToken; }
set { this._clientRequestToken = value; }
}
// Check to see if ClientRequestToken property is set
internal bool IsSetClientRequestToken()
{
return this._clientRequestToken != null;
}
/// <summary>
/// Gets and sets the property JobTag.
/// <para>
/// An identifier you specify that's returned in the completion notification that's published
/// to your Amazon Simple Notification Service topic. For example, you can use <code>JobTag</code>
/// to group related jobs and identify them in the completion notification.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string JobTag
{
get { return this._jobTag; }
set { this._jobTag = value; }
}
// Check to see if JobTag property is set
internal bool IsSetJobTag()
{
return this._jobTag != null;
}
/// <summary>
/// Gets and sets the property MinConfidence.
/// <para>
/// Specifies the minimum confidence that Amazon Rekognition must have in order to return
/// a moderated content label. Confidence represents how certain Amazon Rekognition is
/// that the moderated content is correctly identified. 0 is the lowest confidence. 100
/// is the highest confidence. Amazon Rekognition doesn't return any moderated content
/// labels with a confidence level lower than this specified value. If you don't specify
/// <code>MinConfidence</code>, <code>GetContentModeration</code> returns labels with
/// confidence values greater than or equal to 50 percent.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=100)]
public float MinConfidence
{
get { return this._minConfidence.GetValueOrDefault(); }
set { this._minConfidence = value; }
}
// Check to see if MinConfidence property is set
internal bool IsSetMinConfidence()
{
return this._minConfidence.HasValue;
}
/// <summary>
/// Gets and sets the property NotificationChannel.
/// <para>
/// The Amazon SNS topic ARN that you want Amazon Rekognition Video to publish the completion
/// status of the unsafe content analysis to.
/// </para>
/// </summary>
public NotificationChannel NotificationChannel
{
get { return this._notificationChannel; }
set { this._notificationChannel = value; }
}
// Check to see if NotificationChannel property is set
internal bool IsSetNotificationChannel()
{
return this._notificationChannel != null;
}
/// <summary>
/// Gets and sets the property Video.
/// <para>
/// The video in which you want to detect unsafe content. The video must be stored in
/// an Amazon S3 bucket.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public Video Video
{
get { return this._video; }
set { this._video = value; }
}
// Check to see if Video property is set
internal bool IsSetVideo()
{
return this._video != null;
}
}
} | 37.994186 | 118 | 0.627391 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/StartContentModerationRequest.cs | 6,535 | C# |
using System;
using System.Reflection;
using System.Runtime.Caching;
using Common.Logging;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
namespace ToolKit.Data.NHibernate
{
/// <summary>
/// A Abstract Implementation of A Database Handler Class Using NHibernate.
/// </summary>
public abstract class NHibernateDatabaseBase : DatabaseBase
{
private static readonly object _cacheLock = new object();
private static readonly CacheItemPolicy _cachePolicy = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddDays(1))
};
private static readonly ILog _log = LogManager.GetLogger<NHibernateDatabaseBase>();
/// <summary>
/// Initializes a new instance of the <see cref="NHibernateDatabaseBase"/> class.
/// </summary>
/// <param name="assemblyContainingMappings">The assembly containing mappings.</param>
protected NHibernateDatabaseBase(Assembly assemblyContainingMappings)
{
AssemblyContainingMappings = assemblyContainingMappings;
}
/// <summary>
/// Gets the database instance.
/// </summary>
public static new NHibernateDatabaseBase Instance => _instance as NHibernateDatabaseBase;
/// <summary>
/// Gets the assembly containing mappings.
/// </summary>
public Assembly AssemblyContainingMappings { get; }
/// <summary>
/// Gets or sets the cache of Session Factories.
/// </summary>
protected static ObjectCache Cache { get; set; } = MemoryCache.Default;
/// <summary>
/// This method will Initializes the database in a class that inherits from this base class.
/// </summary>
/// <param name="initialization">The action to preform to initialize database.</param>
public abstract override void InitializeDatabase(Action initialization);
/// <summary>
/// Find and Return the Session Factory for the specified session name.
/// </summary>
/// <param name="sessionName">The name of the database session.</param>
/// <returns>the Session Factory for the specified session name.</returns>
public ISessionFactory SessionFactory(string sessionName)
=> GetOrCreateSessionFactory(sessionName);
/// <summary>
/// Builds the database schema.
/// </summary>
/// <param name="config">The properties and mapping documents to be used.</param>
protected static void BuildSchema(Configuration config) =>
new SchemaExport(config).Create(false, UnitTests);
/// <summary>
/// contains the details about the NHibernate Configuration.
/// </summary>
/// <returns>the NHibernate Configuration.</returns>
protected abstract IPersistenceConfigurer DatabaseConfigurer();
private ISessionFactory GetOrCreateSessionFactory(string sessionName)
{
if (Cache.Contains(sessionName))
{
_log.Debug($"Returning Existing session: {sessionName}");
}
else
{
lock (_cacheLock)
{
if (!Cache.Contains(sessionName))
{
_log.Debug($"Creating a new session: {sessionName}");
var sessionFactory = Fluently.Configure()
.Database(DatabaseConfigurer)
.Mappings(m => m.FluentMappings.AddFromAssembly(AssemblyContainingMappings))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
Cache.Set(sessionName, sessionFactory, _cachePolicy);
}
}
}
return Cache[sessionName] as ISessionFactory;
}
}
}
| 37.757009 | 104 | 0.607921 | [
"Apache-2.0"
] | dcjulian29/toolkit | ToolKit.Data.NHibernate/NHibernateDatabaseBase.cs | 4,040 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Internal.JitInterface
{
public static class CORINFO
{
// CORINFO_MAXINDIRECTIONS is the maximum number of
// indirections used by runtime lookups.
// This accounts for up to 2 indirections to get at a dictionary followed by a possible spill slot
public const uint MAXINDIRECTIONS = 4;
public const ushort USEHELPER = 0xffff;
}
public struct CORINFO_METHOD_STRUCT_
{
internal static unsafe CORINFO_METHOD_STRUCT_* Construct(int i)
{
return (CORINFO_METHOD_STRUCT_*)((i + 1) << 4);
}
internal static unsafe int GetValue(CORINFO_METHOD_STRUCT_* val)
{
return ((int)val - 1) >> 4;
}
}
public struct CORINFO_FIELD_STRUCT_
{
internal static unsafe CORINFO_FIELD_STRUCT_* Construct(int i)
{
return (CORINFO_FIELD_STRUCT_*)((i + 1) << 4);
}
internal static unsafe int GetValue(CORINFO_FIELD_STRUCT_* val)
{
return ((int)val - 1) >> 4;
}
}
public struct CORINFO_CLASS_STRUCT_
{
internal static unsafe CORINFO_CLASS_STRUCT_* Construct(int i)
{
return (CORINFO_CLASS_STRUCT_*)((i + 1) << 4);
}
internal static unsafe int GetValue(CORINFO_CLASS_STRUCT_* val)
{
return ((int)val - 1) >> 4;
}
}
public struct CORINFO_ARG_LIST_STRUCT_
{
}
public struct CORINFO_MODULE_STRUCT_
{
internal static unsafe CORINFO_MODULE_STRUCT_* Construct(int i)
{
return (CORINFO_MODULE_STRUCT_*)((i + 1) << 4);
}
internal static unsafe int GetValue(CORINFO_MODULE_STRUCT_* val)
{
return ((int)val - 1) >> 4;
}
}
public struct CORINFO_ASSEMBLY_STRUCT_
{
}
public struct CORINFO_CONTEXT_STRUCT
{
}
public struct CORINFO_GENERIC_STRUCT_
{
}
public struct CORINFO_JUST_MY_CODE_HANDLE_
{
}
public struct CORINFO_VarArgInfo
{
}
public enum _EXCEPTION_POINTERS
{ }
public unsafe struct CORINFO_SIG_INST
{
public uint classInstCount;
public CORINFO_CLASS_STRUCT_** classInst; // (representative, not exact) instantiation for class type variables in signature
public uint methInstCount;
public CORINFO_CLASS_STRUCT_** methInst; // (representative, not exact) instantiation for method type variables in signature
}
public enum mdToken : uint
{ }
public enum HRESULT {
E_NOTIMPL = -2147467263
}
public unsafe struct CORINFO_SIG_INFO
{
public CorInfoCallConv callConv;
public CORINFO_CLASS_STRUCT_* retTypeClass; // if the return type is a value class, this is its handle (enums are normalized)
public CORINFO_CLASS_STRUCT_* retTypeSigClass;// returns the value class as it is in the sig (enums are not converted to primitives)
public byte _retType;
public CorInfoSigInfoFlags flags; // used by IL stubs code
public ushort numArgs;
public CORINFO_SIG_INST sigInst; // information about how type variables are being instantiated in generic code
public CORINFO_ARG_LIST_STRUCT_* args;
public byte* pSig;
public uint cbSig;
public CORINFO_MODULE_STRUCT_* scope; // passed to getArgClass
public mdToken token;
public CorInfoType retType { get { return (CorInfoType)_retType; } set { _retType = (byte)value; } }
private CorInfoCallConv getCallConv() { return (CorInfoCallConv)((callConv & CorInfoCallConv.CORINFO_CALLCONV_MASK)); }
private bool hasThis() { return ((callConv & CorInfoCallConv.CORINFO_CALLCONV_HASTHIS) != 0); }
private bool hasExplicitThis() { return ((callConv & CorInfoCallConv.CORINFO_CALLCONV_EXPLICITTHIS) != 0); }
private uint totalILArgs() { return (uint)(numArgs + (hasThis() ? 1 : 0)); }
private bool isVarArg() { return ((getCallConv() == CorInfoCallConv.CORINFO_CALLCONV_VARARG) || (getCallConv() == CorInfoCallConv.CORINFO_CALLCONV_NATIVEVARARG)); }
internal bool hasTypeArg() { return ((callConv & CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE) != 0); }
};
//----------------------------------------------------------------------------
// Looking up handles and addresses.
//
// When the JIT requests a handle, the EE may direct the JIT that it must
// access the handle in a variety of ways. These are packed as
// CORINFO_CONST_LOOKUP
// or CORINFO_LOOKUP (contains either a CORINFO_CONST_LOOKUP or a CORINFO_RUNTIME_LOOKUP)
//
// Constant Lookups v. Runtime Lookups (i.e. when will Runtime Lookups be generated?)
// -----------------------------------------------------------------------------------
//
// CORINFO_LOOKUP_KIND is part of the result type of embedGenericHandle,
// getVirtualCallInfo and any other functions that may require a
// runtime lookup when compiling shared generic code.
//
// CORINFO_LOOKUP_KIND indicates whether a particular token in the instruction stream can be:
// (a) Mapped to a handle (type, field or method) at compile-time (!needsRuntimeLookup)
// (b) Must be looked up at run-time, and if so which runtime lookup technique should be used (see below)
//
// If the JIT or EE does not support code sharing for generic code, then
// all CORINFO_LOOKUP results will be "constant lookups", i.e.
// the needsRuntimeLookup of CORINFO_LOOKUP.lookupKind.needsRuntimeLookup
// will be false.
//
// Constant Lookups
// ----------------
//
// Constant Lookups are either:
// IAT_VALUE: immediate (relocatable) values,
// IAT_PVALUE: immediate values access via an indirection through an immediate (relocatable) address
// IAT_RELPVALUE: immediate values access via a relative indirection through an immediate offset
// IAT_PPVALUE: immediate values access via a double indirection through an immediate (relocatable) address
//
// Runtime Lookups
// ---------------
//
// CORINFO_LOOKUP_KIND is part of the result type of embedGenericHandle,
// getVirtualCallInfo and any other functions that may require a
// runtime lookup when compiling shared generic code.
//
// CORINFO_LOOKUP_KIND indicates whether a particular token in the instruction stream can be:
// (a) Mapped to a handle (type, field or method) at compile-time (!needsRuntimeLookup)
// (b) Must be looked up at run-time using the class dictionary
// stored in the vtable of the this pointer (needsRuntimeLookup && THISOBJ)
// (c) Must be looked up at run-time using the method dictionary
// stored in the method descriptor parameter passed to a generic
// method (needsRuntimeLookup && METHODPARAM)
// (d) Must be looked up at run-time using the class dictionary stored
// in the vtable parameter passed to a method in a generic
// struct (needsRuntimeLookup && CLASSPARAM)
public unsafe struct CORINFO_CONST_LOOKUP
{
// If the handle is obtained at compile-time, then this handle is the "exact" handle (class, method, or field)
// Otherwise, it's a representative...
// If accessType is
// IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address
// IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle
// IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle
// IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle
public InfoAccessType accessType;
// _value represent the union of handle and addr
private IntPtr _value;
public CORINFO_GENERIC_STRUCT_* handle { get { return (CORINFO_GENERIC_STRUCT_*)_value; } set { _value = (IntPtr)value; } }
public void* addr { get { return (void*)_value; } set { _value = (IntPtr)value; } }
};
public enum CORINFO_RUNTIME_LOOKUP_KIND
{
CORINFO_LOOKUP_THISOBJ,
CORINFO_LOOKUP_METHODPARAM,
CORINFO_LOOKUP_CLASSPARAM,
}
public unsafe struct CORINFO_LOOKUP_KIND
{
private byte _needsRuntimeLookup;
public bool needsRuntimeLookup { get { return _needsRuntimeLookup != 0; } set { _needsRuntimeLookup = value ? (byte)1 : (byte)0; } }
public CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind;
// The 'runtimeLookupFlags' and 'runtimeLookupArgs' fields
// are just for internal VM / ZAP communication, not to be used by the JIT.
public ushort runtimeLookupFlags;
public void* runtimeLookupArgs;
}
// CORINFO_RUNTIME_LOOKUP indicates the details of the runtime lookup
// operation to be performed.
//
public unsafe struct CORINFO_RUNTIME_LOOKUP
{
// This is signature you must pass back to the runtime lookup helper
public void* signature;
// Here is the helper you must call. It is one of CORINFO_HELP_RUNTIMEHANDLE_* helpers.
public CorInfoHelpFunc helper;
// Number of indirections to get there
// CORINFO_USEHELPER = don't know how to get it, so use helper function at run-time instead
// 0 = use the this pointer itself (e.g. token is C<!0> inside code in sealed class C)
// or method desc itself (e.g. token is method void M::mymeth<!!0>() inside code in M::mymeth)
// Otherwise, follow each byte-offset stored in the "offsets[]" array (may be negative)
public ushort indirections;
// If set, test for null and branch to helper if null
public byte _testForNull;
public bool testForNull { get { return _testForNull != 0; } set { _testForNull = value ? (byte)1 : (byte)0; } }
// If set, test the lowest bit and dereference if set (see code:FixupPointer)
public byte _testForFixup;
public bool testForFixup { get { return _testForFixup != 0; } set { _testForFixup = value ? (byte)1 : (byte)0; } }
public IntPtr offset0;
public IntPtr offset1;
public IntPtr offset2;
public IntPtr offset3;
public byte _indirectFirstOffset;
public bool indirectFirstOffset { get { return _indirectFirstOffset != 0; } set { _indirectFirstOffset = value ? (byte)1 : (byte)0; } }
public byte _indirectSecondOffset;
public bool indirectSecondOffset { get { return _indirectSecondOffset != 0; } set { _indirectSecondOffset = value ? (byte)1 : (byte)0; } }
}
// Result of calling embedGenericHandle
public unsafe struct CORINFO_LOOKUP
{
public CORINFO_LOOKUP_KIND lookupKind;
// If kind.needsRuntimeLookup then this indicates how to do the lookup
public CORINFO_RUNTIME_LOOKUP runtimeLookup;
// If the handle is obtained at compile-time, then this handle is the "exact" handle (class, method, or field)
// Otherwise, it's a representative... If accessType is
// IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address
// IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle
// IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle
// IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle
public ref CORINFO_CONST_LOOKUP constLookup
{
get
{
// constLookup is union with runtimeLookup
Debug.Assert(sizeof(CORINFO_RUNTIME_LOOKUP) >= sizeof(CORINFO_CONST_LOOKUP));
fixed (CORINFO_RUNTIME_LOOKUP * p = &runtimeLookup)
return ref *(CORINFO_CONST_LOOKUP *)p;
}
}
}
public unsafe struct CORINFO_RESOLVED_TOKEN
{
//
// [In] arguments of resolveToken
//
public CORINFO_CONTEXT_STRUCT* tokenContext; //Context for resolution of generic arguments
public CORINFO_MODULE_STRUCT_* tokenScope;
public mdToken token; //The source token
public CorInfoTokenKind tokenType;
//
// [Out] arguments of resolveToken.
// - Type handle is always non-NULL.
// - At most one of method and field handles is non-NULL (according to the token type).
// - Method handle is an instantiating stub only for generic methods. Type handle
// is required to provide the full context for methods in generic types.
//
public CORINFO_CLASS_STRUCT_* hClass;
public CORINFO_METHOD_STRUCT_* hMethod;
public CORINFO_FIELD_STRUCT_* hField;
//
// [Out] TypeSpec and MethodSpec signatures for generics. NULL otherwise.
//
public byte* pTypeSpec;
public uint cbTypeSpec;
public byte* pMethodSpec;
public uint cbMethodSpec;
}
// Flags computed by a runtime compiler
public enum CorInfoMethodRuntimeFlags
{
CORINFO_FLG_BAD_INLINEE = 0x00000001, // The method is not suitable for inlining
CORINFO_FLG_VERIFIABLE = 0x00000002, // The method has verifiable code
CORINFO_FLG_UNVERIFIABLE = 0x00000004, // The method has unverifiable code
CORINFO_FLG_SWITCHED_TO_MIN_OPT = 0x00000008, // The JIT decided to switch to MinOpt for this method, when it was not requested
CORINFO_FLG_SWITCHED_TO_OPTIMIZED = 0x00000010, // The JIT decided to switch to tier 1 for this method, when a different tier was requested
};
// The enumeration is returned in 'getSig'
public enum CorInfoCallConv
{
// These correspond to CorCallingConvention
CORINFO_CALLCONV_DEFAULT = 0x0,
CORINFO_CALLCONV_C = 0x1,
CORINFO_CALLCONV_STDCALL = 0x2,
CORINFO_CALLCONV_THISCALL = 0x3,
CORINFO_CALLCONV_FASTCALL = 0x4,
CORINFO_CALLCONV_VARARG = 0x5,
CORINFO_CALLCONV_FIELD = 0x6,
CORINFO_CALLCONV_LOCAL_SIG = 0x7,
CORINFO_CALLCONV_PROPERTY = 0x8,
CORINFO_CALLCONV_NATIVEVARARG = 0xb, // used ONLY for IL stub PInvoke vararg calls
CORINFO_CALLCONV_MASK = 0x0f, // Calling convention is bottom 4 bits
CORINFO_CALLCONV_GENERIC = 0x10,
CORINFO_CALLCONV_HASTHIS = 0x20,
CORINFO_CALLCONV_EXPLICITTHIS = 0x40,
CORINFO_CALLCONV_PARAMTYPE = 0x80, // Passed last. Same as CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG
}
public enum CorInfoUnmanagedCallConv
{
// These correspond to CorUnmanagedCallingConvention
CORINFO_UNMANAGED_CALLCONV_UNKNOWN,
CORINFO_UNMANAGED_CALLCONV_C,
CORINFO_UNMANAGED_CALLCONV_STDCALL,
CORINFO_UNMANAGED_CALLCONV_THISCALL,
CORINFO_UNMANAGED_CALLCONV_FASTCALL
}
public enum CORINFO_CALLINFO_FLAGS
{
CORINFO_CALLINFO_NONE = 0x0000,
CORINFO_CALLINFO_ALLOWINSTPARAM = 0x0001, // Can the compiler generate code to pass an instantiation parameters? Simple compilers should not use this flag
CORINFO_CALLINFO_CALLVIRT = 0x0002, // Is it a virtual call?
CORINFO_CALLINFO_KINDONLY = 0x0004, // This is set to only query the kind of call to perform, without getting any other information
CORINFO_CALLINFO_VERIFICATION = 0x0008, // Gets extra verification information.
CORINFO_CALLINFO_SECURITYCHECKS = 0x0010, // Perform security checks.
CORINFO_CALLINFO_LDFTN = 0x0020, // Resolving target of LDFTN
CORINFO_CALLINFO_ATYPICAL_CALLSITE = 0x0040, // Atypical callsite that cannot be disassembled by delay loading helper
}
// Bit-twiddling of contexts assumes word-alignment of method handles and type handles
// If this ever changes, some other encoding will be needed
public enum CorInfoContextFlags
{
CORINFO_CONTEXTFLAGS_METHOD = 0x00, // CORINFO_CONTEXT_HANDLE is really a CORINFO_METHOD_HANDLE
CORINFO_CONTEXTFLAGS_CLASS = 0x01, // CORINFO_CONTEXT_HANDLE is really a CORINFO_CLASS_HANDLE
CORINFO_CONTEXTFLAGS_MASK = 0x01
};
public enum CorInfoSigInfoFlags : byte
{
CORINFO_SIGFLAG_IS_LOCAL_SIG = 0x01,
CORINFO_SIGFLAG_IL_STUB = 0x02,
CORINFO_SIGFLAG_SUPPRESS_GC_TRANSITION = 0x04,
};
// These are returned from getMethodOptions
public enum CorInfoOptions
{
CORINFO_OPT_INIT_LOCALS = 0x00000010, // zero initialize all variables
CORINFO_GENERICS_CTXT_FROM_THIS = 0x00000020, // is this shared generic code that access the generic context from the this pointer? If so, then if the method has SEH then the 'this' pointer must always be reported and kept alive.
CORINFO_GENERICS_CTXT_FROM_METHODDESC = 0x00000040, // is this shared generic code that access the generic context from the ParamTypeArg(that is a MethodDesc)? If so, then if the method has SEH then the 'ParamTypeArg' must always be reported and kept alive. Same as CORINFO_CALLCONV_PARAMTYPE
CORINFO_GENERICS_CTXT_FROM_METHODTABLE = 0x00000080, // is this shared generic code that access the generic context from the ParamTypeArg(that is a MethodTable)? If so, then if the method has SEH then the 'ParamTypeArg' must always be reported and kept alive. Same as CORINFO_CALLCONV_PARAMTYPE
CORINFO_GENERICS_CTXT_MASK = (CORINFO_GENERICS_CTXT_FROM_THIS |
CORINFO_GENERICS_CTXT_FROM_METHODDESC |
CORINFO_GENERICS_CTXT_FROM_METHODTABLE),
CORINFO_GENERICS_CTXT_KEEP_ALIVE = 0x00000100, // Keep the generics context alive throughout the method even if there is no explicit use, and report its location to the CLR
}
public enum CorInfoIntrinsics
{
CORINFO_INTRINSIC_Sin,
CORINFO_INTRINSIC_Cos,
CORINFO_INTRINSIC_Cbrt,
CORINFO_INTRINSIC_Sqrt,
CORINFO_INTRINSIC_Abs,
CORINFO_INTRINSIC_Round,
CORINFO_INTRINSIC_Cosh,
CORINFO_INTRINSIC_Sinh,
CORINFO_INTRINSIC_Tan,
CORINFO_INTRINSIC_Tanh,
CORINFO_INTRINSIC_Asin,
CORINFO_INTRINSIC_Asinh,
CORINFO_INTRINSIC_Acos,
CORINFO_INTRINSIC_Acosh,
CORINFO_INTRINSIC_Atan,
CORINFO_INTRINSIC_Atan2,
CORINFO_INTRINSIC_Atanh,
CORINFO_INTRINSIC_Log10,
CORINFO_INTRINSIC_Pow,
CORINFO_INTRINSIC_Exp,
CORINFO_INTRINSIC_Ceiling,
CORINFO_INTRINSIC_Floor,
CORINFO_INTRINSIC_GetChar, // fetch character out of string
CORINFO_INTRINSIC_Array_GetDimLength, // Get number of elements in a given dimension of an array
CORINFO_INTRINSIC_Array_Get, // Get the value of an element in an array
CORINFO_INTRINSIC_Array_Address, // Get the address of an element in an array
CORINFO_INTRINSIC_Array_Set, // Set the value of an element in an array
CORINFO_INTRINSIC_StringGetChar, // fetch character out of string
CORINFO_INTRINSIC_StringLength, // get the length
CORINFO_INTRINSIC_InitializeArray, // initialize an array from static data
CORINFO_INTRINSIC_GetTypeFromHandle,
CORINFO_INTRINSIC_RTH_GetValueInternal,
CORINFO_INTRINSIC_TypeEQ,
CORINFO_INTRINSIC_TypeNEQ,
CORINFO_INTRINSIC_Object_GetType,
CORINFO_INTRINSIC_StubHelpers_GetStubContext,
CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr,
CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget,
CORINFO_INTRINSIC_InterlockedAdd32,
CORINFO_INTRINSIC_InterlockedAdd64,
CORINFO_INTRINSIC_InterlockedXAdd32,
CORINFO_INTRINSIC_InterlockedXAdd64,
CORINFO_INTRINSIC_InterlockedXchg32,
CORINFO_INTRINSIC_InterlockedXchg64,
CORINFO_INTRINSIC_InterlockedCmpXchg32,
CORINFO_INTRINSIC_InterlockedCmpXchg64,
CORINFO_INTRINSIC_MemoryBarrier,
CORINFO_INTRINSIC_GetCurrentManagedThread,
CORINFO_INTRINSIC_GetManagedThreadId,
CORINFO_INTRINSIC_ByReference_Ctor,
CORINFO_INTRINSIC_ByReference_Value,
CORINFO_INTRINSIC_Span_GetItem,
CORINFO_INTRINSIC_ReadOnlySpan_GetItem,
CORINFO_INTRINSIC_GetRawHandle,
CORINFO_INTRINSIC_Count,
CORINFO_INTRINSIC_Illegal = -1, // Not a true intrinsic,
}
// Can a value be accessed directly from JITed code.
public enum InfoAccessType
{
IAT_VALUE, // The info value is directly available
IAT_PVALUE, // The value needs to be accessed via an indirection
IAT_PPVALUE, // The value needs to be accessed via a double indirection
IAT_RELPVALUE // The value needs to be accessed via a relative indirection
}
public enum CorInfoGCType
{
TYPE_GC_NONE, // no embedded objectrefs
TYPE_GC_REF, // Is an object ref
TYPE_GC_BYREF, // Is an interior pointer - promote it but don't scan it
TYPE_GC_OTHER // requires type-specific treatment
}
public enum CorInfoClassId
{
CLASSID_SYSTEM_OBJECT,
CLASSID_TYPED_BYREF,
CLASSID_TYPE_HANDLE,
CLASSID_FIELD_HANDLE,
CLASSID_METHOD_HANDLE,
CLASSID_STRING,
CLASSID_ARGUMENT_HANDLE,
CLASSID_RUNTIME_TYPE,
}
public enum CorInfoInline
{
INLINE_PASS = 0, // Inlining OK
// failures are negative
INLINE_FAIL = -1, // Inlining not OK for this case only
INLINE_NEVER = -2, // This method should never be inlined, regardless of context
}
public enum CorInfoInlineTypeCheck
{
CORINFO_INLINE_TYPECHECK_NONE = 0x00000000, // It's not okay to compare type's vtable with a native type handle
CORINFO_INLINE_TYPECHECK_PASS = 0x00000001, // It's okay to compare type's vtable with a native type handle
CORINFO_INLINE_TYPECHECK_USE_HELPER = 0x00000002, // Use a specialized helper to compare type's vtable with native type handle
}
public enum CorInfoInlineTypeCheckSource
{
CORINFO_INLINE_TYPECHECK_SOURCE_VTABLE = 0x00000000, // Type handle comes from the vtable
CORINFO_INLINE_TYPECHECK_SOURCE_TOKEN = 0x00000001, // Type handle comes from an ldtoken
}
public enum CorInfoInlineRestrictions
{
INLINE_RESPECT_BOUNDARY = 0x00000001, // You can inline if there are no calls from the method being inlined
INLINE_NO_CALLEE_LDSTR = 0x00000002, // You can inline only if you guarantee that if inlinee does an ldstr
// inlinee's module will never see that string (by any means).
// This is due to how we implement the NoStringInterningAttribute
// (by reusing the fixup table).
INLINE_SAME_THIS = 0x00000004, // You can inline only if the callee is on the same this reference as caller
}
// If you add more values here, keep it in sync with TailCallTypeMap in ..\vm\ClrEtwAll.man
// and the string enum in CEEInfo::reportTailCallDecision in ..\vm\JITInterface.cpp
public enum CorInfoTailCall
{
TAILCALL_OPTIMIZED = 0, // Optimized tail call (epilog + jmp)
TAILCALL_RECURSIVE = 1, // Optimized into a loop (only when a method tail calls itself)
TAILCALL_HELPER = 2, // Helper assisted tail call (call to JIT_TailCall)
// failures are negative
TAILCALL_FAIL = -1, // Couldn't do a tail call
}
public enum CorInfoCanSkipVerificationResult
{
CORINFO_VERIFICATION_CANNOT_SKIP = 0, // Cannot skip verification during jit time.
CORINFO_VERIFICATION_CAN_SKIP = 1, // Can skip verification during jit time.
CORINFO_VERIFICATION_RUNTIME_CHECK = 2, // Cannot skip verification during jit time,
// but need to insert a callout to the VM to ask during runtime
// whether to raise a verification or not (if the method is unverifiable).
CORINFO_VERIFICATION_DONT_JIT = 3, // Cannot skip verification during jit time,
// but do not jit the method if is is unverifiable.
}
public enum CorInfoInitClassResult
{
CORINFO_INITCLASS_NOT_REQUIRED = 0x00, // No class initialization required, but the class is not actually initialized yet
// (e.g. we are guaranteed to run the static constructor in method prolog)
CORINFO_INITCLASS_INITIALIZED = 0x01, // Class initialized
CORINFO_INITCLASS_SPECULATIVE = 0x02, // Class may be initialized speculatively
CORINFO_INITCLASS_USE_HELPER = 0x04, // The JIT must insert class initialization helper call.
CORINFO_INITCLASS_DONT_INLINE = 0x08, // The JIT should not inline the method requesting the class initialization. The class
// initialization requires helper class now, but will not require initialization
// if the method is compiled standalone. Or the method cannot be inlined due to some
// requirement around class initialization such as shared generics.
}
public enum CORINFO_ACCESS_FLAGS
{
CORINFO_ACCESS_ANY = 0x0000, // Normal access
CORINFO_ACCESS_THIS = 0x0001, // Accessed via the this reference
CORINFO_ACCESS_UNWRAP = 0x0002, // Accessed via an unwrap reference
CORINFO_ACCESS_NONNULL = 0x0004, // Instance is guaranteed non-null
CORINFO_ACCESS_LDFTN = 0x0010, // Accessed via ldftn
// Field access flags
CORINFO_ACCESS_GET = 0x0100, // Field get (ldfld)
CORINFO_ACCESS_SET = 0x0200, // Field set (stfld)
CORINFO_ACCESS_ADDRESS = 0x0400, // Field address (ldflda)
CORINFO_ACCESS_INIT_ARRAY = 0x0800, // Field use for InitializeArray
CORINFO_ACCESS_ATYPICAL_CALLSITE = 0x4000, // Atypical callsite that cannot be disassembled by delay loading helper
CORINFO_ACCESS_INLINECHECK = 0x8000, // Return fieldFlags and fieldAccessor only. Used by JIT64 during inlining.
}
// these are the attribute flags for fields and methods (getMethodAttribs)
[Flags]
public enum CorInfoFlag : uint
{
// CORINFO_FLG_UNUSED = 0x00000001,
// CORINFO_FLG_UNUSED = 0x00000002,
CORINFO_FLG_PROTECTED = 0x00000004,
CORINFO_FLG_STATIC = 0x00000008,
CORINFO_FLG_FINAL = 0x00000010,
CORINFO_FLG_SYNCH = 0x00000020,
CORINFO_FLG_VIRTUAL = 0x00000040,
// CORINFO_FLG_UNUSED = 0x00000080,
CORINFO_FLG_NATIVE = 0x00000100,
CORINFO_FLG_INTRINSIC_TYPE = 0x00000200, // This type is marked by [Intrinsic]
CORINFO_FLG_ABSTRACT = 0x00000400,
CORINFO_FLG_EnC = 0x00000800, // member was added by Edit'n'Continue
// These are internal flags that can only be on methods
CORINFO_FLG_FORCEINLINE = 0x00010000, // The method should be inlined if possible.
CORINFO_FLG_SHAREDINST = 0x00020000, // the code for this method is shared between different generic instantiations (also set on classes/types)
CORINFO_FLG_DELEGATE_INVOKE = 0x00040000, // "Delegate
CORINFO_FLG_PINVOKE = 0x00080000, // Is a P/Invoke call
CORINFO_FLG_SECURITYCHECK = 0x00100000, // Is one of the security routines that does a stackwalk (e.g. Assert, Demand)
CORINFO_FLG_NOGCCHECK = 0x00200000, // This method is FCALL that has no GC check. Don't put alone in loops
CORINFO_FLG_INTRINSIC = 0x00400000, // This method MAY have an intrinsic ID
CORINFO_FLG_CONSTRUCTOR = 0x00800000, // This method is an instance or type initializer
CORINFO_FLG_AGGRESSIVE_OPT = 0x01000000, // The method may contain hot code and should be aggressively optimized if possible
CORINFO_FLG_DISABLE_TIER0_FOR_LOOPS = 0x02000000, // Indicates that tier 0 JIT should not be used for a method that contains a loop
CORINFO_FLG_NOSECURITYWRAP = 0x04000000, // The method requires no security checks
CORINFO_FLG_DONT_INLINE = 0x10000000, // The method should not be inlined
CORINFO_FLG_DONT_INLINE_CALLER = 0x20000000, // The method should not be inlined, nor should its callers. It cannot be tail called.
CORINFO_FLG_JIT_INTRINSIC = 0x40000000, // Method is a potential jit intrinsic; verify identity by name check
// These are internal flags that can only be on Classes
CORINFO_FLG_VALUECLASS = 0x00010000, // is the class a value class
// This flag is define din the Methods section, but is also valid on classes.
// CORINFO_FLG_SHAREDINST = 0x00020000, // This class is satisfies TypeHandle::IsCanonicalSubtype
CORINFO_FLG_VAROBJSIZE = 0x00040000, // the object size varies depending of constructor args
CORINFO_FLG_ARRAY = 0x00080000, // class is an array class (initialized differently)
CORINFO_FLG_OVERLAPPING_FIELDS = 0x00100000, // struct or class has fields that overlap (aka union)
CORINFO_FLG_INTERFACE = 0x00200000, // it is an interface
CORINFO_FLG_CONTEXTFUL = 0x00400000, // is this a contextful class?
CORINFO_FLG_CUSTOMLAYOUT = 0x00800000, // does this struct have custom layout?
CORINFO_FLG_CONTAINS_GC_PTR = 0x01000000, // does the class contain a gc ptr ?
CORINFO_FLG_DELEGATE = 0x02000000, // is this a subclass of delegate or multicast delegate ?
CORINFO_FLG_MARSHAL_BYREF = 0x04000000, // is this a subclass of MarshalByRef ?
CORINFO_FLG_CONTAINS_STACK_PTR = 0x08000000, // This class has a stack pointer inside it
CORINFO_FLG_VARIANCE = 0x10000000, // MethodTable::HasVariance (sealed does *not* mean uncast-able)
CORINFO_FLG_BEFOREFIELDINIT = 0x20000000, // Additional flexibility for when to run .cctor (see code:#ClassConstructionFlags)
CORINFO_FLG_GENERIC_TYPE_VARIABLE = 0x40000000, // This is really a handle for a variable type
CORINFO_FLG_UNSAFE_VALUECLASS = 0x80000000, // Unsafe (C++'s /GS) value type
}
//----------------------------------------------------------------------------
// Exception handling
// These are the flags set on an CORINFO_EH_CLAUSE
public enum CORINFO_EH_CLAUSE_FLAGS
{
CORINFO_EH_CLAUSE_NONE = 0,
CORINFO_EH_CLAUSE_FILTER = 0x0001, // If this bit is on, then this EH entry is for a filter
CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
CORINFO_EH_CLAUSE_DUPLICATED = 0x0008, // Duplicated clause. This clause was duplicated to a funclet which was pulled out of line
CORINFO_EH_CLAUSE_SAMETRY = 0x0010, // This clause covers same try block as the previous one. (Used by CoreRT ABI.)
};
public struct CORINFO_EH_CLAUSE
{
public CORINFO_EH_CLAUSE_FLAGS Flags;
public uint TryOffset;
public uint TryLength;
public uint HandlerOffset;
public uint HandlerLength;
public uint ClassTokenOrOffset;
/* union
{
DWORD ClassToken; // use for type-based exception handlers
DWORD FilterOffset; // use for filter-based exception handlers (COR_ILEXCEPTION_FILTER is set)
};*/
}
public struct BlockCounts // Also defined here: code:CORBBTPROF_BLOCK_DATA
{
public uint ILOffset;
public uint ExecutionCount;
}
// The enumeration is returned in 'getSig','getType', getArgType methods
public enum CorInfoType
{
CORINFO_TYPE_UNDEF = 0x0,
CORINFO_TYPE_VOID = 0x1,
CORINFO_TYPE_BOOL = 0x2,
CORINFO_TYPE_CHAR = 0x3,
CORINFO_TYPE_BYTE = 0x4,
CORINFO_TYPE_UBYTE = 0x5,
CORINFO_TYPE_SHORT = 0x6,
CORINFO_TYPE_USHORT = 0x7,
CORINFO_TYPE_INT = 0x8,
CORINFO_TYPE_UINT = 0x9,
CORINFO_TYPE_LONG = 0xa,
CORINFO_TYPE_ULONG = 0xb,
CORINFO_TYPE_NATIVEINT = 0xc,
CORINFO_TYPE_NATIVEUINT = 0xd,
CORINFO_TYPE_FLOAT = 0xe,
CORINFO_TYPE_DOUBLE = 0xf,
CORINFO_TYPE_STRING = 0x10, // Not used, should remove
CORINFO_TYPE_PTR = 0x11,
CORINFO_TYPE_BYREF = 0x12,
CORINFO_TYPE_VALUECLASS = 0x13,
CORINFO_TYPE_CLASS = 0x14,
CORINFO_TYPE_REFANY = 0x15,
// CORINFO_TYPE_VAR is for a generic type variable.
// Generic type variables only appear when the JIT is doing
// verification (not NOT compilation) of generic code
// for the EE, in which case we're running
// the JIT in "import only" mode.
CORINFO_TYPE_VAR = 0x16,
CORINFO_TYPE_COUNT, // number of jit types
}
public enum CorInfoIsAccessAllowedResult
{
CORINFO_ACCESS_ALLOWED = 0, // Call allowed
CORINFO_ACCESS_ILLEGAL = 1, // Call not allowed
CORINFO_ACCESS_RUNTIME_CHECK = 2, // Ask at runtime whether to allow the call or not
}
//----------------------------------------------------------------------------
// Embedding type, method and field handles (for "ldtoken" or to pass back to helpers)
// Result of calling embedGenericHandle
public unsafe struct CORINFO_GENERICHANDLE_RESULT
{
public CORINFO_LOOKUP lookup;
// compileTimeHandle is guaranteed to be either NULL or a handle that is usable during compile time.
// It must not be embedded in the code because it might not be valid at run-time.
public CORINFO_GENERIC_STRUCT_* compileTimeHandle;
// Type of the result
public CorInfoGenericHandleType handleType;
}
public enum CorInfoGenericHandleType
{
CORINFO_HANDLETYPE_UNKNOWN,
CORINFO_HANDLETYPE_CLASS,
CORINFO_HANDLETYPE_METHOD,
CORINFO_HANDLETYPE_FIELD
}
/* data to optimize delegate construction */
public unsafe struct DelegateCtorArgs
{
public void* pMethod;
public void* pArg3;
public void* pArg4;
public void* pArg5;
}
// When using CORINFO_HELPER_TAILCALL, the JIT needs to pass certain special
// calling convention/argument passing/handling details to the helper
public enum CorInfoHelperTailCallSpecialHandling
{
CORINFO_TAILCALL_NORMAL = 0x00000000,
CORINFO_TAILCALL_STUB_DISPATCH_ARG = 0x00000001,
}
/*****************************************************************************/
// These are flags passed to ICorJitInfo::allocMem
// to guide the memory allocation for the code, readonly data, and read-write data
public enum CorJitAllocMemFlag
{
CORJIT_ALLOCMEM_DEFAULT_CODE_ALIGN = 0x00000000, // The code will be use the normal alignment
CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN = 0x00000001, // The code will be 16-byte aligned
CORJIT_ALLOCMEM_FLG_RODATA_16BYTE_ALIGN = 0x00000002, // The read-only data will be 16-byte aligned
}
public enum CorJitFuncKind
{
CORJIT_FUNC_ROOT, // The main/root function (always id==0)
CORJIT_FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
CORJIT_FUNC_FILTER // a funclet associated with an EH filter
}
public unsafe struct CORINFO_METHOD_INFO
{
public CORINFO_METHOD_STRUCT_* ftn;
public CORINFO_MODULE_STRUCT_* scope;
public byte* ILCode;
public uint ILCodeSize;
public uint maxStack;
public uint EHcount;
public CorInfoOptions options;
public CorInfoRegionKind regionKind;
public CORINFO_SIG_INFO args;
public CORINFO_SIG_INFO locals;
}
//
// what type of code region we are in
//
public enum CorInfoRegionKind
{
CORINFO_REGION_NONE,
CORINFO_REGION_HOT,
CORINFO_REGION_COLD,
CORINFO_REGION_JIT,
}
// This is for use when the JIT is compiling an instantiation
// of generic code. The JIT needs to know if the generic code itself
// (which can be verified once and for all independently of the
// instantiations) passed verification.
public enum CorInfoInstantiationVerification
{
// The method is NOT a concrete instantiation (eg. List<int>.Add()) of a method
// in a generic class or a generic method. It is either the typical instantiation
// (eg. List<T>.Add()) or entirely non-generic.
INSTVER_NOT_INSTANTIATION = 0,
// The method is an instantiation of a method in a generic class or a generic method,
// and the generic class was successfully verified
INSTVER_GENERIC_PASSED_VERIFICATION = 1,
// The method is an instantiation of a method in a generic class or a generic method,
// and the generic class failed verification
INSTVER_GENERIC_FAILED_VERIFICATION = 2,
};
public enum CorInfoTypeWithMod
{
CORINFO_TYPE_MASK = 0x3F, // lower 6 bits are type mask
CORINFO_TYPE_MOD_PINNED = 0x40, // can be applied to CLASS, or BYREF to indiate pinned
};
public struct CORINFO_HELPER_ARG
{
public IntPtr argHandle;
public CorInfoAccessAllowedHelperArgType argType;
}
public enum CorInfoAccessAllowedHelperArgType
{
CORINFO_HELPER_ARG_TYPE_Invalid = 0,
CORINFO_HELPER_ARG_TYPE_Field = 1,
CORINFO_HELPER_ARG_TYPE_Method = 2,
CORINFO_HELPER_ARG_TYPE_Class = 3,
CORINFO_HELPER_ARG_TYPE_Module = 4,
CORINFO_HELPER_ARG_TYPE_Const = 5,
}
public struct CORINFO_HELPER_DESC
{
public CorInfoHelpFunc helperNum;
public uint numArgs;
public CORINFO_HELPER_ARG args0;
public CORINFO_HELPER_ARG args1;
public CORINFO_HELPER_ARG args2;
public CORINFO_HELPER_ARG args3;
}
public enum CORINFO_OS
{
CORINFO_WINNT,
CORINFO_UNIX,
}
public enum CORINFO_RUNTIME_ABI
{
CORINFO_DESKTOP_ABI = 0x100,
CORINFO_CORECLR_ABI = 0x200,
CORINFO_CORERT_ABI = 0x300,
}
// For some highly optimized paths, the JIT must generate code that directly
// manipulates internal EE data structures. The getEEInfo() helper returns
// this structure containing the needed offsets and values.
public struct CORINFO_EE_INFO
{
// Information about the InlinedCallFrame structure layout
public struct InlinedCallFrameInfo
{
// Size of the Frame structure
public uint size;
public uint offsetOfGSCookie;
public uint offsetOfFrameVptr;
public uint offsetOfFrameLink;
public uint offsetOfCallSiteSP;
public uint offsetOfCalleeSavedFP;
public uint offsetOfCallTarget;
public uint offsetOfReturnAddress;
public uint offsetOfSPAfterProlog;
}
public InlinedCallFrameInfo inlinedCallFrameInfo;
// Offsets into the Thread structure
public uint offsetOfThreadFrame; // offset of the current Frame
public uint offsetOfGCState; // offset of the preemptive/cooperative state of the Thread
// Delegate offsets
public uint offsetOfDelegateInstance;
public uint offsetOfDelegateFirstTarget;
// Wrapper delegate offsets
public uint offsetOfWrapperDelegateIndirectCell;
// Remoting offsets
public uint offsetOfTransparentProxyRP;
public uint offsetOfRealProxyServer;
// Array offsets
public uint offsetOfObjArrayData;
// Reverse PInvoke offsets
public uint sizeOfReversePInvokeFrame;
// OS Page size
public UIntPtr osPageSize;
// Null object offset
public UIntPtr maxUncheckedOffsetForNullObject;
// Target ABI. Combined with target architecture and OS to determine
// GC, EH, and unwind styles.
public CORINFO_RUNTIME_ABI targetAbi;
public CORINFO_OS osType;
public uint osMajor;
public uint osMinor;
public uint osBuild;
}
public enum CORINFO_THIS_TRANSFORM
{
CORINFO_NO_THIS_TRANSFORM,
CORINFO_BOX_THIS,
CORINFO_DEREF_THIS
};
//----------------------------------------------------------------------------
// getCallInfo and CORINFO_CALL_INFO: The EE instructs the JIT about how to make a call
//
// callKind
// --------
//
// CORINFO_CALL :
// Indicates that the JIT can use getFunctionEntryPoint to make a call,
// i.e. there is nothing abnormal about the call. The JITs know what to do if they get this.
// Except in the case of constraint calls (see below), [targetMethodHandle] will hold
// the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag may be combined with nullInstanceCheck=TRUE for uses of callvirt on methods that can
// be resolved at compile-time (non-virtual, final or sealed).
//
// CORINFO_CALL_CODE_POINTER (shared generic code only) :
// Indicates that the JIT should do an indirect call to the entrypoint given by address, which may be specified
// as a runtime lookup by CORINFO_CALL_INFO::codePointerLookup.
// [targetMethodHandle] will not hold a valid value.
// This flag may be combined with nullInstanceCheck=TRUE for uses of callvirt on methods whose target method can
// be resolved at compile-time but whose instantiation can be resolved only through runtime lookup.
//
// CORINFO_VIRTUALCALL_STUB (interface calls) :
// Indicates that the EE supports "stub dispatch" and request the JIT to make a
// "stub dispatch" call (an indirect call through CORINFO_CALL_INFO::stubLookup,
// similar to CORINFO_CALL_CODE_POINTER).
// "Stub dispatch" is a specialized calling sequence (that may require use of NOPs)
// which allow the runtime to determine the call-site after the call has been dispatched.
// If the call is too complex for the JIT (e.g. because
// fetching the dispatch stub requires a runtime lookup, i.e. lookupKind.needsRuntimeLookup
// is set) then the JIT is allowed to implement the call as if it were CORINFO_VIRTUALCALL_LDVIRTFTN
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE.
//
// CORINFO_VIRTUALCALL_LDVIRTFTN (virtual generic methods) :
// Indicates that the EE provides no way to implement the call directly and
// that the JIT should use a LDVIRTFTN sequence (as implemented by CORINFO_HELP_VIRTUAL_FUNC_PTR)
// followed by an indirect call.
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE though typically the null check will
// be implicit in the access through the instance pointer.
//
// CORINFO_VIRTUALCALL_VTABLE (regular virtual methods) :
// Indicates that the EE supports vtable dispatch and that the JIT should use getVTableOffset etc.
// to implement the call.
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE though typically the null check will
// be implicit in the access through the instance pointer.
//
// thisTransform and constraint calls
// ----------------------------------
//
// For everything besides "constrained." calls "thisTransform" is set to
// CORINFO_NO_THIS_TRANSFORM.
//
// For "constrained." calls the EE attempts to resolve the call at compile
// time to a more specific method, or (shared generic code only) to a runtime lookup
// for a code pointer for the more specific method.
//
// In order to permit this, the "this" pointer supplied for a "constrained." call
// is a byref to an arbitrary type (see the IL spec). The "thisTransform" field
// will indicate how the JIT must transform the "this" pointer in order
// to be able to call the resolved method:
//
// CORINFO_NO_THIS_TRANSFORM --> Leave it as a byref to an unboxed value type
// CORINFO_BOX_THIS --> Box it to produce an object
// CORINFO_DEREF_THIS --> Deref the byref to get an object reference
//
// In addition, the "kind" field will be set as follows for constraint calls:
// CORINFO_CALL --> the call was resolved at compile time, and
// can be compiled like a normal call.
// CORINFO_CALL_CODE_POINTER --> the call was resolved, but the target address will be
// computed at runtime. Only returned for shared generic code.
// CORINFO_VIRTUALCALL_STUB,
// CORINFO_VIRTUALCALL_LDVIRTFTN,
// CORINFO_VIRTUALCALL_VTABLE --> usual values indicating that a virtual call must be made
public enum CORINFO_CALL_KIND
{
CORINFO_CALL,
CORINFO_CALL_CODE_POINTER,
CORINFO_VIRTUALCALL_STUB,
CORINFO_VIRTUALCALL_LDVIRTFTN,
CORINFO_VIRTUALCALL_VTABLE
};
public enum CORINFO_VIRTUALCALL_NO_CHUNK : uint
{
Value = 0xFFFFFFFF,
}
public unsafe struct CORINFO_CALL_INFO
{
public CORINFO_METHOD_STRUCT_* hMethod; //target method handle
public uint methodFlags; //flags for the target method
public uint classFlags; //flags for CORINFO_RESOLVED_TOKEN::hClass
public CORINFO_SIG_INFO sig;
//Verification information
public uint verMethodFlags; // flags for CORINFO_RESOLVED_TOKEN::hMethod
public CORINFO_SIG_INFO verSig;
//All of the regular method data is the same... hMethod might not be the same as CORINFO_RESOLVED_TOKEN::hMethod
//If set to:
// - CORINFO_ACCESS_ALLOWED - The access is allowed.
// - CORINFO_ACCESS_ILLEGAL - This access cannot be allowed (i.e. it is public calling private). The
// JIT may either insert the callsiteCalloutHelper into the code (as per a verification error) or
// call throwExceptionFromHelper on the callsiteCalloutHelper. In this case callsiteCalloutHelper
// is guaranteed not to return.
// - CORINFO_ACCESS_RUNTIME_CHECK - The jit must insert the callsiteCalloutHelper at the call site.
// the helper may return
public CorInfoIsAccessAllowedResult accessAllowed;
public CORINFO_HELPER_DESC callsiteCalloutHelper;
// See above section on constraintCalls to understand when these are set to unusual values.
public CORINFO_THIS_TRANSFORM thisTransform;
public CORINFO_CALL_KIND kind;
public uint _nullInstanceCheck;
public bool nullInstanceCheck { get { return _nullInstanceCheck != 0; } set { _nullInstanceCheck = value ? (byte)1 : (byte)0; } }
// Context for inlining and hidden arg
public CORINFO_CONTEXT_STRUCT* contextHandle;
public uint _exactContextNeedsRuntimeLookup; // Set if contextHandle is approx handle. Runtime lookup is required to get the exact handle.
public bool exactContextNeedsRuntimeLookup { get { return _exactContextNeedsRuntimeLookup != 0; } set { _exactContextNeedsRuntimeLookup = value ? (byte)1 : (byte)0; } }
// If kind.CORINFO_VIRTUALCALL_STUB then stubLookup will be set.
// If kind.CORINFO_CALL_CODE_POINTER then entryPointLookup will be set.
public CORINFO_LOOKUP codePointerOrStubLookup;
// Used by Ready-to-Run
public CORINFO_CONST_LOOKUP instParamLookup;
public uint _wrapperDelegateInvoke;
public bool wrapperDelegateInvoke { get { return _wrapperDelegateInvoke != 0; } set { _wrapperDelegateInvoke = value ? (byte)1 : (byte)0; } }
}
//----------------------------------------------------------------------------
// getFieldInfo and CORINFO_FIELD_INFO: The EE instructs the JIT about how to access a field
public enum CORINFO_FIELD_ACCESSOR
{
CORINFO_FIELD_INSTANCE, // regular instance field at given offset from this-ptr
CORINFO_FIELD_INSTANCE_WITH_BASE, // instance field with base offset (used by Ready-to-Run)
CORINFO_FIELD_INSTANCE_HELPER, // instance field accessed using helper (arguments are this, FieldDesc * and the value)
CORINFO_FIELD_INSTANCE_ADDR_HELPER, // instance field accessed using address-of helper (arguments are this and FieldDesc *)
CORINFO_FIELD_STATIC_ADDRESS, // field at given address
CORINFO_FIELD_STATIC_RVA_ADDRESS, // RVA field at given address
CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER, // static field accessed using the "shared static" helper (arguments are ModuleID + ClassID)
CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER, // static field access using the "generic static" helper (argument is MethodTable *)
CORINFO_FIELD_STATIC_ADDR_HELPER, // static field accessed using address-of helper (argument is FieldDesc *)
CORINFO_FIELD_STATIC_TLS, // unmanaged TLS access
CORINFO_FIELD_STATIC_READYTORUN_HELPER, // static field access using a runtime lookup helper
CORINFO_FIELD_INTRINSIC_ZERO, // intrinsic zero (IntPtr.Zero, UIntPtr.Zero)
CORINFO_FIELD_INTRINSIC_EMPTY_STRING, // intrinsic emptry string (String.Empty)
CORINFO_FIELD_INTRINSIC_ISLITTLEENDIAN, // intrinsic BitConverter.IsLittleEndian
}
// Set of flags returned in CORINFO_FIELD_INFO::fieldFlags
public enum CORINFO_FIELD_FLAGS
{
CORINFO_FLG_FIELD_STATIC = 0x00000001,
CORINFO_FLG_FIELD_UNMANAGED = 0x00000002, // RVA field
CORINFO_FLG_FIELD_FINAL = 0x00000004,
CORINFO_FLG_FIELD_STATIC_IN_HEAP = 0x00000008, // See code:#StaticFields. This static field is in the GC heap as a boxed object
CORINFO_FLG_FIELD_SAFESTATIC_BYREF_RETURN = 0x00000010, // Field can be returned safely (has GC heap lifetime)
CORINFO_FLG_FIELD_INITCLASS = 0x00000020, // initClass has to be called before accessing the field
CORINFO_FLG_FIELD_PROTECTED = 0x00000040,
}
public unsafe struct CORINFO_FIELD_INFO
{
public CORINFO_FIELD_ACCESSOR fieldAccessor;
public CORINFO_FIELD_FLAGS fieldFlags;
// Helper to use if the field access requires it
public CorInfoHelpFunc helper;
// Field offset if there is one
public uint offset;
public CorInfoType fieldType;
public CORINFO_CLASS_STRUCT_* structType; //possibly null
//See CORINFO_CALL_INFO.accessAllowed
public CorInfoIsAccessAllowedResult accessAllowed;
public CORINFO_HELPER_DESC accessCalloutHelper;
// Used by Ready-to-Run
public CORINFO_CONST_LOOKUP fieldLookup;
};
// System V struct passing
// The Classification types are described in the ABI spec at https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf
public enum SystemVClassificationType : byte
{
SystemVClassificationTypeUnknown = 0,
SystemVClassificationTypeStruct = 1,
SystemVClassificationTypeNoClass = 2,
SystemVClassificationTypeMemory = 3,
SystemVClassificationTypeInteger = 4,
SystemVClassificationTypeIntegerReference = 5,
SystemVClassificationTypeIntegerByRef = 6,
SystemVClassificationTypeSSE = 7,
// SystemVClassificationTypeSSEUp = Unused, // Not supported by the CLR.
// SystemVClassificationTypeX87 = Unused, // Not supported by the CLR.
// SystemVClassificationTypeX87Up = Unused, // Not supported by the CLR.
// SystemVClassificationTypeComplexX87 = Unused, // Not supported by the CLR.
// Internal flags - never returned outside of the classification implementation.
// This value represents a very special type with two eightbytes.
// First ByRef, second Integer (platform int).
// The VM has a special Elem type for this type - ELEMENT_TYPE_TYPEDBYREF.
// This is the classification counterpart for that element type. It is used to detect
// the special TypedReference type and specialize its classification.
// This type is represented as a struct with two fields. The classification needs to do
// special handling of it since the source/methadata type of the fieds is IntPtr.
// The VM changes the first to ByRef. The second is left as IntPtr (TYP_I_IMPL really). The classification needs to match this and
// special handling is warranted (similar thing is done in the getGCLayout function for this type).
SystemVClassificationTypeTypedReference = 8,
SystemVClassificationTypeMAX = 9
};
public struct SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR
{
public const int CLR_SYSTEMV_MAX_EIGHTBYTES_COUNT_TO_PASS_IN_REGISTERS = 2;
public const int CLR_SYSTEMV_MAX_STRUCT_BYTES_TO_PASS_IN_REGISTERS = 16;
public const int SYSTEMV_EIGHT_BYTE_SIZE_IN_BYTES = 8; // Size of an eightbyte in bytes.
public const int SYSTEMV_MAX_NUM_FIELDS_IN_REGISTER_PASSED_STRUCT = 16; // Maximum number of fields in struct passed in registers
public byte _passedInRegisters;
// Whether the struct is passable/passed (this includes struct returning) in registers.
public bool passedInRegisters { get { return _passedInRegisters != 0; } set { _passedInRegisters = value ? (byte)1 : (byte)0; } }
// Number of eightbytes for this struct.
public byte eightByteCount;
// The eightbytes type classification.
public SystemVClassificationType eightByteClassifications0;
public SystemVClassificationType eightByteClassifications1;
// The size of the eightbytes (an eightbyte could include padding. This represents the no padding size of the eightbyte).
public byte eightByteSizes0;
public byte eightByteSizes1;
// The start offset of the eightbytes (in bytes).
public byte eightByteOffsets0;
public byte eightByteOffsets1;
};
// DEBUGGER DATA
public enum MappingTypes
{
NO_MAPPING = -1, // -- The IL offset corresponds to no source code (such as EH step blocks).
PROLOG = -2, // -- The IL offset indicates a prolog
EPILOG = -3 // -- The IL offset indicates an epilog
}
public enum BoundaryTypes
{
NO_BOUNDARIES = 0x00, // No implicit boundaries
STACK_EMPTY_BOUNDARIES = 0x01, // Boundary whenever the IL evaluation stack is empty
NOP_BOUNDARIES = 0x02, // Before every CEE_NOP instruction
CALL_SITE_BOUNDARIES = 0x04, // Before every CEE_CALL, CEE_CALLVIRT, etc instruction
// Set of boundaries that debugger should always reasonably ask the JIT for.
DEFAULT_BOUNDARIES = STACK_EMPTY_BOUNDARIES | NOP_BOUNDARIES | CALL_SITE_BOUNDARIES
}
// Note that SourceTypes can be OR'd together - it's possible that
// a sequence point will also be a stack_empty point, and/or a call site.
// The debugger will check to see if a boundary offset's source field &
// SEQUENCE_POINT is true to determine if the boundary is a sequence point.
[Flags]
public enum SourceTypes
{
SOURCE_TYPE_INVALID = 0x00, // To indicate that nothing else applies
SEQUENCE_POINT = 0x01, // The debugger asked for it.
STACK_EMPTY = 0x02, // The stack is empty here
CALL_SITE = 0x04, // This is a call site.
NATIVE_END_OFFSET_UNKNOWN = 0x08, // Indicates a epilog endpoint
CALL_INSTRUCTION = 0x10 // The actual instruction of a call.
};
public struct OffsetMapping
{
public uint nativeOffset;
public uint ilOffset;
public SourceTypes source; // The debugger needs this so that
// we don't put Edit and Continue breakpoints where
// the stack isn't empty. We can put regular breakpoints
// there, though, so we need a way to discriminate
// between offsets.
};
public enum ILNum
{
VARARGS_HND_ILNUM = -1, // Value for the CORINFO_VARARGS_HANDLE varNumber
RETBUF_ILNUM = -2, // Pointer to the return-buffer
TYPECTXT_ILNUM = -3, // ParamTypeArg for CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG
UNKNOWN_ILNUM = -4, // Unknown variable
MAX_ILNUM = -4 // Sentinal value. This should be set to the largest magnitude value in the enum
// so that the compression routines know the enum's range.
};
public struct ILVarInfo
{
public uint startOffset;
public uint endOffset;
public uint varNumber;
};
// This enum is used for JIT to tell EE where this token comes from.
// E.g. Depending on different opcodes, we might allow/disallow certain types of tokens or
// return different types of handles (e.g. boxed vs. regular entrypoints)
public enum CorInfoTokenKind
{
CORINFO_TOKENKIND_Class = 0x01,
CORINFO_TOKENKIND_Method = 0x02,
CORINFO_TOKENKIND_Field = 0x04,
CORINFO_TOKENKIND_Mask = 0x07,
// token comes from CEE_LDTOKEN
CORINFO_TOKENKIND_Ldtoken = 0x10 | CORINFO_TOKENKIND_Class | CORINFO_TOKENKIND_Method | CORINFO_TOKENKIND_Field,
// token comes from CEE_CASTCLASS or CEE_ISINST
CORINFO_TOKENKIND_Casting = 0x20 | CORINFO_TOKENKIND_Class,
// token comes from CEE_NEWARR
CORINFO_TOKENKIND_Newarr = 0x40 | CORINFO_TOKENKIND_Class,
// token comes from CEE_BOX
CORINFO_TOKENKIND_Box = 0x80 | CORINFO_TOKENKIND_Class,
// token comes from CEE_CONSTRAINED
CORINFO_TOKENKIND_Constrained = 0x100 | CORINFO_TOKENKIND_Class,
// token comes from CEE_NEWOBJ
CORINFO_TOKENKIND_NewObj = 0x200 | CORINFO_TOKENKIND_Method,
// token comes from CEE_LDVIRTFTN
CORINFO_TOKENKIND_Ldvirtftn = 0x400 | CORINFO_TOKENKIND_Method,
};
// These are error codes returned by CompileMethod
public enum CorJitResult
{
// Note that I dont use FACILITY_NULL for the facility number,
// we may want to get a 'real' facility number
CORJIT_OK = 0 /*NO_ERROR*/,
CORJIT_BADCODE = unchecked((int)0x80000001)/*MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 1)*/,
CORJIT_OUTOFMEM = unchecked((int)0x80000002)/*MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 2)*/,
CORJIT_INTERNALERROR = unchecked((int)0x80000003)/*MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 3)*/,
CORJIT_SKIPPED = unchecked((int)0x80000004)/*MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 4)*/,
CORJIT_RECOVERABLEERROR = unchecked((int)0x80000005)/*MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 5)*/
};
public enum TypeCompareState
{
MustNot = -1, // types are not equal
May = 0, // types may be equal (must test at runtime)
Must = 1, // type are equal
}
public enum CorJitFlag : uint
{
CORJIT_FLAG_CALL_GETJITFLAGS = 0xffffffff, // Indicates that the JIT should retrieve flags in the form of a
// pointer to a CORJIT_FLAGS value via ICorJitInfo::getJitFlags().
CORJIT_FLAG_SPEED_OPT = 0,
CORJIT_FLAG_SIZE_OPT = 1,
CORJIT_FLAG_DEBUG_CODE = 2, // generate "debuggable" code (no code-mangling optimizations)
CORJIT_FLAG_DEBUG_EnC = 3, // We are in Edit-n-Continue mode
CORJIT_FLAG_DEBUG_INFO = 4, // generate line and local-var info
CORJIT_FLAG_MIN_OPT = 5, // disable all jit optimizations (not necesarily debuggable code)
CORJIT_FLAG_GCPOLL_CALLS = 6, // Emit calls to JIT_POLLGC for thread suspension.
CORJIT_FLAG_MCJIT_BACKGROUND = 7, // Calling from multicore JIT background thread, do not call JitComplete
CORJIT_FLAG_UNUSED1 = 8,
CORJIT_FLAG_UNUSED2 = 9,
CORJIT_FLAG_UNUSED3 = 10,
CORJIT_FLAG_UNUSED4 = 11,
CORJIT_FLAG_UNUSED5 = 12,
CORJIT_FLAG_UNUSED6 = 13,
CORJIT_FLAG_USE_AVX = 14,
CORJIT_FLAG_USE_AVX2 = 15,
CORJIT_FLAG_USE_AVX_512 = 16,
CORJIT_FLAG_FEATURE_SIMD = 17,
CORJIT_FLAG_MAKEFINALCODE = 18, // Use the final code generator, i.e., not the interpreter.
CORJIT_FLAG_READYTORUN = 19, // Use version-resilient code generation
CORJIT_FLAG_PROF_ENTERLEAVE = 20, // Instrument prologues/epilogues
CORJIT_FLAG_PROF_REJIT_NOPS = 21, // Insert NOPs to ensure code is re-jitable
CORJIT_FLAG_PROF_NO_PINVOKE_INLINE = 22, // Disables PInvoke inlining
CORJIT_FLAG_SKIP_VERIFICATION = 23, // (lazy) skip verification - determined without doing a full resolve. See comment below
CORJIT_FLAG_PREJIT = 24, // jit or prejit is the execution engine.
CORJIT_FLAG_RELOC = 25, // Generate relocatable code
CORJIT_FLAG_IMPORT_ONLY = 26, // Only import the function
CORJIT_FLAG_IL_STUB = 27, // method is an IL stub
CORJIT_FLAG_PROCSPLIT = 28, // JIT should separate code into hot and cold sections
CORJIT_FLAG_BBINSTR = 29, // Collect basic block profile information
CORJIT_FLAG_BBOPT = 30, // Optimize method based on profile information
CORJIT_FLAG_FRAMED = 31, // All methods have an EBP frame
CORJIT_FLAG_ALIGN_LOOPS = 32, // add NOPs before loops to align them at 16 byte boundaries
CORJIT_FLAG_PUBLISH_SECRET_PARAM = 33, // JIT must place stub secret param into local 0. (used by IL stubs)
CORJIT_FLAG_GCPOLL_INLINE = 34, // JIT must inline calls to GCPoll when possible
CORJIT_FLAG_SAMPLING_JIT_BACKGROUND = 35, // JIT is being invoked as a result of stack sampling for hot methods in the background
CORJIT_FLAG_USE_PINVOKE_HELPERS = 36, // The JIT should use the PINVOKE_{BEGIN,END} helpers instead of emitting inline transitions
CORJIT_FLAG_REVERSE_PINVOKE = 37, // The JIT should insert REVERSE_PINVOKE_{ENTER,EXIT} helpers into method prolog/epilog
CORJIT_FLAG_DESKTOP_QUIRKS = 38, // The JIT should generate desktop-quirk-compatible code
CORJIT_FLAG_TIER0 = 39, // This is the initial tier for tiered compilation which should generate code as quickly as possible
CORJIT_FLAG_TIER1 = 40, // This is the final tier (for now) for tiered compilation which should generate high quality code
CORJIT_FLAG_RELATIVE_CODE_RELOCS = 41, // JIT should generate PC-relative address computations instead of EE relocation records
CORJIT_FLAG_NO_INLINING = 42, // JIT should not inline any called method into this method
#region ARM64
CORJIT_FLAG_HAS_ARM64_AES = 43, // ID_AA64ISAR0_EL1.AES is 1 or better
CORJIT_FLAG_HAS_ARM64_ATOMICS = 44, // ID_AA64ISAR0_EL1.Atomic is 2 or better
CORJIT_FLAG_HAS_ARM64_CRC32 = 45, // ID_AA64ISAR0_EL1.CRC32 is 1 or better
CORJIT_FLAG_HAS_ARM64_DCPOP = 46, // ID_AA64ISAR1_EL1.DPB is 1 or better
CORJIT_FLAG_HAS_ARM64_DP = 47, // ID_AA64ISAR0_EL1.DP is 1 or better
CORJIT_FLAG_HAS_ARM64_FCMA = 48, // ID_AA64ISAR1_EL1.FCMA is 1 or better
CORJIT_FLAG_HAS_ARM64_FP = 49, // ID_AA64PFR0_EL1.FP is 0 or better
CORJIT_FLAG_HAS_ARM64_FP16 = 50, // ID_AA64PFR0_EL1.FP is 1 or better
CORJIT_FLAG_HAS_ARM64_JSCVT = 51, // ID_AA64ISAR1_EL1.JSCVT is 1 or better
CORJIT_FLAG_HAS_ARM64_LRCPC = 52, // ID_AA64ISAR1_EL1.LRCPC is 1 or better
CORJIT_FLAG_HAS_ARM64_PMULL = 53, // ID_AA64ISAR0_EL1.AES is 2 or better
CORJIT_FLAG_HAS_ARM64_SHA1 = 54, // ID_AA64ISAR0_EL1.SHA1 is 1 or better
CORJIT_FLAG_HAS_ARM64_SHA256 = 55, // ID_AA64ISAR0_EL1.SHA2 is 1 or better
CORJIT_FLAG_HAS_ARM64_SHA512 = 56, // ID_AA64ISAR0_EL1.SHA2 is 2 or better
CORJIT_FLAG_HAS_ARM64_SHA3 = 57, // ID_AA64ISAR0_EL1.SHA3 is 1 or better
CORJIT_FLAG_HAS_ARM64_SIMD = 58, // ID_AA64PFR0_EL1.AdvSIMD is 0 or better
CORJIT_FLAG_HAS_ARM64_SIMD_V81 = 59, // ID_AA64ISAR0_EL1.RDM is 1 or better
CORJIT_FLAG_HAS_ARM64_SIMD_FP16 = 60, // ID_AA64PFR0_EL1.AdvSIMD is 1 or better
CORJIT_FLAG_HAS_ARM64_SM3 = 61, // ID_AA64ISAR0_EL1.SM3 is 1 or better
CORJIT_FLAG_HAS_ARM64_SM4 = 62, // ID_AA64ISAR0_EL1.SM4 is 1 or better
CORJIT_FLAG_HAS_ARM64_SVE = 63, // ID_AA64PFR0_EL1.SVE is 1 or better
#endregion
#region x86/x64
CORJIT_FLAG_USE_SSE3 = 43,
CORJIT_FLAG_USE_SSSE3 = 44,
CORJIT_FLAG_USE_SSE41 = 45,
CORJIT_FLAG_USE_SSE42 = 46,
CORJIT_FLAG_USE_AES = 47,
CORJIT_FLAG_USE_BMI1 = 48,
CORJIT_FLAG_USE_BMI2 = 49,
CORJIT_FLAG_USE_FMA = 50,
CORJIT_FLAG_USE_LZCNT = 51,
CORJIT_FLAG_USE_PCLMULQDQ = 52,
CORJIT_FLAG_USE_POPCNT = 53,
#endregion
}
public struct CORJIT_FLAGS
{
private UInt64 _corJitFlags;
public void Reset()
{
_corJitFlags = 0;
}
public void Set(CorJitFlag flag)
{
_corJitFlags |= 1UL << (int)flag;
}
public void Clear(CorJitFlag flag)
{
_corJitFlags &= ~(1UL << (int)flag);
}
public bool IsSet(CorJitFlag flag)
{
return (_corJitFlags & (1UL << (int)flag)) != 0;
}
public void Add(ref CORJIT_FLAGS other)
{
_corJitFlags |= other._corJitFlags;
}
public void Remove(ref CORJIT_FLAGS other)
{
_corJitFlags &= ~other._corJitFlags;
}
public bool IsEmpty()
{
return _corJitFlags == 0;
}
}
}
| 46.606944 | 303 | 0.67579 | [
"MIT"
] | CoffeeFlux/runtime | src/coreclr/src/tools/Common/JitInterface/CorInfoTypes.cs | 67,114 | C# |
// <auto-generated />
// This file was generated by a T4 template.
// Don't change it directly as your change would get overwritten. Instead, make changes
// to the .tt file (i.e. the T4 template) and save it to regenerate this file.
// Make sure the compiler doesn't complain about missing Xml comments
#pragma warning disable 1591
#region T4MVC
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Framework.Mvc.T4MVC;
using T4MVC;
namespace Core.Forms.Controllers {
public partial class FormAnswersController {
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected FormAnswersController(Dummy d) { }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToAction(ActionResult result) {
var callInfo = result.GetT4MVCResult();
return RedirectToRoute(callInfo.RouteValueDictionary);
}
[NonAction]
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public System.Web.Mvc.JsonResult FormAnswersDynamicGridData() {
return new T4MVC_JsonResult(Area, Name, ActionNames.FormAnswersDynamicGridData);
}
[NonAction]
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public System.Web.Mvc.ActionResult ShowAnswers() {
return new T4MVC_ActionResult(Area, Name, ActionNames.ShowAnswers);
}
[NonAction]
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public System.Web.Mvc.ActionResult ShowAnswerDetails() {
return new T4MVC_ActionResult(Area, Name, ActionNames.ShowAnswerDetails);
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public FormAnswersController Actions { get { return FormsMVC.FormAnswers; } }
[GeneratedCode("T4MVC", "2.0")]
public readonly String Area = "";
[GeneratedCode("T4MVC", "2.0")]
public readonly String Name = "FormAnswers";
static readonly ActionNamesClass s_actions = new ActionNamesClass();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ActionNamesClass ActionNames { get { return s_actions; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionNamesClass {
public readonly String ShowAll = "ShowAll";
public readonly String FormAnswersDynamicGridData = "FormAnswersDynamicGridData";
public readonly String ShowAnswers = "ShowAnswers";
public readonly String ShowAnswerDetails = "ShowAnswerDetails";
}
static readonly ViewNames s_views = new ViewNames();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ViewNames Views { get { return s_views; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ViewNames {
public readonly String FormAnswerDetails = "~/Views/FormAnswers/FormAnswerDetails.aspx";
public readonly String FormAnswers = "~/Views/FormAnswers/FormAnswers.aspx";
public readonly String FormsAnswersList = "~/Views/FormAnswers/FormsAnswersList.aspx";
}
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class T4MVC_FormAnswersController: Core.Forms.Controllers.FormAnswersController {
public T4MVC_FormAnswersController() : base(Dummy.Instance) { }
public override System.Web.Mvc.ActionResult ShowAll() {
var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.ShowAll);
return callInfo;
}
public override System.Web.Mvc.JsonResult FormAnswersDynamicGridData(int page, int rows, string search, string sidx, string sord) {
var callInfo = new T4MVC_JsonResult(Area, Name, ActionNames.FormAnswersDynamicGridData);
callInfo.RouteValueDictionary.Add("page", page);
callInfo.RouteValueDictionary.Add("rows", rows);
callInfo.RouteValueDictionary.Add("search", search);
callInfo.RouteValueDictionary.Add("sidx", sidx);
callInfo.RouteValueDictionary.Add("sord", sord);
return callInfo;
}
public override System.Web.Mvc.ActionResult ShowAnswers(long formWidgetId) {
var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.ShowAnswers);
callInfo.RouteValueDictionary.Add("formWidgetId", formWidgetId);
return callInfo;
}
public override System.Web.Mvc.JsonResult ShowAnswers(long formWidgetId, int page, int rows, string sidx, string sord) {
var callInfo = new T4MVC_JsonResult(Area, Name, ActionNames.ShowAnswers);
callInfo.RouteValueDictionary.Add("formWidgetId", formWidgetId);
callInfo.RouteValueDictionary.Add("page", page);
callInfo.RouteValueDictionary.Add("rows", rows);
callInfo.RouteValueDictionary.Add("sidx", sidx);
callInfo.RouteValueDictionary.Add("sord", sord);
return callInfo;
}
public override System.Web.Mvc.ActionResult ShowAnswerDetails(long answerId) {
var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.ShowAnswerDetails);
callInfo.RouteValueDictionary.Add("answerId", answerId);
return callInfo;
}
}
}
#endregion T4MVC
#pragma warning restore 1591
| 44.52381 | 139 | 0.681818 | [
"BSD-2-Clause"
] | coreframework/Core-Framework | Source/Core.Forms/FormAnswersController.generated.cs | 5,610 | C# |
using HidSharp;
using OpenAsusKeyboardRGB.KBImpls.GenericImpls;
using OpenAsusKeyboardRGB.KBInterfaces;
using OpenAsusKeyboardRGB.KeyMappings;
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Threading;
namespace OpenAsusKeyboardRGB.KBImpls
{
class AsusClaymore : GenericHIDKeyboard, IArmouryProtocolKB, IAuraSyncProtocolKB
{
protected override int DevicePID => 6221;
protected override int DeviceVID => 2821;
public string PrettyName => "Asus Claymore (Core?)";
public void Connect()
{
HidDevice iface0Device;
if ((iface0Device = Utils.GetHidDevice(2821, DevicePID, 1, 0xFF00, out DeviceReportIDToUse)) != null)
{
DeviceHIDStream = iface0Device.Open();
DeviceHIDStream.ReadTimeout = 3000;
DeviceInputHandler = iface0Device.GetReportDescriptor().CreateHidDeviceInputReceiver();
DeviceInputHandler.Received += new EventHandler(OnHIDInputReceived);
DeviceInputHandler.Start(DeviceHIDStream);
DeviceMaximumInputReportLen = iface0Device.GetMaxInputReportLength();
}
}
public void SetProfileIndex(byte newIndex)
{
EnableHIDControl(true);
byte[] array = new byte[64];
array[0] = 81;
array[1] = 0;
array[4] = newIndex;
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.SetWritableData);
EnableHIDControl(false);
}
public byte GetProfileIndex()
{
EnableHIDControl(true);
byte[] array = new byte[64];
array[0] = 82;
array[1] = 0;
SendIface0ByteArray(array);
GetIface0Response(InterfaceZeroResponseTypes.GetWritableData, out byte[] buf);
EnableHIDControl(false);
return buf[4];
}
public void AuraSyncModeSwitch(bool state)
{
if (state)
{
SwitchToAuraSyncMode();
}
else
{
//1 is the default profile, 2 is the first user-programmable profile(?)
SetProfileIndex(1);
}
}
public void ExecuteProfileFlashCmd()
{
EnableHIDControl(true);
byte[] array = new byte[64];
array[0] = 80;
array[1] = 85;
array[4] = 0;
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.ExecuteProfileFlashCmd);
EnableHIDControl(false);
}
public void SetEffect_Static(Color mainColor, Color backgroundColor, byte brightness)
{
//Brightness is hardcoded
brightness = 0xFF;
InternalSendWriteType44((byte)ByteSelectedEffectTypes.Static, brightness, mainColor, backgroundColor);
}
public void SetEffect_ColorCycle(ColorCycleSpeeds colorCycleSpeed, byte brightness)
{
//Both parameters are hardcoded
InternalSendWriteType44((byte)ByteSelectedEffectTypes.ColorCycle, 128, Color.Empty, Color.Empty, 121);
}
public void SetEffect_Breathing(Color breathingColor1, Color breathingColor2, byte brightness, BreathingTypes breathingType, BreathingSpeeds speed)
{
if (breathingType != BreathingTypes.Single)
{
//Only single breathing mode is implemented in this keyboard
throw new ArgumentException();
}
//Both parameters are hardcoded here too
InternalSendWriteType44((byte)ByteSelectedEffectTypes.Breathing, byte.MaxValue, breathingColor1, Color.Empty, 107);
}
private void InternalSendWriteType44(byte byteSelectedEffect, byte brightness, Color color1, Color color2, byte speed = 0, byte randColorBit = 0, byte bgSinkBit = 0,
byte brightnessFadeBit = 0, byte byteDirection5Bits = 0, byte byteExt1 = 0xFF, byte byteExt2 = 0xFF)
{
EnableHIDControl(true);
byte[] array = new byte[64];
array[0] = 81;
array[1] = 44; //write type 44
//Array.Copy(kbInfo.effectModeData[0].byteIndex, 0, array, 2, 2);
for (int l = 0; l < 5; l++)
{
array[4 + l * 12] = byte.MaxValue;
array[7 + l * 12] = byte.MaxValue;
array[8 + l * 12] = byte.MaxValue;
array[9 + l * 12] = byte.MaxValue;
}
array[4] = byteSelectedEffect;
array[5] = speed;
array[6] = 0;
array[6] |= (byte)(randColorBit << 7);
array[6] |= (byte)((bgSinkBit << 6) & 0b01000000);
array[6] |= (byte)((brightnessFadeBit << 5) & 0b00100000);
array[6] |= (byte)((byteDirection5Bits) & 0b00011111);
array[7] = byteExt1;
array[8] = byteExt2;
array[9] = brightness;
array[10] = color1.R;
array[11] = color1.G;
array[12] = color1.B;
array[13] = color2.R;
array[14] = color2.G;
array[15] = color2.B;
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.SetWritableData);
SetByteSelectedEffectWritableData(byteSelectedEffect);
/*GetConst(99);
if (iProfileIndex == 0)
{
return;
}*/
ExecuteProfileFlashCmd();
EnableHIDControl(false);
}
#region Enums
private enum InterfaceZeroResponseTypes
{
GetInfo,
ApplyLight20P,
GetTarget,
SetTarget,
HIDControlStateSwitch,
GetConstantValue,
SetWritableData,
GetWritableData,
SetLedResponse,
AddressCommand,
SetFlashWritePoint,
GetFlashWritePoint,
WriteToFlash,
ExecuteMacroFlash,
ExecuteProfileFlashCmd,
GetKeyLogData,
AuraSyncProtocolUpdateCommand,
InvalidResponse
};
private enum ByteSelectedEffectTypes
{
Static,
Breathing,
ColorCycle,
Reactive,
Wave,
Ripple,
StarryNight,
Quicksand,
OFF = 254
};
#endregion
#region Direct color canvas update functions
private Tuple<int, int> DirectColorCanvasLength = Tuple.Create(23, 8);
public Color[,] GetNewDirectColorCanvas()
{
return new Color[DirectColorCanvasLength.Item2, DirectColorCanvasLength.Item1];
}
public Tuple<int, int> GetDirectColorCanvasIndexOfKey(AsusAuraSDKKeys key)
{
switch (key)
{
case AsusAuraSDKKeys.UNOFFICIAL_ISO_BACKSLASH:
return Tuple.Create(4, 1);
case AsusAuraSDKKeys.ROG_KEY_Z:
return Tuple.Create(4, 2);
case AsusAuraSDKKeys.ROG_KEY_X:
return Tuple.Create(4, 3);
case AsusAuraSDKKeys.ROG_KEY_C:
return Tuple.Create(4, 4);
case AsusAuraSDKKeys.ROG_KEY_V:
return Tuple.Create(4, 5);
case AsusAuraSDKKeys.ROG_KEY_B:
return Tuple.Create(4, 6);
case AsusAuraSDKKeys.ROG_KEY_N:
return Tuple.Create(4, 7);
case AsusAuraSDKKeys.ROG_KEY_M:
return Tuple.Create(4, 8);
case AsusAuraSDKKeys.ROG_KEY_COMMA:
return Tuple.Create(4, 9);
case AsusAuraSDKKeys.ROG_KEY_PERIOD:
return Tuple.Create(4, 10);
case AsusAuraSDKKeys.ROG_KEY_SLASH:
return Tuple.Create(4, 11);
case AsusAuraSDKKeys.UNOFFICIAL_ISO_HASH:
return Tuple.Create(3, 12);
case AsusAuraSDKKeys.ROG_KEY_LOGO:
return Tuple.Create(5, 8);
/*case AsusAuraSDKKeys.ROG_KEY_NUMPAD5:
return Tuple.Create(4, 19);
case AsusAuraSDKKeys.ROG_KEY_NUMPAD6:
return Tuple.Create(4, 21);*/
}
var rgbKey = AuraSyncProtocolKeyMappings.ClaymoreMapping.FirstOrDefault(x => x.KeyCode == (ushort)key);
if (rgbKey == null || rgbKey.X >= DirectColorCanvasLength.Item2 || rgbKey.Y >= DirectColorCanvasLength.Item1)
{
throw new ArgumentException();
}
return Tuple.Create((int)rgbKey.X, (int)rgbKey.Y);
}
public void SendDirectColorCanvas(Color[,] arg1)
{
//Claymore's key matrix is [Rows, Columns] whereas a sane key matrix is [Columns, Rows]
var colorArray = arg1.TransposeMatrix().FlattenMatrix();
int XMax = DirectColorCanvasLength.Item1;
int YMax = DirectColorCanvasLength.Item2;
int iVar12 = XMax * YMax;
byte[] buffer = new byte[64];
byte uVar14 = 0;
byte bVar6 = 0;
byte uVar9 = 0;
buffer[0] = 0xc0;
buffer[1] = 0x81;
buffer[2] = 0x0f;
do
{
int iVar10 = 0;
uint uVar11 = uVar14;
byte bVar8 = bVar6;
do
{
uint uVar3 = uVar11 & 0x80000007;
if ((int)uVar3 < 0)
{
uVar3 = (uVar3 - 1 | 0xfffffff8) + 1;
}
bVar6 = (byte)iVar10;
if (uVar3 != 0)
{
bVar6 = bVar8;
}
iVar10++;
uVar11--;
bVar8 = bVar6;
} while (iVar10 < 8);
iVar10 = uVar14 - bVar6;
buffer[uVar9 + 4] = (byte)(((byte)iVar10 + ((byte)(iVar10 >> 0x1f) & 7) & 0xf8) + bVar6);
buffer[uVar9 + 5] = colorArray[uVar14].R;
buffer[uVar9 + 6] = colorArray[uVar14].G;
buffer[uVar9 + 7] = colorArray[uVar14].B;
uVar14++;
bVar8 = (byte)(uVar9 + 4);
if (bVar8 == 60)
{
SendIface0ByteArray(buffer);
bVar8 = 0;
Array.Clear(buffer, 4, 20);
/*puVar5[4]
pbVar4 = puVar5 + 4;
lVar5 = 4;
do
{
*(undefined4*)(pbVar4) = 0;
pbVar4 += 4;
lVar5--;
} while (lVar5 != 0);*/
}
uVar9 = bVar8;
if (uVar14 == iVar12 - 1)
{
buffer[2] = (byte)(bVar8 >> 2);
SendIface0ByteArray(buffer);
}
} while (uVar14 < iVar12);
}
#endregion
#region HID response handling
private event Action<InterfaceZeroResponseTypes, ReadOnlyCollection<byte>> OnValidIface0ResponseEvent;
private void OnHIDInputReceived(object sender, EventArgs e)
{
var inputReportBuffer = new byte[DeviceMaximumInputReportLen];
//Flush pending report buffer
while (DeviceInputHandler.TryRead(inputReportBuffer, 0, out _))
{
//Dispatch by removing the report ID
DispatchInterfaceZeroResponse(inputReportBuffer.Skip(1).ToArray());
}
}
private void DispatchInterfaceZeroResponse(byte[] receivedBuffer)
{
var respType = Iface0GetResponseType(receivedBuffer);
Console.WriteLine("[Claymore] Got a response! Response type: " + respType.ToString());
OnValidIface0ResponseEvent?.Invoke(respType, Array.AsReadOnly(receivedBuffer));
}
private InterfaceZeroResponseTypes Iface0GetResponseType(byte[] receiveBuffer)
{
if (receiveBuffer.Length < 2)
{
return InterfaceZeroResponseTypes.InvalidResponse;
}
if (receiveBuffer[0] == 18 /*&& (new byte[] { 1, 0, 32, getInfoID }.Contains(receiveBuffer[1]))*/)
{
return InterfaceZeroResponseTypes.GetInfo;
}
else if (receiveBuffer[0] == 64 && receiveBuffer[1] == 146)
{
return InterfaceZeroResponseTypes.ApplyLight20P;
}
else if (receiveBuffer[0] == 64 && (new byte[] { 0, 32, 96, 97, 98, 99 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.GetConstantValue;
}
else if (receiveBuffer[0] == 16 && (new byte[] { 0, 2 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.GetTarget;
}
else if (receiveBuffer[0] == 16 && receiveBuffer[1] == 1)
{
return InterfaceZeroResponseTypes.SetTarget;
}
else if (receiveBuffer[0] == 65 && (new byte[] { 0, 1, 2, 3, 128 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.HIDControlStateSwitch;
}
else if (receiveBuffer[0] == 81 && (new byte[] { 0, 16, 24, 25, 40, 44, 160, 48, 168, 32, 41, 145, 144, 2 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.SetWritableData;
}
else if (receiveBuffer[0] == 82 && (new byte[] { 0, 16, 24, 25, 40, 44, 160, 48, 168, 32, 41, 145, 144, 2 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.GetWritableData;
}
else if (receiveBuffer[0] == 192 && (new byte[] { 0, 1, 2, 240 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.SetLedResponse;
}
else if (receiveBuffer[0] == 30 && receiveBuffer[1] == 1)
{
return InterfaceZeroResponseTypes.SetFlashWritePoint;
}
else if (receiveBuffer[0] == 30 && receiveBuffer[1] == 0)
{
return InterfaceZeroResponseTypes.GetFlashWritePoint;
}
else if (receiveBuffer[0] == 31 && receiveBuffer[1] == 52)
{
return InterfaceZeroResponseTypes.WriteToFlash;
}
else if (receiveBuffer[0] == 83 && (new byte[] { 0, 1, 16, 17, 255 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.ExecuteMacroFlash;
}
else if (receiveBuffer[0] == 80 && (new byte[] { 0, 16, 32, 85, 0, 1 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.ExecuteProfileFlashCmd;
}
else if (receiveBuffer[0] == 80 && (new byte[] { 0, 16, 32, 85, 0, 1 }.Contains(receiveBuffer[1])))
{
return InterfaceZeroResponseTypes.ExecuteProfileFlashCmd;
}
else if (receiveBuffer[0] == 67 && receiveBuffer[1] >= 128 && receiveBuffer[1] <= 159)
{
return InterfaceZeroResponseTypes.GetKeyLogData;
}
else if (receiveBuffer[0] == 67 && receiveBuffer[1] == 1)
{
return InterfaceZeroResponseTypes.GetKeyLogData;
}
else if (receiveBuffer[0] == 67)
{
if (receiveBuffer[1] >= 128 && receiveBuffer[1] <= 159)
{
return InterfaceZeroResponseTypes.GetKeyLogData;
}
else if (receiveBuffer[1] == 0)
{
//bSetKeyEvent
}
else if (receiveBuffer[1] == 1)
{
//array[4] = keyCodeTable X/Y packed struct
//array[5] = keystate packed struct
//FN + Special key response
}
}
else if (receiveBuffer[0] == 0xc0 && receiveBuffer[1] == 0x81)
{
return InterfaceZeroResponseTypes.AuraSyncProtocolUpdateCommand;
}
return InterfaceZeroResponseTypes.InvalidResponse;
}
//Warning: This function may throw a TimeoutException
private void GetIface0Response(InterfaceZeroResponseTypes responseType, out byte[] outBuffer, TimeSpan? timeout = null, bool copyBuffer = true)
{
if (timeout == null)
{
timeout = TimeSpan.FromSeconds(5);
}
byte[] localBufCopy = null;
var event_1 = new AutoResetEvent(false);
void eventSubscriber(InterfaceZeroResponseTypes respType, ReadOnlyCollection<byte> buf)
{
if (respType == responseType)
{
if (copyBuffer)
{
localBufCopy = new byte[buf.Count];
buf.CopyTo(localBufCopy, 0);
}
event_1.Set();
}
}
OnValidIface0ResponseEvent += eventSubscriber;
bool isTimedOut = !event_1.WaitOne(timeout.Value);
OnValidIface0ResponseEvent -= eventSubscriber;
outBuffer = localBufCopy;
if (isTimedOut)
{
throw new TimeoutException("Timed out while waiting for a response of the type " + responseType);
}
}
private bool WaitForIface0Confirmation(InterfaceZeroResponseTypes responseType, TimeSpan? timeout = null)
{
try
{
GetIface0Response(responseType, out _, timeout, false);
return true;
}
catch (TimeoutException)
{
//Timeouts happen because the keyboard doesn't respond sometimes
}
return false;
}
#endregion
#region Unimplemented Functions
public KeyLogData GetKeylogHistory()
{
throw new NotImplementedException(); //TODO
}
public void KeylogModeSwitch(bool state)
{
throw new NotImplementedException(); //TODO
}
public void SetEffect_WriteMultiStaticColorData(MultiStaticData arg1)
{
throw new NotImplementedException(); //TODO
}
public Tuple<int, int> GetMultiStaticColorDataIndexByVKCode(int virtualKeyCode)
{
throw new NotImplementedException(); //TODO
}
#endregion
#region Claymore specific functions
private void EnableHIDControl(bool state)
{
byte[] array = new byte[64];
array[0] = 65;
array[1] = (byte)(state ? 1 : 0);
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.HIDControlStateSwitch);
}
private void SwitchToAuraSyncMode()
{
byte[] array = new byte[64];
array[0] = 65;
array[1] = 3;
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.HIDControlStateSwitch);
}
private void SetByteSelectedEffectWritableData(byte newValue)
{
byte[] array = new byte[64];
array[0] = 81;
array[1] = 40; //write type 40
array[4] = newValue;
SendIface0ByteArray(array);
WaitForIface0Confirmation(InterfaceZeroResponseTypes.SetWritableData);
}
#endregion
}
}
| 35.861456 | 173 | 0.52526 | [
"MIT"
] | SnakePin/OpenAsusKeyboardRGB | src/OpenAsusKeyboardRGB_Library/KBImpls/AsusClaymoreAll.cs | 20,192 | C# |
using System.Collections.Generic;
using UnityEngine;
using QPath;
public class HexMap : MonoBehaviour, IQPathWorld {
public GameObject HexPrefab;
public GameObject ForestPrefab;
public GameObject JunglePrefab;
public Mesh MeshWater;
public Mesh MeshFlat;
public Mesh MeshHill;
public Mesh MeshMountain;
public Material MatDesert;
public Material MatOcean;
public Material MatPlain;
public Material MatGrasslands;
public Material MatMountain;
public GameObject UnitDwarfPrefab;
HexMapObject_Unit Dwarf = new HexMapObject_Unit();
// Tiles with height above x is given its appropriate mesh y
// Serializing is assigns the variable in memory (basically you can control the variable in the inspector which can lead to confusion, this "hides" it from the inspector
// (hiding would actually still not work as the value is still saved as whatever it was when the script was compiled))
[System.NonSerialized] public float HeightMountain = 1f;
[System.NonSerialized] public float HeightHill = 0.6f;
[System.NonSerialized] public float HeightFlat = 0f;
[System.NonSerialized] public float MoistureJungle = 1f;
[System.NonSerialized] public float MoistureForest = 0.3f;
[System.NonSerialized] public float MoistureGrasslands = 0f;
[System.NonSerialized] public float MoisturePlains = -0.75f;
[System.NonSerialized] public int numRows = 30;
[System.NonSerialized] public int numColumns = 60;
private Hex[,] hexes; // only setable in this class
private Dictionary<Hex, GameObject> hexToGameObjectMap;
private Dictionary<HexMapObject_Unit, GameObject> unitToGameObjectMap;
private Dictionary<GameObject, Hex> gameObjectToHexMap;
// @TODO: Link with Hex version for vertical/horizontal looping
bool allowWrapEastWest = true;
bool allowWrapNorthSouth = false;
// Start is called before the first frame update
void Start() {
GenerateMap();
}
void Update() {
if (Input.GetMouseButtonDown(1)) {
Debug.Log("Move time");
Hex toMoveto = new Hex(29, 13, this);
Dwarf.SetHex(toMoveto);
}
if (Input.GetKeyDown("p")) {
Dwarf.DUMMY_PATHING_FUNCTION();
}
if (Input.GetKeyDown("space")) {
Dwarf.DoMove();
}
if (Input.GetKeyDown("n")) {
Dwarf.RefreshMovement();
}
}
public Hex GetHexAt(int x, int y) {
if (hexes == null) {
//throw new UnityException("No Hex array to fetch from"); // This would be be a "loud" exception that will crash the code
Debug.Log("No Hex array to fetch from");
return null; //returns early
}
if (allowWrapEastWest) {
x = x % numColumns; //NOTE!! the modulo on x to num rows. This is due to the wrapping west east. ie row -1 will be row numRows -1
if (x < 0) {
x += numColumns;
}
}
if (allowWrapNorthSouth) {
y = y % numRows;
if (y < 0) {
y += numRows;
}
}
if (x < 0 || y < 0) {
return null; // This is to retrieve the relevant area of the map even if there is overflow out of the map
}
return hexes[x, y];
}
public Vector3 GetHexPosition(int q, int r) {
Hex hex = GetHexAt(q, r);
return GetHexPosition(hex);
}
public Vector3 GetHexPosition(Hex hex) {
return hex.PositionFromCamera(Camera.main.transform.position, numRows, numColumns);
}
public Hex GetHexFromGameObject(GameObject hexGO) {
if (gameObjectToHexMap.ContainsKey(hexGO)) {
return gameObjectToHexMap[hexGO];
}
return null;
}
public GameObject GetHexGO(Hex h) {
if (hexToGameObjectMap.ContainsKey(h)) {
return hexToGameObjectMap[h];
}
return null;
}
public GameObject GetUnitGO(HexMapObject_Unit c) {
if (unitToGameObjectMap.ContainsKey(c)) {
return unitToGameObjectMap[c];
}
return null;
}
virtual public void GenerateMap() {
hexes = new Hex[numColumns, numRows];
hexToGameObjectMap = new Dictionary<Hex, GameObject>();
for (int column = 0; column < numColumns; column++) {
for (int row = 0; row < numRows; row++) {
Hex hex = new Hex(column, row, this); // This is passing the HexMap to the Hex so it is aware of certain Map parameters
hex.Elevation = -0.5f; // initially all hexxes under water Generate map with ocean
hexes[column, row] = hex;
Vector3 postionFromCamera = hex.PositionFromCamera(Camera.main.transform.position, numColumns, numRows);
//Instantiate Hex Object
GameObject hexGO = Instantiate(HexPrefab, postionFromCamera, Quaternion.identity, this.transform);
hexGO.name = string.Format("Hex {0}, {1}", column, row); // naming the object in the Heirachy
hexToGameObjectMap.Add(hex, hexGO); // add the link between hex and gameObject. NOTE! you can add to a directionary with hexToGameObjectMap.Add(hex, hexGO) but this is fine too
hex.TerrainType = Hex.TERRAIN_TYPE.OCEAN;
hex.ElevationType = Hex.ELEVATION_TYPE.WATER;
hexGO.GetComponent<HexComponent>().Hex = hex; // Gives the Hex Component script reference to the instantiated hex
hexGO.GetComponent<HexComponent>().HexMap = this; // Gives the Hex Component script reference to the instantiated hex
}
}
UpdateHexVisuals();
SpawnUnitAt(Dwarf, UnitDwarfPrefab, 28, 13);
}
public void UpdateHexVisuals() {
for (int column = 0; column < numColumns; column++) {
for (int row = 0; row < numRows; row++) {
Hex hex = hexes[column, row];
GameObject hexGO = hexToGameObjectMap[hex];
HexComponent hexComp = hexGO.GetComponentInChildren<HexComponent>();
MeshRenderer hexMR = hexGO.GetComponentInChildren<MeshRenderer>();
MeshFilter hexMF = hexGO.GetComponentInChildren<MeshFilter>();
setHexTypeFromElevationAndMoisture(hex, hexMR, hexMF, hexGO, hexComp);
hexGO.GetComponentInChildren<TextMesh>().text = string.Format("{0}, {1} \n{2}", column, row, hex.BaseMovementCost(false, false, false));
}
}
}
void setHexTypeFromElevationAndMoisture(Hex h, MeshRenderer mr, MeshFilter mf, GameObject hexGO, HexComponent hexComp) {
if (h.Elevation >= HeightFlat && h.Elevation < HeightMountain) {
if (h.Moisture >= MoistureJungle) {
mr.material = MatGrasslands;
h.TerrainType = Hex.TERRAIN_TYPE.GRASSLANDS;
h.FeatureType = Hex.FEATURE_TYPE.RAINFOREST;
// Spawn trees
Vector3 p = hexGO.transform.position;
if (h.Elevation >= HeightHill) {
p.y += 0.25f;
}
GameObject.Instantiate(JunglePrefab, p, Quaternion.identity, hexGO.transform);
} else if (h.Moisture >= MoistureForest) {
mr.material = MatGrasslands;
h.TerrainType = Hex.TERRAIN_TYPE.GRASSLANDS;
h.FeatureType = Hex.FEATURE_TYPE.FOREST;
// Spawn trees
Vector3 p = hexGO.transform.position;
if (h.Elevation >= HeightHill) {
p.y += 0.25f;
}
GameObject.Instantiate(ForestPrefab, p, Quaternion.identity, hexGO.transform);
} else if (h.Moisture >= MoistureGrasslands) {
mr.material = MatGrasslands;
h.TerrainType = Hex.TERRAIN_TYPE.GRASSLANDS;
} else if (h.Moisture >= MoisturePlains) {
mr.material = MatPlain;
h.TerrainType = Hex.TERRAIN_TYPE.PLAINS;
} else {
mr.material = MatDesert;
h.TerrainType = Hex.TERRAIN_TYPE.DESERT;
}
}
if (h.Elevation >= HeightMountain) {
mr.material = MatMountain;
mf.mesh = MeshMountain;
h.ElevationType = Hex.ELEVATION_TYPE.MOUNTAIN;
} else if (h.Elevation >= HeightHill) {
h.ElevationType = Hex.ELEVATION_TYPE.HILL;
mf.mesh = MeshHill;
hexComp.VerticalOffset = 0.25f;
} else if (h.Elevation >= HeightFlat) {
h.ElevationType = Hex.ELEVATION_TYPE.FLAT;
mf.mesh = MeshFlat;
} else {
h.ElevationType = Hex.ELEVATION_TYPE.WATER;
mr.material = MatOcean;
mf.mesh = MeshWater;
}
}
public Hex[] GetHexesWithinRangeOf(Hex centerHex, int range) {
List<Hex> results = new List<Hex>();
for (int dx = -range; dx <= range; dx++) {
for (int dy = Mathf.Max(-range, -dx - range); dy <= Mathf.Min(range, -dx + range); dy++) {
Hex retrievedHex = GetHexAt(centerHex.Q + dx, centerHex.R + dy);
if (retrievedHex != null) {
results.Add(retrievedHex);
}
}
}
return results.ToArray();
}
public void SpawnUnitAt(HexMapObject_Unit unit, GameObject prefab, int q, int r) {
if (unitToGameObjectMap == null) {
unitToGameObjectMap = new Dictionary<HexMapObject_Unit, GameObject>();
}
Hex hexToSpawnAt = GetHexAt(q, r);
GameObject hexToSpawnAtGO = hexToGameObjectMap[hexToSpawnAt];
GameObject unitGO = Instantiate(prefab, hexToSpawnAtGO.transform.position, Quaternion.identity, hexToSpawnAtGO.transform);
unit.SetHex(hexToSpawnAt);
unit.OnObjectMoved += unitGO.GetComponent<HexMapObject_UnitVisuals>().OnUnitMoved;
//CurrentPlayer.AddUnit(unit);
//unit.OnObjectDestroyed += OnUnitDestroyed;
//unitToGameObjectMap.Add(unit, unitGO);
}
} | 36.745098 | 216 | 0.655283 | [
"MIT"
] | StuartGough7/Hex-Strategy-Demo | Assets/Scripts/HexMap.cs | 9,372 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CafeOtomasyon
{
public partial class KullaniciGuncelleTur : Form
{
public KullaniciGuncelleTur()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
KullaniciYetkiCombo.Enabled = false;
this.Hide();
}
private void KullaniciGuncelleTur_Load(object sender, EventArgs e)
{
KullaniciYetkiCombo.Enabled = true;
}
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Hide();
}
private void bunifuImageButton2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
| 23.261905 | 74 | 0.633572 | [
"Apache-2.0"
] | FrozenShadows/cafeotomasyon | CafeOtomasyon/KullaniciGuncelleTur.cs | 979 | C# |
namespace JsonWebToken
{
/// <summary>
/// Represents the metadata of the JWT, like the cryptographic
/// operations applied to the JWT and optionally any additional properties of the JWT.
/// </summary>
public sealed class JwtHeader : JsonObject
{
/// <summary>Initializes a new instance of the <see cref="JsonObject"/> class.</summary>
public JwtHeader()
: base(MemberStore.CreateSlowGrowingStore())
{
}
}
} | 32.266667 | 96 | 0.630165 | [
"MIT"
] | signature-opensource/Jwt | src/JsonWebToken/Writer/JwtHeader.cs | 486 | C# |
using System;
namespace UnrealEngine
{
/// <summary>LINEAR DOF</summary>
public enum ELinearConstraintMotion:byte
{
/// <summary>No constraint against this axis.</summary>
LCM_Free=0,
/// <summary>Limited freedom along this axis.</summary>
LCM_Limited=1,
/// <summary>Fully constraint against this axis.</summary>
LCM_Locked=2,
LCM_MAX=3,
}
}
| 20.333333 | 60 | 0.704918 | [
"MIT"
] | xiongfang/UnrealCS | Script/UnrealEngine/GeneratedScriptFile/ELinearConstraintMotion.cs | 366 | C# |
#nullable enable
using System;
using System.Threading.Tasks;
using Content.Server.Body.Circulatory;
using Content.Shared.Chemistry;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution.Components;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Helpers;
using Content.Shared.Notification;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Players;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Chemistry.Components
{
/// <summary>
/// Server behavior for reagent injectors and syringes. Can optionally support both
/// injection and drawing or just injection. Can inject/draw reagents from solution
/// containers, and can directly inject into a mobs bloodstream.
/// </summary>
[RegisterComponent]
public class InjectorComponent : SharedInjectorComponent, IAfterInteract, IUse, ISolutionChange
{
/// <summary>
/// Whether or not the injector is able to draw from containers or if it's a single use
/// device that can only inject.
/// </summary>
[ViewVariables]
[DataField("injectOnly")]
private bool _injectOnly;
/// <summary>
/// Amount to inject or draw on each usage. If the injector is inject only, it will
/// attempt to inject it's entire contents upon use.
/// </summary>
[ViewVariables]
[DataField("transferAmount")]
private ReagentUnit _transferAmount = ReagentUnit.New(5);
/// <summary>
/// Initial storage volume of the injector
/// </summary>
[ViewVariables]
[DataField("initialMaxVolume")]
private ReagentUnit _initialMaxVolume = ReagentUnit.New(15);
private InjectorToggleMode _toggleState;
/// <summary>
/// The state of the injector. Determines it's attack behavior. Containers must have the
/// right SolutionCaps to support injection/drawing. For InjectOnly injectors this should
/// only ever be set to Inject
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public InjectorToggleMode ToggleState
{
get => _toggleState;
set
{
_toggleState = value;
Dirty();
}
}
protected override void Startup()
{
base.Startup();
Dirty();
}
/// <summary>
/// Toggle between draw/inject state if applicable
/// </summary>
private void Toggle(IEntity user)
{
if (_injectOnly)
{
return;
}
string msg;
switch (ToggleState)
{
case InjectorToggleMode.Inject:
ToggleState = InjectorToggleMode.Draw;
msg = "Now drawing";
break;
case InjectorToggleMode.Draw:
ToggleState = InjectorToggleMode.Inject;
msg = "Now injecting";
break;
default:
throw new ArgumentOutOfRangeException();
}
Owner.PopupMessage(user, Loc.GetString(msg));
}
/// <summary>
/// Called when clicking on entities while holding in active hand
/// </summary>
/// <param name="eventArgs"></param>
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true))
return false;
//Make sure we have the attacking entity
if (eventArgs.Target == null || !Owner.HasComponent<SolutionContainerComponent>())
{
return false;
}
var targetEntity = eventArgs.Target;
// Handle injecting/drawing for solutions
if (targetEntity.TryGetComponent<ISolutionInteractionsComponent>(out var targetSolution))
{
if (ToggleState == InjectorToggleMode.Inject)
{
if (targetSolution.CanInject)
{
TryInject(targetSolution, eventArgs.User);
}
else
{
eventArgs.User.PopupMessage(eventArgs.User,
Loc.GetString("You aren't able to transfer to {0:theName}!", targetSolution.Owner));
}
}
else if (ToggleState == InjectorToggleMode.Draw)
{
if (targetSolution.CanDraw)
{
TryDraw(targetSolution, eventArgs.User);
}
else
{
eventArgs.User.PopupMessage(eventArgs.User,
Loc.GetString("You aren't able to draw from {0:theName}!", targetSolution.Owner));
}
}
}
// Handle injecting into bloodstream
else if (targetEntity.TryGetComponent(out BloodstreamComponent? bloodstream) &&
ToggleState == InjectorToggleMode.Inject)
{
TryInjectIntoBloodstream(bloodstream, eventArgs.User);
}
return true;
}
/// <summary>
/// Called when use key is pressed when held in active hand
/// </summary>
/// <param name="eventArgs"></param>
/// <returns></returns>
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
Toggle(eventArgs.User);
return true;
}
private void TryInjectIntoBloodstream(BloodstreamComponent targetBloodstream, IEntity user)
{
if (!Owner.TryGetComponent(out SolutionContainerComponent? solution) || solution.CurrentVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = ReagentUnit.Min(_transferAmount, targetBloodstream.EmptyVolume);
if (realTransferAmount <= 0)
{
Owner.PopupMessage(user,
Loc.GetString("You aren't able to inject {0:theName}!", targetBloodstream.Owner));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = solution.SplitSolution(realTransferAmount);
if (!solution.CanAddSolution(removedSolution))
{
return;
}
// TODO: Account for partial transfer.
removedSolution.DoEntityReaction(solution.Owner, ReactionMethod.Injection);
solution.TryAddSolution(removedSolution);
removedSolution.DoEntityReaction(targetBloodstream.Owner, ReactionMethod.Injection);
Owner.PopupMessage(user,
Loc.GetString("You inject {0}u into {1:theName}!", removedSolution.TotalVolume,
targetBloodstream.Owner));
Dirty();
AfterInject();
}
private void TryInject(ISolutionInteractionsComponent targetSolution, IEntity user)
{
if (!Owner.TryGetComponent(out SolutionContainerComponent? solution) || solution.CurrentVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = ReagentUnit.Min(_transferAmount, targetSolution.InjectSpaceAvailable);
if (realTransferAmount <= 0)
{
Owner.PopupMessage(user, Loc.GetString("{0:theName} is already full!", targetSolution.Owner));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = solution.SplitSolution(realTransferAmount);
removedSolution.DoEntityReaction(targetSolution.Owner, ReactionMethod.Injection);
targetSolution.Inject(removedSolution);
Owner.PopupMessage(user,
Loc.GetString("You transfer {0}u to {1:theName}", removedSolution.TotalVolume, targetSolution.Owner));
Dirty();
AfterInject();
}
private void AfterInject()
{
// Automatically set syringe to draw after completely draining it.
if (Owner.GetComponent<SolutionContainerComponent>().CurrentVolume == 0)
{
ToggleState = InjectorToggleMode.Draw;
}
}
private void TryDraw(ISolutionInteractionsComponent targetSolution, IEntity user)
{
if (!Owner.TryGetComponent(out SolutionContainerComponent? solution) || solution.EmptyVolume == 0)
{
return;
}
// Get transfer amount. May be smaller than _transferAmount if not enough room
var realTransferAmount = ReagentUnit.Min(_transferAmount, targetSolution.DrawAvailable);
if (realTransferAmount <= 0)
{
Owner.PopupMessage(user, Loc.GetString("{0:theName} is empty!", targetSolution.Owner));
return;
}
// Move units from attackSolution to targetSolution
var removedSolution = targetSolution.Draw(realTransferAmount);
if (!solution.TryAddSolution(removedSolution))
{
return;
}
Owner.PopupMessage(user,
Loc.GetString("Drew {0}u from {1:theName}", removedSolution.TotalVolume, targetSolution.Owner));
Dirty();
AfterDraw();
}
private void AfterDraw()
{
// Automatically set syringe to inject after completely filling it.
if (Owner.GetComponent<SolutionContainerComponent>().EmptyVolume == 0)
{
ToggleState = InjectorToggleMode.Inject;
}
}
void ISolutionChange.SolutionChanged(SolutionChangeEventArgs eventArgs)
{
Dirty();
}
public override ComponentState GetComponentState(ICommonSession player)
{
Owner.TryGetComponent(out SolutionContainerComponent? solution);
var currentVolume = solution?.CurrentVolume ?? ReagentUnit.Zero;
var maxVolume = solution?.MaxVolume ?? ReagentUnit.Zero;
return new InjectorComponentState(currentVolume, maxVolume, ToggleState);
}
}
}
| 35.719472 | 118 | 0.577104 | [
"MIT"
] | GalacticChimp/space-station-14 | Content.Server/Chemistry/Components/InjectorComponent.cs | 10,825 | C# |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// A complex element consisting of: * lastSentDateTime – the date and time the user last sent an envelope. * lastSignedDateTime – the date and time the user last signed an envelope. * sentCount – the number of envelopes the user has sent. * signedCount – the number of envelopes the user has signed.
/// </summary>
[DataContract]
public partial class UsageHistory : IEquatable<UsageHistory>, IValidatableObject
{
public UsageHistory()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="UsageHistory" /> class.
/// </summary>
/// <param name="LastSentDateTime">The date and time the user last sent an envelope. .</param>
/// <param name="LastSignedDateTime">The date and time the user last signed an envelope..</param>
/// <param name="SentCount">The number of envelopes the user has sent. .</param>
/// <param name="SignedCount">The number of envelopes the user has signed. .</param>
public UsageHistory(string LastSentDateTime = default(string), string LastSignedDateTime = default(string), int? SentCount = default(int?), int? SignedCount = default(int?))
{
this.LastSentDateTime = LastSentDateTime;
this.LastSignedDateTime = LastSignedDateTime;
this.SentCount = SentCount;
this.SignedCount = SignedCount;
}
/// <summary>
/// The date and time the user last sent an envelope.
/// </summary>
/// <value>The date and time the user last sent an envelope. </value>
[DataMember(Name="lastSentDateTime", EmitDefaultValue=false)]
public string LastSentDateTime { get; set; }
/// <summary>
/// The date and time the user last signed an envelope.
/// </summary>
/// <value>The date and time the user last signed an envelope.</value>
[DataMember(Name="lastSignedDateTime", EmitDefaultValue=false)]
public string LastSignedDateTime { get; set; }
/// <summary>
/// The number of envelopes the user has sent.
/// </summary>
/// <value>The number of envelopes the user has sent. </value>
[DataMember(Name="sentCount", EmitDefaultValue=false)]
public int? SentCount { get; set; }
/// <summary>
/// The number of envelopes the user has signed.
/// </summary>
/// <value>The number of envelopes the user has signed. </value>
[DataMember(Name="signedCount", EmitDefaultValue=false)]
public int? SignedCount { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UsageHistory {\n");
sb.Append(" LastSentDateTime: ").Append(LastSentDateTime).Append("\n");
sb.Append(" LastSignedDateTime: ").Append(LastSignedDateTime).Append("\n");
sb.Append(" SentCount: ").Append(SentCount).Append("\n");
sb.Append(" SignedCount: ").Append(SignedCount).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as UsageHistory);
}
/// <summary>
/// Returns true if UsageHistory instances are equal
/// </summary>
/// <param name="other">Instance of UsageHistory to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UsageHistory other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.LastSentDateTime == other.LastSentDateTime ||
this.LastSentDateTime != null &&
this.LastSentDateTime.Equals(other.LastSentDateTime)
) &&
(
this.LastSignedDateTime == other.LastSignedDateTime ||
this.LastSignedDateTime != null &&
this.LastSignedDateTime.Equals(other.LastSignedDateTime)
) &&
(
this.SentCount == other.SentCount ||
this.SentCount != null &&
this.SentCount.Equals(other.SentCount)
) &&
(
this.SignedCount == other.SignedCount ||
this.SignedCount != null &&
this.SignedCount.Equals(other.SignedCount)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.LastSentDateTime != null)
hash = hash * 59 + this.LastSentDateTime.GetHashCode();
if (this.LastSignedDateTime != null)
hash = hash * 59 + this.LastSignedDateTime.GetHashCode();
if (this.SentCount != null)
hash = hash * 59 + this.SentCount.GetHashCode();
if (this.SignedCount != null)
hash = hash * 59 + this.SignedCount.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.517045 | 307 | 0.577899 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | redistributable/docusign-csharp-client/DocuSign.eSign/Model/UsageHistory.cs | 7,139 | C# |
namespace PracticeWebApp.Data.Models.BlobStorage
{
public class Credentials
{
public string Endpoint { get; set; }
public string AccessKey { get; set; }
public string SecretKey { get; set; }
}
}
| 23.2 | 49 | 0.62931 | [
"MIT"
] | Mason32NZ/PracticeWebApp | PracticeWebApp.Data/Models/BlobStorage/Credentials.cs | 234 | C# |
using GizmoFort.Connector.ERPNext.PublicTypes;
using GizmoFort.Connector.ERPNext.WrapperTypes;
using System.ComponentModel;
namespace GizmoFort.Connector.ERPNext.ERPTypes.Packing_slip_item
{
public class ERPPacking_slip_item : ERPNextObjectBase
{
public ERPPacking_slip_item() : this(new ERPObject(DocType.Packing_slip_item)) { }
public ERPPacking_slip_item(ERPObject obj) : base(obj) { }
public static ERPPacking_slip_item Create(string itemcode, string itemname, string batchno, string description, double qty, double netweight, string stockuom, string weightuom, long pagebreak, string dndetail)
{
ERPPacking_slip_item obj = new ERPPacking_slip_item();
obj.item_code = itemcode;
obj.item_name = itemname;
obj.batch_no = batchno;
obj.description = description;
obj.qty = qty;
obj.net_weight = netweight;
obj.stock_uom = stockuom;
obj.weight_uom = weightuom;
obj.page_break = pagebreak;
obj.dn_detail = dndetail;
return obj;
}
public string item_code
{
get { return data.item_code; }
set
{
data.item_code = value;
data.name = value;
}
}
public string item_name
{
get { return data.item_name; }
set { data.item_name = value; }
}
public string batch_no
{
get { return data.batch_no; }
set { data.batch_no = value; }
}
public string description
{
get { return data.description; }
set { data.description = value; }
}
public double qty
{
get { return data.qty; }
set { data.qty = value; }
}
public double net_weight
{
get { return data.net_weight; }
set { data.net_weight = value; }
}
public string stock_uom
{
get { return data.stock_uom; }
set { data.stock_uom = value; }
}
public string weight_uom
{
get { return data.weight_uom; }
set { data.weight_uom = value; }
}
public long page_break
{
get { return data.page_break; }
set { data.page_break = value; }
}
public string dn_detail
{
get { return data.dn_detail; }
set { data.dn_detail = value; }
}
}
//Enums go here
} | 26.744898 | 217 | 0.538344 | [
"MIT"
] | dmequus/gizmofort.connector.erpnext | Libs/GizmoFort.Connector.ERPNext/ERPTypes/Packing_slip_item/ERPPacking_slip_item.cs | 2,621 | C# |
namespace OpenCV_test.Common
{
partial class ImageInOutCtrl
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージド リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region コンポーネント デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.numericUpDownInputNo = new System.Windows.Forms.NumericUpDown();
this.numericUpDownOutNo = new System.Windows.Forms.NumericUpDown();
this.groupBox1 = new System.Windows.Forms.GroupBox();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownInputNo)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownOutNo)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(3, 12);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(50, 12);
this.label5.TabIndex = 43;
this.label5.Text = "Input No.";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(64, 12);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(59, 12);
this.label4.TabIndex = 44;
this.label4.Text = "Output No.";
//
// numericUpDownInputNo
//
this.numericUpDownInputNo.Location = new System.Drawing.Point(3, 27);
this.numericUpDownInputNo.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.numericUpDownInputNo.Name = "numericUpDownInputNo";
this.numericUpDownInputNo.Size = new System.Drawing.Size(57, 19);
this.numericUpDownInputNo.TabIndex = 41;
//
// numericUpDownOutNo
//
this.numericUpDownOutNo.Location = new System.Drawing.Point(66, 27);
this.numericUpDownOutNo.Maximum = new decimal(new int[] {
9,
0,
0,
0});
this.numericUpDownOutNo.Name = "numericUpDownOutNo";
this.numericUpDownOutNo.Size = new System.Drawing.Size(57, 19);
this.numericUpDownOutNo.TabIndex = 42;
this.numericUpDownOutNo.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.numericUpDownOutNo);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.numericUpDownInputNo);
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(1);
this.groupBox1.Size = new System.Drawing.Size(150, 50);
this.groupBox1.TabIndex = 45;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Image";
//
// ImageInOutCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupBox1);
this.Name = "ImageInOutCtrl";
this.Size = new System.Drawing.Size(150, 50);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownInputNo)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownOutNo)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown numericUpDownInputNo;
private System.Windows.Forms.NumericUpDown numericUpDownOutNo;
private System.Windows.Forms.GroupBox groupBox1;
}
}
| 40.48062 | 158 | 0.573918 | [
"BSD-3-Clause"
] | iryachi/OpenCV_test | OpenCV_test/Common/ImageInOutCtrl.Designer.cs | 5,510 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Bit.Core.Models.Data;
using Bit.Core.Models.Table;
namespace Bit.Core.Repositories
{
public interface IOrganizationRepository : IRepository<Organization, Guid>
{
Task<ICollection<Organization>> GetManyByEnabledAsync();
Task<ICollection<Organization>> GetManyByUserIdAsync(Guid userId);
Task<ICollection<Organization>> SearchAsync(string name, string userEmail, bool? paid, int skip, int take);
Task UpdateStorageAsync(Guid id);
Task<ICollection<OrganizationAbility>> GetManyAbilitiesAsync();
}
}
| 35.222222 | 115 | 0.750789 | [
"MPL-2.0"
] | carloskcheung/fossa-cli | test/fixtures/nuget/src/Core/Repositories/IOrganizationRepository.cs | 636 | C# |
using System;
using HaloEzAPI.Converter;
using Newtonsoft.Json;
namespace HaloEzAPI.Model.Response.Stats.Halo5.Events
{
public class WeaponDropEvent : WeaponEvent
{
public int ShotsFired { get; set; }
public int ShotsLanded { get; set; }
[JsonConverter(typeof(TimeSpanConverter))]
public TimeSpan TimeWeaponActiveAsPrimary { get; set; }
}
} | 27.5 | 63 | 0.698701 | [
"MIT"
] | BadDub/Halo-API | HaloEzAPI/Model/Response/Stats/Halo5/Events/WeaponDropEvent.cs | 385 | C# |
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using TetraPak.XP;
using TetraPak.XP.ApplicationInformation;
using TetraPak.XP.Auth.Abstractions;
using TetraPak.XP.DependencyInjection;
using TetraPak.XP.Desktop;
using TetraPak.XP.Identity;
using TetraPak.XP.Logging.Abstractions;
using TetraPak.XP.Logging.Microsoft;
using TetraPak.XP.OAuth2;
using TetraPak.XP.OAuth2.AuthCode;
using TetraPak.XP.OAuth2.ClientCredentials;
using TetraPak.XP.OAuth2.DeviceCode;
using TetraPak.XP.OAuth2.TokenExchange;
using TetraPak.XP.Web.Services;
using UserInformation = TetraPak.XP.Identity.UserInformation;
namespace authClient.console
{
sealed class Auth
{
readonly ILog? _log;
readonly IServiceProvider? _serviceProvider;
Grant? _lastGrant;
public Task AcquireTokenAsync(GrantType grantType, CancellationTokenSource cts, bool forced = false)
{
return Task.Run(async () =>
{
var options = forced
? GrantOptions.Forced(cts)
: GrantOptions.Silent(cts);
var provider = _serviceProvider ?? throw new Exception("No service provider!");
switch (grantType)
{
case GrantType.OIDC:
var ac = provider.GetRequiredService<IAuthorizationCodeGrantService>();
Console.WriteLine();
Console.WriteLine("OIDC grant requested ...");
onOutcome(await ac.AcquireTokenAsync(options.WithHtmlResponseHandlers(
loadHtmlAsync(new FileInfo("./_html/authComplete.html"), true),
loadHtmlAsync(new FileInfo("./_html/authComplete.html"), false))));
break;
case GrantType.CC:
var cc = provider.GetRequiredService<IClientCredentialsGrantService>();
Console.WriteLine();
Console.WriteLine("Client Credentials grant requested ...");
onOutcome(await cc.AcquireTokenAsync(options));
break;
case GrantType.DC:
var dc = provider.GetRequiredService<IDeviceCodeGrantService>();
Console.WriteLine();
Console.WriteLine("Device Code grant requested ...");
onOutcome(await dc.AcquireTokenAsync(options, requestUserCodeVerificationAsync));
break;
case GrantType.TX:
Console.WriteLine();
if (_lastGrant?.IdToken is null)
{
Console.WriteLine("Token Exchange requires an existing identity token. Please execute OIDC or Device Code grant first");
break;
}
var tx = provider.GetRequiredService<ITokenExchangeGrantService>();
Console.WriteLine("Token Exchange grant requested ...");
onOutcome(await tx.AcquireTokenAsync(_lastGrant.IdToken, options));
break;
default:
throw new ArgumentOutOfRangeException(nameof(grantType), grantType, null);
}
});
}
static async Task<string> loadHtmlAsync(FileInfo htmlFile, bool isSuccess)
{
using var reader = htmlFile.OpenText();
var html = await reader.ReadToEndAsync();
return html
.Replace("#outcome", isSuccess ? "ok" : "error")
.Replace("#message", isSuccess
? "Authorization Code grant was completed"
: "Authorization Code grant failed");
}
public async Task GetUserInformationAsync(CancellationTokenSource cts)
{
if (_lastGrant?.AccessToken is null)
{
Console.WriteLine("Please obtain a grant and try again!");
return;
}
var provider = _serviceProvider ?? throw new Exception("No service provider!");
var ui = provider.GetRequiredService<IUserInformationService>();
onOutcome(await ui.GetUserInformationAsync(_lastGrant, GrantOptions.Default()));
}
static Task requestUserCodeVerificationAsync(VerificationArgs args)
{
Console.WriteLine($"Please very code '{args.UserCode}' on: {args.VerificationUri} ...");
return Task.CompletedTask;
}
void onOutcome(Outcome<Grant> outcome)
{
if (!outcome)
{
if (!string.IsNullOrWhiteSpace(outcome.Message))
{
_log.Warning(outcome.Message);
}
else if (outcome.Exception is { })
{
_log.Warning(outcome.Exception.Message);
}
else
{
_log.Warning("Authorization failed with no message");
}
return;
}
_lastGrant = outcome.Value;
var sb = new StringBuilder();
sb.AppendLine("SUCCESS!");
var grant = outcome.Value!;
sb.AppendLine("Token(s):");
sb.AppendLine();
foreach (var token in grant.Tokens!)
{
sb.AppendLine($" {token.Role}:");
sb.AppendLine($" {token.Token}");
sb.AppendLine();
}
sb.AppendLine("Scope:");
sb.AppendLine($" {grant.Scope}");
_log.Information(sb.ToString());
}
void onOutcome(Outcome<UserInformation> outcome)
{
if (!outcome)
{
if (!string.IsNullOrWhiteSpace(outcome.Message))
{
_log.Warning(outcome.Message);
}
else if (outcome.Exception is { })
{
_log.Warning(outcome.Exception.Message);
}
else
{
_log.Warning("Could not get user information (no error message available)");
}
return;
}
var sb = new StringBuilder();
sb.AppendLine("SUCCESS!");
var information = outcome.Value!;
foreach (var pair in information.ToDictionary())
{
sb.AppendLine($" {pair.Key} = {pair.Value}");
}
_log.Information(sb.ToString);
}
internal async Task ClearCachedGrantsAsync()
{
var p = _serviceProvider ?? throw new Exception("No service provider!");
await p.GetRequiredService<IAuthorizationCodeGrantService>().ClearCachedGrantsAsync();
await p.GetRequiredService<IClientCredentialsGrantService>().ClearCachedGrantsAsync();
await p.GetRequiredService<IDeviceCodeGrantService>().ClearCachedGrantsAsync();
// todo clear Token Exchange service cached grants
}
internal async Task ClearCachedRefreshTokensAsync()
{
var p = _serviceProvider ?? throw new Exception("No service provider!");
await p.GetRequiredService<IAuthorizationCodeGrantService>().ClearCachedRefreshTokensAsync();
await p.GetRequiredService<IClientCredentialsGrantService>().ClearCachedRefreshTokensAsync();
await p.GetRequiredService<IDeviceCodeGrantService>().ClearCachedRefreshTokensAsync();
// todo clear Token Exchange service refresh tokens
}
public Auth(string[] args)
{
var info = args.BuildTetraPakDesktopHost(ApplicationPlatform.Console, collection =>
{
collection
.AddTetraPakDesktopAuthorization(
GrantType.OIDC,
GrantType.DeviceCode,
GrantType.ClientCredentials,
GrantType.TokenExchange)
.AddTetraPakWebServices()
.AddAppCredentialsDelegate<CustomAppCredentialsDelegate>()
// just a very basic log (abstracted by the ILog interface, you can use something else here, like NLog, SemiLog, Log4Net or whatever)
// .AddSingleton(p => new LogBase(p.GetService<IConfiguration>()).WithConsoleLogging())
.AddMicrosoftLogging(new LogFormatOptions { OmitRank = true, OmitPrefix = true});
});
_serviceProvider = info.ServiceCollection.BuildXpServiceProvider();
_log = _serviceProvider.GetService<ILog>();
}
}
} | 41.692661 | 153 | 0.546265 | [
"MIT"
] | Tetra-Pak-APIs/TetraPak.XP | source/testClients/authClient.console/Auth.cs | 9,091 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public abstract class RoomEntity : MonoBehaviour
{
public Module CurrentModule;
public void Move(Module _moveTo)
{
if (!(CurrentModule is null))
{
CurrentModule.Occupier = null;
}
CurrentModule = _moveTo;
CurrentModule.Occupier = this;
transform.position = _moveTo.transform.position;
}
public UnityEvent<RoomEntity> GetEnterRoomCallback = new UnityEvent<RoomEntity>();
}
| 24.652174 | 86 | 0.677249 | [
"MIT"
] | SherbertLemon64/Telium | Assets/Code/RoomEntity.cs | 567 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _02.Command_Interpreter
{
class Program
{
static void Main(string[] args)
{
List<string> array = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
string inputLine = Console.ReadLine();
while (inputLine != "end")
{
string[] inputParameters = inputLine.Split();
string command = inputParameters[0];
switch (command)
{
case "reverse":
int reverseStart = int.Parse(inputParameters[2]);
int reverseCount = int.Parse(inputParameters[4]);
if (IsValid(array, reverseStart, reverseCount))
{
Reverse(array, reverseStart, reverseCount);
}
else
{
Console.WriteLine("Invalid input parameters.");
}
break;
case "sort":
int sortStart = int.Parse(inputParameters[2]);
int sortCount = int.Parse(inputParameters[4]);
if (IsValid(array, sortStart, sortCount))
{
Sort(array, sortStart, sortCount);
}
else
{
Console.WriteLine("Invalid input parameters.");
}
break;
case "rollLeft":
int rollLeftCount = int.Parse(inputParameters[1]);
if (rollLeftCount >= 0)
{
rollLeft(array, rollLeftCount);
}
else
{
Console.WriteLine("Invalid input parameters.");
}
break;
case "rollRight":
int rollRightCount = int.Parse(inputParameters[1]);
if (rollRightCount >= 0)
{
rollRight(array, rollRightCount);
}
else
{
Console.WriteLine("Invalid input parameters.");
}
break;
default:
break;
}
inputLine = Console.ReadLine();
}
Console.WriteLine($"[{string.Join(", ", array)}]");
}
private static bool IsValid(List<string> array, int start, int count)
{
bool result = start >= 0 && start < array.Count && count >= 0 && (start + count) <= array.Count;
return result;
}
private static void Reverse(List<string> array, int reverseStart, int reverseCount)
{
array.Reverse(reverseStart, reverseCount);
}
private static void Sort(List<string> array, int sortStart, int sortCount)
{
array.Sort(sortStart, sortCount, null);
}
private static void rollLeft(List<string> array, int rollLeftCount)
{
int rotations = rollLeftCount % array.Count;
for (int i = 0; i < rotations; i++)
{
for (int j = 0; j < array.Count - 1; j++)
{
string temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
private static void rollRight(List<string> array, int rollRightCount)
{
int rotations = rollRightCount % array.Count;
for (int i = 0; i < rotations; i++)
{
for (int j = array.Count - 2; j >= 0; j--)
{
string temp = string.Empty;
if (j == 0)
{
temp = array[array.Count - 1];
array[array.Count - 1] = array[j];
array[j] = temp;
}
else
{
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
}
}
| 31.375839 | 121 | 0.388449 | [
"MIT"
] | alex99q/proggraming-fundamentals-exercises | Exam Preparation III/02. Command Interpreter/Program.cs | 4,677 | C# |
/*
Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal.
This Source Code Form is subject to the terms of the Appverse Public License
Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
file, You can obtain one at http://appverse.org/legal/appverse-license/.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the conditions of the AppVerse Public License v2.0
are met.
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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
SHALL THE COPYRIGHT OWNER 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;
using System.Collections.Generic;
using System.Text;
namespace Unity.Core.Storage.Share
{
public abstract class AbstractShare : IShare
{
}
}
| 45.441176 | 84 | 0.739806 | [
"MPL-2.0"
] | Appverse-Archive/appverse-mobile | appverse-core/src/csharp/Unity/Core/Storage/Share/AbstractShare.cs | 1,551 | C# |
using MdbTask.Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
namespace MdbTask.Data.Context
{
public static class ModelBuilderExtensions
{
/// <summary>
/// Seed DB data
/// </summary>
/// <param name="modelBuilder"></param>
public static void Seed(this ModelBuilder modelBuilder)
{
#region cast
modelBuilder.Entity<Cast>().HasData(
new Cast { CastId = 1, Name = "Tim Robbins" },
new Cast { CastId = 2, Name = "Morgan Freeman" },
new Cast { CastId = 3, Name = "Bob Gunton" },
new Cast { CastId = 4, Name = "William Sadler" },
new Cast { CastId = 5, Name = "Clancy Brown" },
new Cast { CastId = 6, Name = "Uma Thurman" },
new Cast { CastId = 7, Name = "Rebecca Williams" },
new Cast { CastId = 8, Name = "Sally Field" },
new Cast { CastId = 9, Name = "Carrie-Anne Moss" },
new Cast { CastId = 10, Name = "Gloria Foster" }
);
#endregion
#region media
modelBuilder.Entity<Media>().HasData(
new Media {
MediaId = 1,
Type = Enums.MediaType.Movie,
Title = "The Shawshank Redemption",
Image= "76dc4726-424b-4b81-b6f4-f9ffa4bf1734.PNG",
Descritpion = "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
ReleaseDate = new DateTime(1994, 05, 25)
},
new Media
{
MediaId = 2,
Type = Enums.MediaType.Movie,
Title = "The Godfather",
Image = "32ab2181-3042-4737-96e6-6d22d2099346.PNG",
Descritpion = "An organized crime dynasty's aging patriarch transfers control of his clandestine empire to his reluctant son.",
ReleaseDate = new DateTime(1972, 05, 25)
},
new Media
{
MediaId = 3,
Type = Enums.MediaType.Movie,
Title = "The Godfather: Part II",
Image = "7e5bd243-8464-4e66-8209-067d09782b9e.PNG",
Descritpion = "The early life and career of Vito Corleone in 1920s New York City is portrayed, while his son, Michael, expands and tightens his grip on the family crime syndicate.",
ReleaseDate = new DateTime(1974, 05, 25)
},
new Media
{
MediaId = 4,
Type = Enums.MediaType.Movie,
Title = "The Dark Knight",
Image = "acdbb57f-ea31-4796-bcca-19ee0859a95a.PNG",
Descritpion = "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.",
ReleaseDate = new DateTime(2008, 05, 25)
},
new Media
{
MediaId = 5,
Type = Enums.MediaType.Movie,
Title = "12 Angry Men",
Image = "d1b10603-f921-4958-add9-2cf24917e5c7.PNG",
Descritpion = "A jury holdout attempts to prevent a miscarriage of justice by forcing his colleagues to reconsider the evidence.",
ReleaseDate = new DateTime(1957, 05, 25)
},
new Media
{
MediaId = 6,
Type = Enums.MediaType.Movie,
Title = "Schindler's List",
Image = "2675bc9d-b461-4c80-aa58-eeaf1ea4351f.PNG",
Descritpion = "In German-occupied Poland during World War II, industrialist Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.",
ReleaseDate = new DateTime(1993, 05, 25)
},
new Media
{
MediaId = 7,
Type = Enums.MediaType.Movie,
Title = "The Lord of the Rings: The Return of the King",
Image = "18f1125b-6306-48e4-8f9f-263d76018a79.PNG",
Descritpion = "Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.",
ReleaseDate = new DateTime(2003, 05, 25)
},
new Media
{
MediaId = 8,
Type = Enums.MediaType.Movie,
Title = "Pulp Fiction",
Image = "0d7b6135-16d4-4586-b417-6a48e5c7837c.PNG",
Descritpion = "The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.",
ReleaseDate = new DateTime(1994, 05, 25)
},
new Media
{
MediaId = 9,
Type = Enums.MediaType.Movie,
Title = "The Good, the Bad and the Ugly",
Image = "886a7fcd-d44a-410a-bd43-c6499fc4ea3c.PNG",
Descritpion = "A bounty hunting scam joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.",
ReleaseDate = new DateTime(1966, 05, 25)
},
new Media
{
MediaId = 10,
Type = Enums.MediaType.Movie,
Title = "The Lord of the Rings: The Fellowship of the Ring",
Image = "a5394d5f-cf3a-4f4a-a073-33f01537343e.PNG",
Descritpion = "A meek Hobbit from the Shire and eight companions set out on a journey to destroy the powerful One Ring and save Middle-earth from the Dark Lord Sauron.",
ReleaseDate = new DateTime(2001, 05, 25)
},
new Media
{
MediaId = 11,
Type = Enums.MediaType.Movie,
Title = "Fight Club",
Image = "b03ba6df-c0b3-473b-9054-c11b8e72172c.PNG",
Descritpion = "An insomniac office worker and a devil-may-care soap maker form an underground fight club that evolves into much more.",
ReleaseDate = new DateTime(1999, 05, 25)
},
new Media
{
MediaId = 12,
Type = Enums.MediaType.Movie,
Title = "Forrest Gump",
Image = "1c615d7a-4eb2-4df2-961b-ee495d56fcde.PNG",
Descritpion = "The presidencies of Kennedy and Johnson, the Vietnam War, the Watergate scandal and other historical events unfold from the perspective of an Alabama man with an IQ of 75, whose only desire is to be reunited with his childhood sweetheart.",
ReleaseDate = new DateTime(1994, 05, 25)
},
new Media
{
MediaId = 13,
Type = Enums.MediaType.Movie,
Title = "Inception",
Image = "908728fd-3cde-4d75-b0fa-78e9e6eeddb4.PNG",
Descritpion = "A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.",
ReleaseDate = new DateTime(2010, 05, 25)
},
new Media
{
MediaId = 14,
Type = Enums.MediaType.Movie,
Title = "The Lord of the Rings: The Two Towers",
Image = "11fb7a34-bc30-4add-b6e4-ee69fb60e841.PNG",
Descritpion = "While Frodo and Sam edge closer to Mordor with the help of the shifty Gollum, the divided fellowship makes a stand against Sauron's new ally, Saruman, and his hordes of Isengard.",
ReleaseDate = new DateTime(2002, 05, 25)
},
new Media
{
MediaId = 15,
Type = Enums.MediaType.Movie,
Title = "The Matrix",
Image = "ea1cf8c2-cb50-4a3c-8454-b15f1e6b8417.PNG",
Descritpion = "When a beautiful stranger leads computer hacker Neo to a forbidding underworld, he discovers the shocking truth--the life he knows is the elaborate deception of an evil cyber-intelligence.",
ReleaseDate = new DateTime(1999, 05, 25)
},
new Media
{
MediaId = 16,
Type = Enums.MediaType.Movie,
Title = "Goodfellas",
Image = "524d78a2-cbcf-4d35-9700-0dc1e4dd14c1.PNG",
Descritpion = "The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito in the Italian-American crime syndicate.",
ReleaseDate = new DateTime(1990, 05, 25)
},
new Media
{
MediaId = 17,
Type = Enums.MediaType.Movie,
Title = "Seven Samurai",
Image = "35f15079-9c99-4c88-8040-6d4fca4f1fa5.PNG",
Descritpion = "A poor village under attack by bandits recruits seven unemployed samurai to help them defend themselves.",
ReleaseDate = new DateTime(1954, 05, 25)
},
new Media
{
MediaId = 18,
Type = Enums.MediaType.Movie,
Title = "Se7en",
Image = "5ca1d05b-0c72-4686-860b-c6d2cb21ba95.PNG",
Descritpion = "Two detectives, a rookie and a veteran, hunt a serial killer who uses the seven deadly sins as his motives.",
ReleaseDate = new DateTime(1995, 05, 25)
},
new Media
{
MediaId = 19,
Type = Enums.MediaType.Movie,
Title = "The Silence of the Lambs",
Image = "9100a14d-a3d1-4811-976e-575f619d01d4.PNG",
Descritpion = "A young F.B.I. cadet must receive the help of an incarcerated and manipulative cannibal killer to help catch another serial killer, a madman who skins his victims.",
ReleaseDate = new DateTime(1991, 05, 25)
},
new Media
{
MediaId = 20,
Type = Enums.MediaType.Movie,
Title = "City of God",
Image = "27514c79-8c30-477a-8c0a-38e9078f7147.PNG",
Descritpion = "In the slums of Rio, two kids' paths diverge as one struggles to become a photographer and the other a kingpin.",
ReleaseDate = new DateTime(2002, 05, 25)
},
new Media
{
MediaId = 21,
Type = Enums.MediaType.Show,
Title = "Planet Earth II",
Image = "bfd415ff-e78c-4b14-ace6-7bad9ae53f37.PNG",
Descritpion = "Wildlife documentary series with David Attenborough, beginning with a look at the remote islands which offer sanctuary to some of the planet's rarest creatures, to the beauty of cities, which are home to humans, and animals.",
ReleaseDate = new DateTime(2016, 05, 25)
},
new Media
{
MediaId = 22,
Type = Enums.MediaType.Show,
Title = "Planet Earth",
Image = "740d3ede-41c0-43c6-a3cb-7cdb0082a6fa.PNG",
Descritpion = "Emmy Award-winning, 11 episodes, five years in the making, the most expensive nature documentary series ever commissioned by the BBC, and the first to be filmed in high definition.",
ReleaseDate = new DateTime(2006, 05, 25)
},
new Media
{
MediaId = 23,
Type = Enums.MediaType.Show,
Title = "Breaking Bad",
Image = "2fb29410-c0dc-4d46-949c-4a1815d3b50f.PNG",
Descritpion = "A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family's future.",
ReleaseDate = new DateTime(2008, 05, 25)
},
new Media
{
MediaId = 24,
Type = Enums.MediaType.Show,
Title = "Band of Brothers",
Image = "6e7edc1a-bc77-4253-aa96-ed5e91dc42b3.PNG",
Descritpion = "The story of Easy Company of the U.S. Army 101st Airborne Division and their mission in World War II Europe, from Operation Overlord to V-J Day.",
ReleaseDate = new DateTime(2001, 05, 25)
},
new Media
{
MediaId = 25,
Type = Enums.MediaType.Show,
Title = "Chernobyl",
Image = "17513a86-fdc0-4598-bec4-52acd627cc36.PNG",
Descritpion = "In April 1986, an explosion at the Chernobyl nuclear power plant in the Union of Soviet Socialist Republics becomes one of the world's worst man-made catastrophes.",
ReleaseDate = new DateTime(2019, 05, 25)
},
new Media
{
MediaId = 26,
Type = Enums.MediaType.Show,
Title = "The Wire",
Image = "6150136a-4ce7-4c9b-a49e-68ec6c9fe642.PNG",
Descritpion = "The Baltimore drug scene, as seen through the eyes of drug dealers and law enforcement.",
ReleaseDate = new DateTime(2000, 05, 25)
},
new Media
{
MediaId = 27,
Type = Enums.MediaType.Show,
Title = "Avatar: The Last Airbender",
Image = "85dc2dbe-d959-417e-b403-e12a8fe8afb5.PNG",
Descritpion = "In a war-torn world of elemental magic, a young boy reawakens to undertake a dangerous mystic quest to fulfill his destiny as the Avatar, and bring peace to the world.",
ReleaseDate = new DateTime(2005, 05, 25)
},
new Media
{
MediaId = 28,
Type = Enums.MediaType.Show,
Title = "Game of Thrones",
Image = "6fad8c23-c2c8-45b3-8baf-47495dece884.PNG",
Descritpion = "Nine noble families fight for control over the lands of Westeros, while an ancient enemy returns after being dormant for millennia.",
ReleaseDate = new DateTime(2011, 05, 25)
},
new Media
{
MediaId = 29,
Type = Enums.MediaType.Show,
Title = "The Sopranos",
Image = "6562d6af-f04d-4246-8304-2a62c0ac1945.PNG",
Descritpion = "New Jersey mob boss Tony Soprano deals with personal and professional issues in his home and business life that affect his mental state, leading him to seek professional psychiatric counseling.",
ReleaseDate = new DateTime(1999, 05, 25)
},
new Media
{
MediaId = 30,
Type = Enums.MediaType.Show,
Title = "Rick and Morty",
Image = "756a163a-adf9-45e3-bbbf-c00f9aed8b18.PNG",
Descritpion = "An animated series that follows the exploits of a super scientist and his not-so-bright grandson.",
ReleaseDate = new DateTime(2000, 05, 25)
},
new Media
{
MediaId = 31,
Type = Enums.MediaType.Show,
Title = "The World at War",
Image = "b7c5c80e-4e4a-4072-919f-5b2b82aa2d1a.PNG",
Descritpion = "A groundbreaking 26-part documentary series narrated by the actor Laurence Olivier about the deadliest conflict in history, World War II.",
ReleaseDate = new DateTime(1973, 05, 25)
},
new Media
{
MediaId = 32,
Type = Enums.MediaType.Show,
Title = "Sherlock",
Image = "8d758e36-b365-4ab7-8d47-e125b98c165e.PNG",
Descritpion = "A modern update finds the famous sleuth and his doctor partner solving crime in 21st century London.",
ReleaseDate = new DateTime(2010, 05, 25)
},
new Media
{
MediaId = 33,
Type = Enums.MediaType.Show,
Title = "The Twilight Zone",
Image = "23c49b20-e975-4840-86a0-a18a5543faa8.PNG",
Descritpion = "Ordinary people find themselves in extraordinarily astounding situations, which they each try to solve in a remarkable manner.",
ReleaseDate = new DateTime(1959, 05, 25)
},
new Media
{
MediaId = 34,
Type = Enums.MediaType.Show,
Title = "Firefly",
Image = "162c4579-c6b9-4eae-b773-8ae1e6ef69e5.PNG",
Descritpion = "Five hundred years in the future, a renegade crew aboard a small spacecraft tries to survive as they travel the unknown parts of the galaxy and evade warring factions as well as authority agents out to get them.",
ReleaseDate = new DateTime(2002, 05, 25)
},
new Media
{
MediaId = 35,
Type = Enums.MediaType.Show,
Title = "Death Note",
Image = "a8f5c87c-6fad-477a-9a09-4c125ed37f69.PNG",
Descritpion = "An intelligent high school student goes on a secret crusade to eliminate criminals from the world after discovering a notebook capable of killing anyone whose name is written into it.",
ReleaseDate = new DateTime(2006, 05, 25)
},
new Media
{
MediaId = 36,
Type = Enums.MediaType.Show,
Title = "True Detective",
Image = "31121abe-e86f-4843-9baa-711b33928fb4.PNG",
Descritpion = "Seasonal anthology series in which police investigations unearth the personal and professional secrets of those involved, both within and outside the law.",
ReleaseDate = new DateTime(2014, 05, 25)
},
new Media
{
MediaId = 37,
Type = Enums.MediaType.Show,
Title = "Cowboy Bebop",
Image = "c1ad8f44-fc28-4f7d-8c99-59485b74cd06.PNG",
Descritpion = "The futuristic misadventures and tragedies of an easygoing bounty hunter and his partners.",
ReleaseDate = new DateTime(1998, 05, 25)
},
new Media
{
MediaId = 38,
Type = Enums.MediaType.Show,
Title = "The Office",
Image = "f8279730-3905-4497-946d-5377e20ae4be.PNG",
Descritpion = "A mockumentary on a group of typical office workers, where the workday consists of ego clashes, inappropriate behavior, and tedium.",
ReleaseDate = new DateTime(2005, 05, 25)
},
new Media
{
MediaId = 39,
Type = Enums.MediaType.Show,
Title = "Fargo",
Image = "526abfac-a3f1-40a8-b58c-1a8649088182.PNG",
Descritpion = "Various chronicles of deception, intrigue and murder in and around frozen Minnesota. Yet all of these tales mysteriously lead back one way or another to Fargo, North Dakota.",
ReleaseDate = new DateTime(2014, 05, 25)
},
new Media
{
MediaId = 40,
Type = Enums.MediaType.Show,
Title = "Only Fools and Horses",
Image = "d5d7d230-f594-4783-9063-21176004a786.PNG",
Descritpion = "Comedy that follows two brothers from London's rough Peckham estate as they wheel and deal through a number of dodgy deals and search for the big score that'll make them millionaires.",
ReleaseDate = new DateTime(1981, 05, 25)
}
);
#endregion
#region media cast
IList<object> mediaCastData = new List<object>();
Random rnd = new Random();
for (int i = 1; i <= 40; i++)
{
int nmbr = rnd.Next(1, 11);
mediaCastData.Add(new { MediaId = i, CastId = nmbr });
mediaCastData.Add(new { MediaId = i, CastId = nmbr > 1 ? nmbr -1 : nmbr + 1 });
};
modelBuilder.Entity<Media>().HasMany(m => m.Cast).WithMany(m => m.Media).UsingEntity(j => j.HasData(mediaCastData));
#endregion
#region media ratings
IList<Rating> mediaRatingData = new List<Rating>();
for(int i = 1; i <= 25; i++)
{
mediaRatingData.Add(new Rating { RatingId = i, UserRating = rnd.Next(1, 6), MediaId = rnd.Next(1, 41) });
}
modelBuilder.Entity<Rating>().HasData(mediaRatingData);
#endregion
}
}
}
| 53.955189 | 275 | 0.509114 | [
"MIT"
] | zjog/MdbTask | MdbTask/MdbTask.Data/Context/ModelBuilderExtensions.cs | 22,879 | C# |
using System;
using Xunit;
using LeetCode.Impl.Template;
namespace LeetCode.Test.Template;
public class SolutionTests
{
[Theory]
[InlineData(null)]
public void TestSomething(string? value)
{
_ = new Solution();
Assert.Null(value);
}
}
| 16.117647 | 44 | 0.656934 | [
"MIT"
] | gdoct/LeetCodeExcercises | LeetCode.Test/000_Template/Solution.cs | 276 | C# |
using RestSharp;
using GamePriceComparison.Helpers;
using GamePriceComparison.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace GamePriceComparison.Services
{
public class AppStore
{
private const string DefaultLanguage = "en";
private RestClient _client = new RestClient(baseUrl: "https://store.steampowered.com/api");
private ExchangeRateCollection _exchangeRates = ExchangeRateCollection.GetExchangeRates();
public static Currency ParseCurrency(string code)
{
return Enum.GetValues(typeof(Currency))
.OfType<Currency>()
.Single(c => c.GetShortName() == code);
}
public async Task<IEnumerable<App>> GetTopSellersAsync(Country country = Country.UnitedKingdom)
{
var topSellers = new List<App>();
var request = new RestRequest("featuredcategories");
request.AddParameter("cc", country.GetShortName());
request.AddParameter("l", DefaultLanguage);
IRestResponse response = await _client.ExecuteTaskAsync(request);
using (var document = JsonDocument.Parse(response.Content))
{
JsonElement items = document.RootElement.GetProperty("top_sellers").GetProperty("items");
foreach (JsonElement item in items.EnumerateArray())
{
var app = new App
{
Id = item.GetProperty("id").GetInt32(),
EnglishName = item.GetProperty("name").GetString()
};
if (topSellers.Any(a => a.Id == app.Id))
{
// identic top sellers possible
continue;
}
var currencyCode = item.GetProperty("currency").GetString();
var originalPriceCurrency = ParseCurrency(currencyCode);
var finalPrice = item.GetProperty("final_price").GetInt32();
var originalPriceValue = Convert.ToDecimal(finalPrice) / 100;
app.LocalPrice = new Price
{
Currency = originalPriceCurrency,
Value = originalPriceValue
};
topSellers.Add(app);
}
}
await UpdateAsync(topSellers, country);
return topSellers;
}
public async Task UpdateAsync(IEnumerable<App> apps, Country baseCountry)
{
IEnumerable<int> appIds = apps.Select(a => a.Id);
var appIdsString = string.Join(',', appIds);
var remainingCountries = Enum.GetValues(typeof(Country))
.OfType<Country>()
.Where(c => c != baseCountry);
foreach (Country country in remainingCountries)
{
var request = new RestRequest("appdetails");
request.AddParameter("appids", appIdsString);
request.AddParameter("filters", "price_overview");
request.AddParameter("cc", country.GetShortName());
request.AddParameter("l", "en");
IRestResponse response = await _client.ExecuteTaskAsync(request);
using (var document = JsonDocument.Parse(response.Content))
{
foreach (var item in document.RootElement.EnumerateObject())
{
if (item.Value.GetProperty("success").GetBoolean())
{
int id = int.Parse(item.Name);
App app = apps.Single(a => a.Id == id);
JsonElement priceOverview = item.Value.GetProperty("data").GetProperty("price_overview");
var currencyCode = priceOverview.GetProperty("currency").GetString();
var originalPriceCurrency = ParseCurrency(currencyCode);
var finalPrice = priceOverview.GetProperty("final").GetInt32();
var originalPriceValue = Convert.ToDecimal(finalPrice) / 100;
var exchangeRate = _exchangeRates[originalPriceCurrency];
var basePriceValue = originalPriceValue / exchangeRate;
var price = new LocalizedPrice
{
OriginalPrice = new Price
{
Currency = originalPriceCurrency,
Value = originalPriceValue
},
BasePrice = new Price
{
Currency = Currency.PoundSterling,
Value = basePriceValue
}
};
app.LocalizedPrices.Add(country, price);
}
}
}
}
}
}
}
| 39.470149 | 117 | 0.503687 | [
"MIT"
] | 235u/proposals | GamePriceComparison/src/GamePriceComparison/Services/AppStore.cs | 5,291 | C# |
namespace Microsoft.ApplicationInsights.Wcf.Tests
{
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.ApplicationInsights.DataContracts;
public class MockOperationContext : IOperationContext, IOperationContextState
{
private Dictionary<string, object> stateDictionary;
public MockOperationContext()
{
this.IncomingProperties = new Dictionary<string, object>();
this.IncomingHeaders = new Dictionary<string, object>();
this.OutgoingProperties = new Dictionary<string, object>();
this.ContractName = "IFakeService";
this.ContractNamespace = "urn:fake";
this.Request = new RequestTelemetry();
this.Request.GenerateOperationId();
this.OwnsRequest = true;
this.stateDictionary = new Dictionary<string, object>();
}
public IDictionary<string, object> IncomingProperties { get; private set; }
public IDictionary<string, object> OutgoingProperties { get; private set; }
public IDictionary<string, object> IncomingHeaders { get; private set; }
public string OperationId
{
get { return this.Request.Id; }
}
public RequestTelemetry Request { get; private set; }
public bool OwnsRequest { get; private set; }
public Uri EndpointUri { get; set; }
public Uri ToHeader { get; set; }
public string OperationName { get; set; }
public string SoapAction { get; set; }
public string ContractName { get; set; }
public string ContractNamespace { get; set; }
public ServiceSecurityContext SecurityContext { get; set; }
public bool HasIncomingMessageProperty(string propertyName)
{
return this.IncomingProperties.ContainsKey(propertyName);
}
public object GetIncomingMessageProperty(string propertyName)
{
return this.IncomingProperties[propertyName];
}
public bool HasOutgoingMessageProperty(string propertyName)
{
return this.OutgoingProperties.ContainsKey(propertyName);
}
public object GetOutgoingMessageProperty(string propertyName)
{
return this.OutgoingProperties[propertyName];
}
public T GetIncomingMessageHeader<T>(string name, string ns)
{
object value;
if (this.IncomingHeaders.TryGetValue(ns + "#" + name, out value))
{
return (T)value;
}
return default(T);
}
public void AddIncomingMessageHeader<T>(string name, string ns, T value)
{
this.IncomingHeaders.Add(ns + "#" + name, value);
}
public void SetHttpHeaders(HttpRequestMessageProperty httpHeaders)
{
this.IncomingProperties[HttpRequestMessageProperty.Name] = httpHeaders;
}
public void SetState(string key, object value)
{
this.stateDictionary.Add(key, value);
}
public bool TryGetState<T>(string key, out T value)
{
value = default(T);
object obj = null;
if (this.stateDictionary.TryGetValue(key, out obj))
{
value = (T)obj;
return true;
}
return false;
}
}
} | 30.640351 | 83 | 0.606356 | [
"MIT"
] | Bhaskers-Blu-Org2/ApplicationInsights-SDK-Labs | WCF/Shared.Tests/MockOperationContext.cs | 3,495 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BMI.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BMI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.375 | 169 | 0.600796 | [
"MIT"
] | justin-harper/cs122 | Lab9/BMI/BMI/Properties/Resources.Designer.cs | 2,765 | C# |
// Copyright 2016 Xamarin Inc. All rights reserved.
using System;
#if XAMCORE_2_0
using Foundation;
#else
using MonoTouch.Foundation;
#endif
using NUnit.Framework;
namespace Linker.Sealer {
[Preserve (AllMembers = true)]
public class Unsealable {
public virtual bool A () { return true; }
public virtual bool B () { return false; }
}
[Preserve (AllMembers = true)]
public class Sealable : Unsealable {
public override bool B () { return true; }
public virtual bool C () { return false; }
}
interface Interface {
bool A ();
}
[Preserve (AllMembers = true)]
public class Base {
public bool A () { return true; }
}
[Preserve (AllMembers = true)]
public class Subclass : Base, Interface {
}
[TestFixture]
[Preserve (AllMembers = true)]
public class SealerTest {
[Test]
public void Sealed ()
{
// this can not be optimized into a sealed type
Assert.False (typeof (Unsealable).IsSealed, "Unsealed");
#if DEBUG
// this is not a sealed type (in the source)
Assert.False (typeof (Sealable).IsSealed, "Sealable");
Assert.False (typeof (Base).IsSealed, "Base");
Assert.False (typeof (Subclass).IsSealed, "Subclass");
Assert.False (typeof (Interface).IsSealed, "Interface");
#else
// Sealable can be optimized / sealed as nothing else is (or can) subclass it
Assert.True (typeof (Sealable).IsSealed, "Sealable");
// Base is subclassed so it can't be sealed
Assert.False (typeof (Base).IsSealed, "Base");
// Subclass is not subclassed anymore and can be sealed
Assert.True (typeof (Subclass).IsSealed, "Subclass");
// interface can not be sealed
Assert.False (typeof (Interface).IsSealed, "Interface");
#endif
}
[Test]
public void Final ()
{
var t = typeof (Sealable);
var a = t.GetMethod ("A");
var b = t.GetMethod ("B");
var c = t.GetMethod ("C");
#if DEBUG
// this is not a sealed (C#) method (in the source)
Assert.False (a.IsFinal, "A");
Assert.False (b.IsFinal, "B");
Assert.False (c.IsFinal, "C");
#else
// but it can be optimized / sealed as nothing else is (or can) overrides it
Assert.True (a.IsFinal, "A");
Assert.True (b.IsFinal, "B");
Assert.True (c.IsFinal, "C");
#endif
}
[Test]
public void Virtual ()
{
var t = typeof (Sealable);
var a = t.GetMethod ("A");
var b = t.GetMethod ("B");
var c = t.GetMethod ("C");
#if DEBUG
// both methods are virtual (both in C# and IL)
Assert.True (a.IsVirtual, "A");
Assert.True (b.IsVirtual, "B");
Assert.True (c.IsVirtual, "C");
#else
// calling A needs dispatch to base type Unsealable
Assert.True (a.IsVirtual, "A");
// B is an override and must remain virtual
Assert.True (b.IsVirtual, "B");
// C has no special requirement and can be de-virtualized
Assert.False (c.IsVirtual, "C");
#endif
}
[Test]
public void Interface ()
{
var t = typeof (Subclass);
var a = t.GetMethod ("A");
// A cannot be de-virtualized since Concrete must satisfy Interface thru Base
Assert.True (a.IsVirtual, "A");
}
}
}
| 25.838983 | 80 | 0.653001 | [
"BSD-3-Clause"
] | 1975781737/xamarin-macios | tests/linker/ios/link all/SealerTest.cs | 3,051 | C# |
using System;
namespace DShop.Monolith.Core.Domain.Products.Events
{
public class ProductUpdated : IEvent
{
public Guid Id { get; }
public string Name { get; }
public string Description { get; }
public string Vendor { get; }
public decimal Price { get; }
public ProductUpdated(Guid id, string name, string description,
string vendor, decimal price)
{
Id = id;
Name = name;
Description = description;
Vendor = vendor;
Price = price;
}
}
}
| 24.583333 | 72 | 0.547458 | [
"MIT"
] | devmentors/DNC-DShop.Monolith | src/DShop.Monolith.Core/Domain/Products/Events/ProductUpdated.cs | 592 | C# |
/*******************************************************************************
* Copyright (C) Git Corporation. All rights reserved.
*
* Author: 情缘
* Create Date: 2016-03-16 22:06:50
*
* Description: Git.Framework
* http://www.cnblogs.com/qingyuan/
* Revision History:
* Date Author Description
* 2016-03-16 22:06:50 情缘
*********************************************************************************/
using Git.Framework.Cache;
using Git.Framework.Log;
using Git.Framework.ORM;
using Git.Storage.Common.Enum;
using Git.Storage.Entity.Storage;
using Git.Framework.DataTypes;
using Git.Framework.DataTypes.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Git.Storage.Provider.Sys
{
public partial class SupplierProvider : DataFactory
{
public SupplierProvider(string _CompanyID)
{
this.CompanyID = _CompanyID;
}
/// <summary>
/// 获得所有供应商信息
/// </summary>
/// <param name="entity"></param>
/// <param name="pageInfo"></param>
/// <returns></returns>
public List<SupplierEntity> GetList()
{
string key = string.Format(CacheKey.JOOSHOW_SUPPLIER_CACHE,this.CompanyID);
List<SupplierEntity> listResult = CacheHelper.Get(key) as List<SupplierEntity>;
if (!listResult.IsNullOrEmpty())
{
return listResult;
}
SupplierEntity entity = new SupplierEntity();
entity.IncludeAll();
entity.OrderBy(a => a.ID, EOrderBy.DESC);
entity.Where(a => a.IsDelete == (int)EIsDelete.NotDelete)
.And(a=>a.CompanyID==this.CompanyID);
listResult = this.Supplier.GetList(entity);
if (!listResult.IsNullOrEmpty())
{
CacheHelper.Insert(key, listResult);
}
return listResult;
}
/// <summary>
/// 获得所有供应商信息
/// </summary>
/// <param name="entity"></param>
/// <param name="pageInfo"></param>
/// <returns></returns>
public List<SupplierEntity> GetList(SupplierEntity entity, ref PageInfo pageInfo)
{
entity.IncludeAll();
entity.OrderBy(a => a.ID, EOrderBy.DESC);
entity.Where(a => a.IsDelete == (int)EIsDelete.NotDelete)
.And(a=>a.CompanyID==this.CompanyID);
if (!entity.SupName.IsEmpty())
{
entity.And("SupName", ECondition.Like, "%"+entity.SupName+"%");
}
if (!entity.SupNum.IsEmpty())
{
entity.And("SupNum", ECondition.Like, "%" + entity.SupNum + "%");
}
if (entity.SupType > 0)
{
entity.And(a => a.SupType == entity.SupType);
}
if (!entity.Phone.IsEmpty())
{
entity.And("Phone",ECondition.Like,"%"+entity.Phone+"%");
}
int rowCount = 0;
List<SupplierEntity> listResult = this.Supplier.GetList(entity, pageInfo.PageSize, pageInfo.PageIndex, out rowCount);
pageInfo.RowCount = rowCount;
return listResult;
}
/// <summary>
/// 添加供应商
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Add(SupplierEntity entity)
{
string key = string.Format(CacheKey.JOOSHOW_SUPPLIER_CACHE, this.CompanyID);
entity.IsDelete = (int)EIsDelete.NotDelete;
entity.CreateTime = DateTime.Now;
entity.SupNum = entity.SupNum.IsEmpty() ? new TNumProvider(this.CompanyID).GetSwiftNum(typeof(SupplierEntity),5) : entity.SupNum;
entity.SnNum = entity.SnNum.IsEmpty() ? ConvertHelper.NewGuid() : entity.SnNum;
entity.IncludeAll();
int line = this.Supplier.Add(entity);
if (line > 0)
{
CacheHelper.Remove(key);
}
return line;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="userCode"></param>
/// <returns></returns>
public int Delete(IEnumerable<string> list)
{
string key = string.Format(CacheKey.JOOSHOW_SUPPLIER_CACHE, this.CompanyID);
SupplierEntity entity = new SupplierEntity();
entity.IsDelete = (int)EIsDelete.Deleted;
entity.IncludeIsDelete(true);
entity.Where("SnNum",ECondition.In,list.ToArray());
entity.And(a=>a.CompanyID==this.CompanyID);
int line = this.Supplier.Update(entity);
if (line > 0)
{
CacheHelper.Remove(key);
}
return line;
}
/// <summary>
/// 根据供应商编号获得供应商信息
/// </summary>
/// <param name="userCode"></param>
/// <returns></returns>
public SupplierEntity GetSupplier(string SnNum)
{
List<SupplierEntity> listSource = GetList();
if (listSource.IsNullOrEmpty())
{
return null;
}
SupplierEntity entity = listSource.SingleOrDefault(item => item.SnNum == SnNum);
return entity;
}
/// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public int Update(SupplierEntity entity)
{
string key = string.Format(CacheKey.JOOSHOW_SUPPLIER_CACHE, this.CompanyID);
entity.Include(a => new { a.SupNum, a.SupName, a.SupType, a.Email, a.Phone, a.Fax, a.ContactName, a.Address, a.Description });
entity.Where(a => a.SnNum == entity.SnNum)
.And(a=>a.CompanyID==entity.CompanyID);
int line = this.Supplier.Update(entity);
if (line > 0)
{
CacheHelper.Remove(key);
}
return line;
}
/// <summary>
/// 供应商搜索关键字
/// </summary>
/// <param name="Keyword"></param>
/// <param name="PageSize"></param>
/// <returns></returns>
public List<SupplierEntity> SearchSupplier(string Keyword,int PageSize)
{
List<SupplierEntity> listSource = GetList();
if (listSource.IsNullOrEmpty())
{
return null;
}
List<SupplierEntity> listResult = listSource.Where(item => item.SupNum.Contains(Keyword) || item.SupName.Contains(Keyword) || item.Phone.Contains(Keyword)).Skip(0).Take(PageSize).ToList();
return listResult;
}
}
}
| 34.328283 | 200 | 0.525526 | [
"MIT"
] | colin08/yun_gitwms | Git.WMS.Web/Git.Storage.Provider/Sys/SupplierProvider.cs | 6,905 | C# |
using System;
using Nez.BitmapFonts;
using Microsoft.Xna.Framework;
using System.Text;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
namespace Nez.UI
{
/// <summary>
/// A single-line text input field.
///
/// The preferred height of a text field is the height of the {@link TextFieldStyle#font} and {@link TextFieldStyle#background}.
/// The preferred width of a text field is 150, a relatively arbitrary size.
///
/// The text field will copy the currently selected text when ctrl+c is pressed, and paste any text in the clipboard when ctrl+v is
/// pressed. Clipboard functionality is provided via the {@link Clipboard} interface.
///
/// The text field allows you to specify an {@link OnscreenKeyboard} for displaying a softkeyboard and piping all key events
/// generated by the keyboard to the text field. There are two standard implementations, one for the desktop and one for Android.
/// The desktop keyboard is a stub, as a softkeyboard is not needed on the desktop. The Android {@link OnscreenKeyboard}
/// implementation will bring up the default IME.
/// </summary>
public class TextField : Element, IInputListener, IKeyboardListener
{
public event Action<TextField,string> onTextChanged;
public override float preferredWidth
{
get { return _preferredWidth; }
}
public override float preferredHeight
{
get
{
var prefHeight = textHeight;
if( style.background != null )
prefHeight = Math.Max( prefHeight + style.background.bottomHeight + style.background.topHeight, style.background.minHeight );
return prefHeight;
}
}
/// <summary>
/// the maximum distance outside the TextField the mouse can move when pressing it to cause it to be unfocused
/// </summary>
public float textFieldBoundaryThreshold = 100f;
/// <summary>
/// if true and setText is called it will be ignored
/// </summary>
public bool shouldIgnoreTextUpdatesWhileFocused = true;
protected string text;
protected int cursor, selectionStart;
protected bool hasSelection;
protected bool writeEnters;
List<float> glyphPositions = new List<float>( 15 );
float _preferredWidth = 150;
TextFieldStyle style;
string messageText;
protected string displayText = string.Empty;
ITextFieldFilter filter;
bool focusTraversal = true, onlyFontChars = true, disabled;
int textHAlign = AlignInternal.left;
float selectionX, selectionWidth;
StringBuilder _textBuffer = new StringBuilder();
bool passwordMode;
StringBuilder passwordBuffer;
char passwordCharacter = '*';
protected float fontOffset, textHeight, textOffset;
float renderOffset;
int visibleTextStart, visibleTextEnd;
int maxLength = 0;
float blinkTime = 0.5f;
bool cursorOn = true;
float lastBlink;
bool programmaticChangeEvents;
protected bool _isOver, _isPressed, _isFocused;
ITimer _keyRepeatTimer;
float _keyRepeatTime = 0.2f;
public TextField( string text, TextFieldStyle style )
{
setStyle( style );
setText( text );
setSize( preferredWidth, preferredHeight );
}
public TextField( string text, Skin skin, string styleName = null ) : this( text, skin.get<TextFieldStyle>( styleName ) )
{}
#region IInputListener
float _clickCountInterval = 0.2f;
int _clickCount;
float _lastClickTime;
void IInputListener.onMouseEnter()
{
_isOver = true;
}
void IInputListener.onMouseExit()
{
_isOver = _isPressed = false;
}
bool IInputListener.onMousePressed( Vector2 mousePos )
{
if( disabled )
return false;
_isPressed = true;
setCursorPosition( mousePos.X, mousePos.Y );
selectionStart = cursor;
hasSelection = true;
var stage = getStage();
if( stage != null )
stage.setKeyboardFocus( this as IKeyboardListener );
return true;
}
void IInputListener.onMouseMoved( Vector2 mousePos )
{
if( distanceOutsideBoundsToPoint( mousePos ) > textFieldBoundaryThreshold )
{
_isPressed = _isOver = false;
getStage().removeInputFocusListener( this );
}
else
{
setCursorPosition( mousePos.X, mousePos.Y );
}
}
void IInputListener.onMouseUp( Vector2 mousePos )
{
if( selectionStart == cursor )
hasSelection = false;
if( Time.time - _lastClickTime > _clickCountInterval )
_clickCount = 0;
_clickCount++;
_lastClickTime = Time.time;
_isPressed = _isOver = false;
}
bool IInputListener.onMouseScrolled( int mouseWheelDelta )
{
return false;
}
#endregion
#region IKeyboardListener
void IKeyboardListener.keyDown( Keys key )
{
if( disabled )
return;
lastBlink = 0;
cursorOn = false;
var isCtrlDown = InputUtils.isControlDown();
var jump = isCtrlDown && !passwordMode;
var repeat = false;
if( isCtrlDown )
{
if( key == Keys.V )
{
paste( Clipboard.getContents(), true );
}
else if( key == Keys.C || key == Keys.Insert )
{
copy();
return;
}
else if( key == Keys.X )
{
cut( true );
return;
}
else if( key == Keys.A )
{
selectAll();
return;
}
}
if( InputUtils.isShiftDown() )
{
if( key == Keys.Insert )
paste( Clipboard.getContents(), true );
else if( key == Keys.Delete )
cut( true );
// jumping around shortcuts
var temp = cursor;
var foundJumpKey = true;
if( key == Keys.Left )
{
moveCursor( false, jump );
repeat = true;
}
else if( key == Keys.Right )
{
moveCursor( true, jump );
repeat = true;
}
else if( key == Keys.Home )
{
goHome();
}
else if( key == Keys.End )
{
goEnd();
}
else
{
foundJumpKey = false;
}
if( foundJumpKey && !hasSelection )
{
selectionStart = temp;
hasSelection = true;
}
}
else
{
// Cursor movement or other keys (kills selection)
if( key == Keys.Left )
{
moveCursor( false, jump );
clearSelection();
repeat = true;
}
else if( key == Keys.Right )
{
moveCursor( true, jump );
clearSelection();
repeat = true;
}
else if( key == Keys.Home )
{
goHome();
}
else if( key == Keys.End )
{
goEnd();
}
}
cursor = Mathf.clamp( cursor, 0, text.Length );
if( repeat )
{
if( _keyRepeatTimer != null )
_keyRepeatTimer.stop();
_keyRepeatTimer = Core.schedule( _keyRepeatTime, true, this, t => ( t.context as IKeyboardListener ).keyDown( key ) );
}
}
void IKeyboardListener.keyPressed( Keys key, char character )
{
if( InputUtils.isControlDown() )
return;
// disallow typing most ASCII control characters, which would show up as a space
switch ( key )
{
case Keys.Back:
case Keys.Delete:
case Keys.Tab:
case Keys.Enter:
break;
default:
{
if( (int)character < 32 )
return;
break;
}
}
if( key == Keys.Tab && focusTraversal )
{
next( InputUtils.isShiftDown() );
}
else
{
var enterPressed = key == Keys.Enter;
var backspacePressed = key == Keys.Back;
var deletePressed = key == Keys.Delete;
var add = enterPressed ? writeEnters : ( !onlyFontChars || style.font.hasCharacter( character ) );
var remove = backspacePressed || deletePressed;
if( add || remove )
{
var oldText = text;
if( hasSelection )
{
cursor = delete( false );
}
else
{
if( backspacePressed && cursor > 0 )
{
text = text.Substring( 0, cursor - 1 ) + text.Substring( cursor-- );
renderOffset = 0;
}
if( deletePressed && cursor < text.Length )
{
text = text.Substring( 0, cursor ) + text.Substring( cursor + 1 );
}
}
if( add && !remove )
{
// character may be added to the text.
if( !enterPressed && filter != null && !filter.acceptChar( this, character ) )
return;
if( !withinMaxLength( text.Length ) )
return;
var insertion = enterPressed ? "\n" : character.ToString();
text = insert( cursor++, insertion, text );
}
changeText( oldText, text );
updateDisplayText();
}
}
}
void IKeyboardListener.keyReleased( Keys key )
{
if( _keyRepeatTimer != null )
{
_keyRepeatTimer.stop();
_keyRepeatTimer = null;
}
}
void IKeyboardListener.gainedFocus()
{
hasSelection = _isFocused = true;
}
void IKeyboardListener.lostFocus()
{
hasSelection = _isFocused = false;
if( _keyRepeatTimer != null )
{
_keyRepeatTimer.stop();
_keyRepeatTimer = null;
}
}
#endregion
protected int letterUnderCursor( float x )
{
var halfSpaceSize = style.font.spaceWidth;
x -= textOffset + fontOffset + halfSpaceSize /*- style.font.getData().cursorX*/ - glyphPositions[visibleTextStart];
var n = glyphPositions.Count;
for( var i = 0; i < n; i++ )
{
if( glyphPositions[i] > x && i >= 1 )
{
if( glyphPositions[i] - x <= x - glyphPositions[i - 1] )
return i;
return i - 1;
}
}
return n - 1;
}
protected bool isWordCharacter( char c )
{
return ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ) || ( c >= '0' && c <= '9' );
}
protected int[] wordUnderCursor( int at )
{
int start = at, right = text.Length, left = 0, index = start;
for(; index < right; index++ )
{
if( !isWordCharacter( text[index] ) )
{
right = index;
break;
}
}
for( index = start - 1; index > -1; index-- )
{
if( !isWordCharacter( text[index] ) )
{
left = index + 1;
break;
}
}
return new int[] { left, right };
}
int[] wordUnderCursor( float x )
{
return wordUnderCursor( letterUnderCursor( x ) );
}
bool withinMaxLength( int size )
{
return maxLength <= 0 || size < maxLength;
}
public TextField setMaxLength( int maxLength )
{
this.maxLength = maxLength;
return this;
}
public int getMaxLength()
{
return this.maxLength;
}
/// <summary>
/// When false, text set by {@link #setText(String)} may contain characters not in the font, a space will be displayed instead.
/// When true (the default), characters not in the font are stripped by setText. Characters not in the font are always stripped
/// when typed or pasted.
/// </summary>
/// <param name="onlyFontChars">If set to <c>true</c> only font chars.</param>
public TextField setOnlyFontChars( bool onlyFontChars )
{
this.onlyFontChars = onlyFontChars;
return this;
}
public TextField setStyle( TextFieldStyle style )
{
this.style = style;
textHeight = style.font.lineHeight;
invalidateHierarchy();
return this;
}
/// <summary>
/// Returns the text field's style. Modifying the returned style may not have an effect until {@link #setStyle(TextFieldStyle)} is called
/// </summary>
/// <returns>The style.</returns>
public TextFieldStyle getStyle()
{
return style;
}
protected void calculateOffsets()
{
float visibleWidth = getWidth();
if( style.background != null )
visibleWidth -= style.background.leftWidth + style.background.rightWidth;
var glyphCount = glyphPositions.Count;
// Check if the cursor has gone out the left or right side of the visible area and adjust renderoffset.
var distance = glyphPositions[Math.Max( 0, cursor - 1 )] + renderOffset;
if( distance <= 0 )
{
renderOffset -= distance;
}
else
{
var index = Math.Min( glyphCount - 1, cursor + 1 );
var minX = glyphPositions[index] - visibleWidth;
if( -renderOffset < minX )
{
renderOffset = -minX;
}
}
// calculate first visible char based on render offset
visibleTextStart = 0;
var startX = 0f;
for( var i = 0; i < glyphCount; i++ )
{
if( glyphPositions[i] >= -renderOffset )
{
visibleTextStart = Math.Max( 0, i );
startX = glyphPositions[i];
break;
}
}
// calculate last visible char based on visible width and render offset
var length = displayText.Length;
visibleTextEnd = Math.Min( length, cursor + 1 );
for(; visibleTextEnd <= length; visibleTextEnd++ )
if( glyphPositions[visibleTextEnd] > startX + visibleWidth )
break;
visibleTextEnd = Math.Max( 0, visibleTextEnd - 1 );
if( ( textHAlign & AlignInternal.left ) == 0 )
{
textOffset = visibleWidth - ( glyphPositions[visibleTextEnd] - startX );
if( ( textHAlign & AlignInternal.center ) != 0 )
textOffset = Mathf.round( textOffset * 0.5f );
}
else
{
textOffset = startX + renderOffset;
}
// calculate selection x position and width
if( hasSelection )
{
var minIndex = Math.Min( cursor, selectionStart );
var maxIndex = Math.Max( cursor, selectionStart );
var minX = Math.Max( glyphPositions[minIndex], -renderOffset );
var maxX = Math.Min( glyphPositions[maxIndex], visibleWidth - renderOffset );
selectionX = minX;
if( renderOffset == 0 )
selectionX += textOffset;
selectionWidth = maxX - minX;
}
}
#region Drawing
public override void draw( Graphics graphics, float parentAlpha )
{
var font = style.font;
var fontColor = ( disabled && style.disabledFontColor.HasValue ) ? style.disabledFontColor.Value
: ( ( _isFocused && style.focusedFontColor.HasValue ) ? style.focusedFontColor.Value : style.fontColor );
IDrawable selection = style.selection;
IDrawable background = ( disabled && style.disabledBackground != null ) ? style.disabledBackground
: ( ( _isFocused && style.focusedBackground != null ) ? style.focusedBackground : style.background );
var color = getColor();
var x = getX();
var y = getY();
var width = getWidth();
var height = getHeight();
float bgLeftWidth = 0, bgRightWidth = 0;
if( background != null )
{
background.draw( graphics, x, y, width, height, new Color( color, (int)(color.A * parentAlpha) ) );
bgLeftWidth = background.leftWidth;
bgRightWidth = background.rightWidth;
}
var textY = getTextY( font, background );
var yOffset = (textY < 0) ? -textY - font.lineHeight/2f + getHeight() / 2 : 0;
calculateOffsets();
if( _isFocused && hasSelection && selection != null )
drawSelection( selection, graphics, font, x + bgLeftWidth, y + textY + yOffset );
if( displayText.Length == 0 )
{
if( !_isFocused && messageText != null )
{
var messageFontColor = style.messageFontColor.HasValue ? style.messageFontColor.Value : new Color( 180, 180, 180, (int)(color.A * parentAlpha) );
var messageFont = style.messageFont != null ? style.messageFont : font;
graphics.batcher.drawString( messageFont, messageText, new Vector2( x + bgLeftWidth, y + textY + yOffset ), messageFontColor );
//messageFont.draw( graphics.batcher, messageText, x + bgLeftWidth, y + textY + yOffset, 0, messageText.length(),
// width - bgLeftWidth - bgRightWidth, textHAlign, false, "..." );
}
}
else
{
var col = new Color( fontColor, (int)(fontColor.A * parentAlpha / 255.0f) );
var t = displayText.Substring( visibleTextStart, visibleTextEnd - visibleTextStart );
graphics.batcher.drawString( font, t, new Vector2( x + bgLeftWidth + textOffset, y + textY + yOffset ), col );
}
if( _isFocused && !disabled )
{
blink();
if( cursorOn && style.cursor != null )
drawCursor( style.cursor, graphics, font, x + bgLeftWidth, y + textY + yOffset );
}
}
protected float getTextY( BitmapFont font, IDrawable background )
{
float height = getHeight();
float textY = textHeight / 2 + font.descent;
if( background != null )
{
var bottom = background.bottomHeight;
textY = textY - ( height - background.topHeight - bottom ) / 2 + bottom;
}
else
{
textY = textY - height / 2;
}
return textY;
}
/// <summary>
/// Draws selection rectangle
/// </summary>
/// <param name="selection">Selection.</param>
/// <param name="batch">Batch.</param>
/// <param name="font">Font.</param>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
protected void drawSelection( IDrawable selection, Graphics graphics, BitmapFont font, float x, float y )
{
selection.draw( graphics, x + selectionX + renderOffset + fontOffset, y - font.descent / 2, selectionWidth, textHeight, Color.White );
}
protected void drawCursor( IDrawable cursorPatch, Graphics graphics, BitmapFont font, float x, float y )
{
cursorPatch.draw( graphics,
x + textOffset + glyphPositions[cursor] - glyphPositions[visibleTextStart] + fontOffset - 1 /*font.getData().cursorX*/,
y - font.descent / 2, cursorPatch.minWidth, textHeight, color );
}
#endregion
void updateDisplayText()
{
var textLength = text.Length;
_textBuffer.Clear();
for( var i = 0; i < textLength; i++ )
{
var c = text[i];
_textBuffer.Append( style.font.hasCharacter( c ) ? c : ' ' );
}
var newDisplayText = _textBuffer.ToString();
if( passwordMode && style.font.hasCharacter( passwordCharacter ) )
{
if( passwordBuffer == null )
passwordBuffer = new StringBuilder( newDisplayText.Length );
else if( passwordBuffer.Length > textLength )
passwordBuffer.Clear();
for( var i = passwordBuffer.Length; i < textLength; i++ )
passwordBuffer.Append( passwordCharacter );
displayText = passwordBuffer.ToString();
}
else
{
displayText = newDisplayText;
}
//layout.setText( font, displayText );
glyphPositions.Clear();
float x = 0;
if( displayText.Length > 0 )
{
for( var i = 0; i < displayText.Length; i++ )
{
var region = style.font.fontRegionForChar( displayText[i] );
// we dont have fontOffset in BitmapFont, it is the first Glyph in a GlyphRun
//if( i == 0 )
// fontOffset = region.xAdvance;
glyphPositions.Add( x );
x += region.xAdvance;
}
//GlyphRun run = layout.runs.first();
//FloatArray xAdvances = run.xAdvances;
//fontOffset = xAdvances.first();
//for( int i = 1, n = xAdvances.size; i < n; i++ )
//{
// glyphPositions.add( x );
// x += xAdvances.get( i );
//}
}
else
{
fontOffset = 0;
}
glyphPositions.Add( x );
if( selectionStart > newDisplayText.Length )
selectionStart = textLength;
}
void blink()
{
if( ( Time.time - lastBlink ) > blinkTime )
{
cursorOn = !cursorOn;
lastBlink = Time.time;
}
}
#region Text manipulation
/// <summary>
/// Copies the contents of this TextField to the {@link Clipboard} implementation set on this TextField
/// </summary>
public void copy()
{
if( hasSelection && !passwordMode )
{
var start = Math.Min( cursor, selectionStart );
var length = Math.Max( cursor, selectionStart ) - start;
Clipboard.setContents( text.Substring( start, length ) );
}
}
/// <summary>
/// Copies the selected contents of this TextField to the {@link Clipboard} implementation set on this TextField, then removes it
/// </summary>
public void cut()
{
cut( programmaticChangeEvents );
}
void cut( bool fireChangeEvent )
{
if( hasSelection && !passwordMode )
{
copy();
cursor = delete( fireChangeEvent );
updateDisplayText();
}
}
void paste( string content, bool fireChangeEvent )
{
if( content == null )
return;
_textBuffer.Clear();
int textLength = text.Length;
if( hasSelection )
textLength -= Math.Abs( cursor - selectionStart );
//var data = style.font.getData();
for( int i = 0, n = content.Length; i < n; i++ )
{
if( !withinMaxLength( textLength + _textBuffer.Length ) )
break;
var c = content[i];
if( !( writeEnters && c == '\r' ) )
{
if( onlyFontChars && !style.font.hasCharacter( c ) )
continue;
if( filter != null && !filter.acceptChar( this, c ) )
continue;
}
_textBuffer.Append( c );
}
content = _textBuffer.ToString();
if( hasSelection )
cursor = delete( fireChangeEvent );
if( fireChangeEvent )
changeText( text, insert( cursor, content, text ) );
else
text = insert( cursor, content, text );
updateDisplayText();
cursor += content.Length;
}
string insert( int position, string text, string to )
{
if( to.Length == 0 )
return text;
return to.Substring( 0, position ) + text + to.Substring( position, to.Length - position );
}
int delete( bool fireChangeEvent )
{
var from = selectionStart;
var to = cursor;
var minIndex = Math.Min( from, to );
var maxIndex = Math.Max( from, to );
var newText = ( minIndex > 0 ? text.Substring( 0, minIndex ) : "" )
+ ( maxIndex < text.Length ? text.Substring( maxIndex, text.Length - maxIndex ) : "" );
if( fireChangeEvent )
changeText( text, newText );
else
text = newText;
clearSelection();
return minIndex;
}
/// <summary>
/// Focuses the next TextField. If none is found, the keyboard is hidden. Does nothing if the text field is not in a stage
/// up: If true, the TextField with the same or next smallest y coordinate is found, else the next highest.
/// </summary>
/// <param name="up">Up.</param>
public void next( bool up )
{
var stage = getStage();
if( stage == null )
return;
var tmp2 = Vector2.Zero;
var tmp1 = getParent().localToStageCoordinates( new Vector2( getX(), getY() ) );
var textField = findNextTextField( stage.getElements(), null, tmp2, tmp1, up );
if( textField == null )
{
// Try to wrap around.
if( up )
tmp1 = new Vector2( float.MinValue, float.MinValue );
else
tmp1 = new Vector2( float.MaxValue, float.MaxValue );
textField = findNextTextField( getStage().getElements(), null, tmp2, tmp1, up );
}
if( textField != null )
stage.setKeyboardFocus( textField );
}
TextField findNextTextField( List<Element> elements, TextField best, Vector2 bestCoords, Vector2 currentCoords, bool up )
{
bestCoords = Vector2.Zero;
for( int i = 0, n = elements.Count; i < n; i++ )
{
var element = elements[i];
if( element == this )
continue;
if( element is TextField )
{
var textField = (TextField)element;
if( textField.isDisabled() || !textField.focusTraversal )
continue;
var elementCoords = element.getParent().localToStageCoordinates( new Vector2( element.getX(), element.getY() ) );
if( ( elementCoords.Y < currentCoords.Y || ( elementCoords.Y == currentCoords.Y && elementCoords.X > currentCoords.X ) ) ^ up )
{
if( best == null
|| ( elementCoords.Y > bestCoords.Y || ( elementCoords.Y == bestCoords.Y && elementCoords.X < bestCoords.X ) ) ^ up )
{
best = (TextField)element;
bestCoords = elementCoords;
}
}
}
else if( element is Group )
{
best = findNextTextField( ( (Group)element ).getChildren(), best, bestCoords, currentCoords, up );
}
}
return best;
}
#endregion
/// <summary>
/// if str is null, "" is used
/// </summary>
/// <param name="str">String.</param>
public void appendText( string str )
{
if( shouldIgnoreTextUpdatesWhileFocused && _isFocused )
return;
if( str == null )
str = "";
clearSelection();
cursor = text.Length;
paste( str, programmaticChangeEvents );
}
/// <summary>
/// str If null, "" is used
/// </summary>
/// <param name="str">String.</param>
public TextField setText( string str )
{
if( shouldIgnoreTextUpdatesWhileFocused && _isFocused )
return this;
if( str == null )
str = "";
if( str == text )
return this;
clearSelection();
var oldText = text;
text = "";
paste( str, false );
if( programmaticChangeEvents )
changeText( oldText, text );
cursor = 0;
return this;
}
/// <summary>
/// force sets the text without validating or firing change events. Use at your own risk.
/// </summary>
/// <param name="str">String.</param>
public TextField setTextForced( string str )
{
text = str;
updateDisplayText();
// ensure our cursor is in bounds
cursor = text.Length;
return this;
}
/// <summary>
/// Never null, might be an empty string
/// </summary>
/// <returns>The text.</returns>
public string getText()
{
return text;
}
/// <summary>
/// oldText May be null
/// </summary>
/// <param name="oldText">Old text.</param>
/// <param name="newText">New text.</param>
void changeText( string oldText, string newText )
{
if( newText == oldText )
return;
text = newText;
if( onTextChanged != null )
onTextChanged( this, text );
}
/// <summary>
/// If false, methods that change the text will not fire {@link onTextChanged}, the event will be fired only when user changes the text
/// </summary>
/// <param name="programmaticChangeEvents">If set to <c>true</c> programmatic change events.</param>
public TextField setProgrammaticChangeEvents( bool programmaticChangeEvents )
{
this.programmaticChangeEvents = programmaticChangeEvents;
return this;
}
public int getSelectionStart()
{
return selectionStart;
}
public string getSelection()
{
return hasSelection ? text.Substring( Math.Min( selectionStart, cursor ), Math.Max( selectionStart, cursor ) ) : "";
}
/// <summary>
/// Sets the selected text
/// </summary>
/// <param name="selectionStart">Selection start.</param>
/// <param name="selectionEnd">Selection end.</param>
public TextField setSelection( int selectionStart, int selectionEnd )
{
Assert.isFalse( selectionStart < 0, "selectionStart must be >= 0" );
Assert.isFalse( selectionEnd < 0, "selectionEnd must be >= 0" );
selectionStart = Math.Min( text.Length, selectionStart );
selectionEnd = Math.Min( text.Length, selectionEnd );
if( selectionEnd == selectionStart )
{
clearSelection();
return this;
}
if( selectionEnd < selectionStart )
{
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
hasSelection = true;
this.selectionStart = selectionStart;
cursor = selectionEnd;
return this;
}
public void selectAll()
{
setSelection( 0, text.Length );
}
public void clearSelection()
{
hasSelection = false;
}
protected void setCursorPosition( float x, float y )
{
lastBlink = 0;
cursorOn = false;
cursor = letterUnderCursor( x );
}
/// <summary>
/// Sets the cursor position and clears any selection
/// </summary>
/// <param name="cursorPosition">Cursor position.</param>
public TextField setCursorPosition( int cursorPosition )
{
Assert.isFalse( cursorPosition < 0, "cursorPosition must be >= 0" );
clearSelection();
cursor = Math.Min( cursorPosition, text.Length );
return this;
}
public int getCursorPosition()
{
return cursor;
}
protected void goHome()
{
cursor = 0;
}
protected void goEnd()
{
cursor = text.Length;
}
protected void moveCursor( bool forward, bool jump )
{
var limit = forward ? text.Length : 0;
var charOffset = forward ? 0 : -1;
if( ( forward && cursor == limit ) || ( !forward && cursor == 0 ) )
return;
while( ( forward ? ++cursor < limit : --cursor > limit ) && jump )
{
if( !continueCursor( cursor, charOffset ) )
break;
}
}
protected bool continueCursor( int index, int offset )
{
var c = text[index + offset];
return isWordCharacter( c );
}
#region Configuration
public TextField setPreferredWidth( float preferredWidth )
{
_preferredWidth = preferredWidth;
return this;
}
/// <summary>
/// filter May be null
/// </summary>
/// <param name="filter">Filter.</param>
public TextField setTextFieldFilter( ITextFieldFilter filter )
{
this.filter = filter;
return this;
}
public ITextFieldFilter getTextFieldFilter()
{
return filter;
}
/// <summary>
/// If true (the default), tab/shift+tab will move to the next text field
/// </summary>
/// <param name="focusTraversal">If set to <c>true</c> focus traversal.</param>
public TextField setFocusTraversal( bool focusTraversal )
{
this.focusTraversal = focusTraversal;
return this;
}
/// <summary>
/// May be null
/// </summary>
/// <returns>The message text.</returns>
public string getMessageText()
{
return messageText;
}
/// <summary>
/// Sets the text that will be drawn in the text field if no text has been entered.
/// </summary>
/// <param name="messageText">Message text.</param>
public TextField setMessageText( string messageText )
{
this.messageText = messageText;
return this;
}
/// <summary>
/// Sets text horizontal alignment (left, center or right).
/// </summary>
/// <param name="alignment">Alignment.</param>
public TextField setAlignment( Align alignment )
{
this.textHAlign = (int)alignment;
return this;
}
/// <summary>
/// If true, the text in this text field will be shown as bullet characters.
/// </summary>
/// <param name="passwordMode">Password mode.</param>
public TextField setPasswordMode( bool passwordMode )
{
this.passwordMode = passwordMode;
updateDisplayText();
return this;
}
public bool isPasswordMode()
{
return passwordMode;
}
/// <summary>
/// Sets the password character for the text field. The character must be present in the {@link BitmapFont}. Default is 149 (bullet)
/// </summary>
/// <param name="passwordCharacter">Password character.</param>
public TextField setPasswordCharacter( char passwordCharacter )
{
this.passwordCharacter = passwordCharacter;
if( passwordMode )
updateDisplayText();
return this;
}
public TextField setBlinkTime( float blinkTime )
{
this.blinkTime = blinkTime;
return this;
}
public TextField setDisabled( bool disabled )
{
this.disabled = disabled;
return this;
}
public bool isDisabled()
{
return disabled;
}
#endregion
/// <summary>
/// Interface for filtering characters entered into the text field.
/// </summary>
public interface ITextFieldFilter
{
bool acceptChar( TextField textField, char c );
}
}
public class TextFieldStyle
{
public BitmapFont font;
public Color fontColor = Color.White;
/** Optional. */
public Color? focusedFontColor, disabledFontColor;
/** Optional. */
public IDrawable background, focusedBackground, disabledBackground, cursor, selection;
/** Optional. */
public BitmapFont messageFont;
/** Optional. */
public Color? messageFontColor;
public TextFieldStyle()
{
font = Graphics.instance.bitmapFont;
}
public TextFieldStyle( BitmapFont font, Color fontColor, IDrawable cursor, IDrawable selection, IDrawable background )
{
this.background = background;
this.cursor = cursor;
this.font = font ?? Graphics.instance.bitmapFont;
this.fontColor = fontColor;
this.selection = selection;
}
public static TextFieldStyle create( Color fontColor, Color cursorColor, Color selectionColor, Color backgroundColor )
{
var cursor = new PrimitiveDrawable( cursorColor );
cursor.minWidth = 1;
cursor.leftWidth = 4;
var background = new PrimitiveDrawable( backgroundColor );
background.leftWidth = background.rightWidth = 10f;
background.bottomHeight = background.topHeight = 5f;
return new TextFieldStyle {
fontColor = fontColor,
cursor = cursor,
selection = new PrimitiveDrawable( selectionColor ),
background = background
};
}
public TextFieldStyle clone()
{
return new TextFieldStyle {
font = font,
fontColor = fontColor,
focusedFontColor = focusedFontColor,
disabledFontColor = disabledFontColor,
background = background,
focusedBackground = focusedBackground,
disabledBackground = disabledBackground,
cursor = cursor,
selection = selection,
messageFont = messageFont,
messageFontColor = messageFontColor
};
}
}
public class DigitsOnlyFilter : TextField.ITextFieldFilter
{
public bool acceptChar( TextField textField, char c )
{
return Char.IsDigit( c ) || c == '-';
}
}
public class FloatFilter : TextField.ITextFieldFilter
{
public bool acceptChar( TextField textField, char c )
{
// only allow one .
if( c == '.' )
return !textField.getText().Contains( "." );
return Char.IsDigit( c ) || c == '-';
}
}
public class BoolFilter : TextField.ITextFieldFilter
{
public bool acceptChar( TextField textField, char c )
{
if( c == 't' || c == 'T' )
textField.setTextForced( "true" );
if( c == 'f' || c == 'F' )
textField.setTextForced( "false" );
return false;
}
}
}
| 24.128938 | 150 | 0.639422 | [
"MIT"
] | Blucky87/Nez | Nez.Portable/UI/Widgets/TextField.cs | 32,938 | C# |
using JSC_LMS.Application.Contracts.Persistence;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JSC_LMS.Application.Features.KnowledgeBase.Commands.DeleteKnowledgeBase
{
public class DeleteKnowledgeBaseCommandHandler : IRequestHandler<DeleteKnowledgeBaseCommand>
{
private readonly IKnowledgeBaseRepository _knowledgebaseRepository;
public DeleteKnowledgeBaseCommandHandler(IKnowledgeBaseRepository knowledgebaseRepository)
{
_knowledgebaseRepository = knowledgebaseRepository;
}
public async Task<Unit> Handle(DeleteKnowledgeBaseCommand request, CancellationToken cancellationToken)
{
var knowledgebaseToDelete = await _knowledgebaseRepository.GetByIdAsync(request.Id);
await _knowledgebaseRepository.DeleteAsync(knowledgebaseToDelete);
return Unit.Value;
}
}
}
| 35.071429 | 111 | 0.766802 | [
"Apache-2.0"
] | ashishneosoftmail/JSC_LMS | src/Core/JSC_LMS.Application/Features/KnowledgeBase/Commands/DeleteKnowledgeBase/DeleteKnowledgeBaseCommandHandler.cs | 984 | C# |
using System.Diagnostics.Contracts;
namespace Funcable.Control;
public static partial class Prelude
{
[Pure]
public static IResult<U, UError> BiMap<T, TError, U, UError>(
IResult<T, TError> result,
Func<T, U> okMapping,
Func<TError, UError> errorMapping)
where T : notnull
where TError : notnull
where U : notnull
where UError : notnull =>
Match(
result,
t => Ok<U, UError>(okMapping(t)),
e => Error<U, UError>(errorMapping(e))
);
}
| 21.090909 | 62 | 0.68319 | [
"MIT"
] | CarvanaCorp/funcable | src/Funcable.Control/src/Result/Prelude_BiFunctor_Result.cs | 464 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NUnit.Framework;
using Python.Runtime;
using QuantConnect.Data;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Python;
using QuantConnect.Securities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuantConnect.Tests.Engine.DataFeeds
{
[TestFixture, Ignore]
public class PandasConverterTests
{
[Test]
public void HandlesEmptyEnumerable()
{
var converter = new PandasConverter();
var rawBars = Enumerable.Empty<TradeBar>().ToArray();
// GetDataFrame with argument of type IEnumerable<TradeBar>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsTrue(dataFrame.empty.AsManagedObject(typeof(bool)));
}
// GetDataFrame with argument of type IEnumerable<TradeBar>
var history = GetHistory(Symbols.SPY, Resolution.Minute, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsTrue(dataFrame.empty.AsManagedObject(typeof(bool)));
}
}
[Test]
public void HandlesTradeBars()
{
var converter = new PandasConverter();
var symbol = Symbols.SPY;
var rawBars = Enumerable
.Range(0, 10)
.Select(i => new TradeBar(DateTime.UtcNow.AddMinutes(i), symbol, i + 101m, i + 102m, i + 100m, i + 101m, 0m))
.ToArray();
// GetDataFrame with argument of type IEnumerable<TradeBar>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var close = subDataFrame.loc[index].close.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Close, close);
}
}
// GetDataFrame with argument of type IEnumerable<TradeBar>
var history = GetHistory(symbol, Resolution.Minute, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var close = subDataFrame.loc[index].close.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Close, close);
}
}
}
[Test]
public void HandlesQuoteBars()
{
var converter = new PandasConverter();
var symbol = Symbols.EURUSD;
var rawBars = Enumerable
.Range(0, 10)
.Select(i => new QuoteBar(DateTime.UtcNow.AddMinutes(i), symbol, new Bar(i + 1.01m, i + 1.02m, i + 1.00m, i + 1.01m), 0m, new Bar(i + 1.01m, i + 1.02m, i + 1.00m, i + 1.01m), 0m))
.ToArray();
// GetDataFrame with argument of type IEnumerable<QuoteBar>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var close = subDataFrame.loc[index].close.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Close, close);
}
}
// GetDataFrame with argument of type IEnumerable<QuoteBar>
var history = GetHistory(symbol, Resolution.Minute, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var close = subDataFrame.loc[index].askclose.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Ask.Close, close);
}
}
}
[Test]
public void HandlesTradeTicks()
{
var converter = new PandasConverter();
var symbol = Symbols.SPY;
var rawBars = Enumerable
.Range(0, 10)
.Select(i => new Tick(symbol, $"1440{i:D2}00,167{i:D2}00,1{i:D2},T,T,0", new DateTime(2013, 10, 7)))
.ToArray();
// GetDataFrame with argument of type IEnumerable<QuoteBar>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
Assert.IsTrue(subDataFrame.get("askprice") == null);
Assert.IsTrue(subDataFrame.get("exchange") != null);
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].lastprice.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].LastPrice, value);
}
}
// GetDataFrame with argument of type IEnumerable<QuoteBar>
var history = GetHistory(symbol, Resolution.Tick, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
Assert.IsTrue(subDataFrame.get("askprice") == null);
Assert.IsTrue(subDataFrame.get("exchange") != null);
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].lastprice.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].LastPrice, value);
}
}
}
[Test]
public void HandlesQuoteTicks()
{
var converter = new PandasConverter();
var symbol = Symbols.EURUSD;
var rawBars = Enumerable
.Range(0, 10)
.Select(i => new Tick(DateTime.UtcNow.AddMilliseconds(100 * i), symbol, 0.99m, 1.01m))
.ToArray();
// GetDataFrame with argument of type IEnumerable<QuoteBar>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
Assert.IsTrue(subDataFrame.get("askprice") != null);
Assert.IsTrue(subDataFrame.get("exchange") == null);
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].lastprice.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].LastPrice, value);
}
}
// GetDataFrame with argument of type IEnumerable<QuoteBar>
var history = GetHistory(symbol, Resolution.Tick, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
Assert.IsTrue(subDataFrame.get("askprice") != null);
Assert.IsTrue(subDataFrame.get("exchange") == null);
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].askprice.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].AskPrice, value);
}
}
}
[Test]
[TestCase(typeof(Quandl), "yyyy-MM-dd")]
[TestCase(typeof(FxcmVolume), "yyyyMMdd HH:mm")]
public void HandlesCustomDataBars(Type type, string format)
{
var converter = new PandasConverter();
var symbol = Symbols.LTCUSD;
var config = GetSubscriptionDataConfig<Quandl>(symbol, Resolution.Daily);
var custom = Activator.CreateInstance(type) as BaseData;
if (type == typeof(Quandl)) custom.Reader(config, "date,open,high,low,close,transactions", DateTime.UtcNow, false);
var rawBars = Enumerable
.Range(0, 10)
.Select(i =>
{
var line = $"{DateTime.UtcNow.AddDays(i).ToString(format)},{i + 101},{i + 102},{i + 100},{i + 101},{i + 101}";
return custom.Reader(config, line, DateTime.UtcNow.AddDays(i), false);
})
.ToArray();
// GetDataFrame with argument of type IEnumerable<BaseData>
dynamic dataFrame = converter.GetDataFrame(rawBars);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].value.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Value, value);
var transactions = subDataFrame.loc[index].transactions.AsManagedObject(typeof(decimal));
var expected = (rawBars[i] as DynamicData)?.GetProperty("transactions");
expected = expected ?? type.GetProperty("Transactions")?.GetValue(rawBars[i]);
Assert.AreEqual(expected, transactions);
}
}
// GetDataFrame with argument of type IEnumerable<BaseData>
var history = GetHistory(symbol, Resolution.Daily, rawBars);
dataFrame = converter.GetDataFrame(history);
using (Py.GIL())
{
Assert.IsFalse(dataFrame.empty.AsManagedObject(typeof(bool)));
var subDataFrame = dataFrame.loc[symbol];
Assert.IsFalse(subDataFrame.empty.AsManagedObject(typeof(bool)));
var count = subDataFrame.__len__().AsManagedObject(typeof(int));
Assert.AreEqual(count, 10);
for (var i = 0; i < count; i++)
{
var index = subDataFrame.index[i];
var value = subDataFrame.loc[index].value.AsManagedObject(typeof(decimal));
Assert.AreEqual(rawBars[i].Value, value);
var transactions = subDataFrame.loc[index].transactions.AsManagedObject(typeof(decimal));
var expected = (rawBars[i] as DynamicData)?.GetProperty("transactions");
expected = expected ?? type.GetProperty("Transactions")?.GetValue(rawBars[i]);
Assert.AreEqual(expected, transactions);
}
}
}
public IEnumerable<Slice> GetHistory<T>(Symbol symbol, Resolution resolution, IEnumerable<T> data)
where T : IBaseData
{
var subscriptionDataConfig = GetSubscriptionDataConfig<T>(symbol, resolution);
var security = GetSecurity(subscriptionDataConfig);
return data.Select(t => TimeSlice.Create(
t.Time,
TimeZones.Utc,
new CashBook(),
new List<DataFeedPacket> { new DataFeedPacket(security, subscriptionDataConfig, new List<BaseData>() { t as BaseData }) },
new SecurityChanges(Enumerable.Empty<Security>(), Enumerable.Empty<Security>())).Slice);
}
private SubscriptionDataConfig GetSubscriptionDataConfig<T>(Symbol symbol, Resolution resolution)
{
return new SubscriptionDataConfig(
typeof(T),
symbol,
resolution,
TimeZones.Utc,
TimeZones.Utc,
true,
true,
false);
}
private Security GetSecurity(SubscriptionDataConfig subscriptionDataConfig)
{
return new Security(
SecurityExchangeHours.AlwaysOpen(TimeZones.Utc),
subscriptionDataConfig,
new Cash(CashBook.AccountCurrency, 0, 1m),
SymbolProperties.GetDefault(CashBook.AccountCurrency));
}
}
} | 40.17 | 195 | 0.559995 | [
"Apache-2.0"
] | Bimble/Lean | Tests/Python/PandasConverterTests.cs | 16,070 | C# |
using DotVVM.Framework.ViewModel;
using DotvvmAcademy.CourseFormat;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DotvvmAcademy.Web.Pages.Test
{
public class TestViewModel : DotvvmViewModelBase
{
private readonly CourseWorkspace workspace;
public TestViewModel(CourseWorkspace workspace)
{
this.workspace = workspace;
}
public List<CodeTaskDiagnostic> Diagnostics { get; set; }
[FromRoute("LessonMoniker")]
public string LessonMoniker { get; set; }
[FromRoute("VariantMoniker")]
public string VariantMoniker { get; set; }
[FromRoute("StepMoniker")]
public string StepMoniker { get; set; }
public override async Task Load()
{
var codeTask = workspace.CurrentCourse.GetLesson(LessonMoniker)
.GetVariant(VariantMoniker)
.GetStep(StepMoniker)
.CodeTask;
var diagnostics = await workspace.ValidateCodeTask(codeTask, "");
Diagnostics = diagnostics.ToList();
}
}
} | 29.025641 | 77 | 0.638693 | [
"Apache-2.0"
] | ammogcoder/dotvvm-samples-academy | src/DotvvmAcademy.Web/Pages/Test/TestViewModel.cs | 1,134 | C# |
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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 OWNER 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using MatterHackers.Agg.Font;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
namespace MatterHackers.Agg.UI
{
public class InternalTextEditWidget : GuiWidget, IIgnoredPopupChild
{
private static HashSet<char> WordBreakChars = new HashSet<char>(new char[]
{
' ', '\t', // white space characters
'\'', '"', '`', // quotes
',', '.', '?', '!', '@', '&', // punctuation
'(', ')', '<', '>', '[', ']', '{', '}', // parents (or equivalent)
'-', '+', '*', '/', '=', '\\', '#', '$', '^', '|', // math symbols
});
private static HashSet<char> WordBreakCharsAndCR
{
get
{
var withCR = new HashSet<char>(WordBreakChars);
withCR.Add('\n');
return withCR;
}
}
public static Action<InternalTextEditWidget, MouseEventArgs> DefaultRightClick;
public event KeyEventHandler EnterPressed;
public event EventHandler AllSelected;
private UndoBuffer undoBuffer = new UndoBuffer();
private bool mouseIsDownLeft = false;
private bool showingRightClickMenu = false;
private bool _selecting;
public bool Selecting
{
get
{
return _selecting;
}
set
{
if (_selecting != value)
{
_selecting = value;
Invalidate();
}
}
}
public bool KeepMenuOpen { get; set; } = false;
public int SelectionIndexToStartBefore { get; set; }
private int _charIndexToInsertBefore;
public int CharIndexToInsertBefore
{
get
{
if (!string.IsNullOrEmpty(this.Text))
{
_charIndexToInsertBefore = Math.Min(this.Text.Length, _charIndexToInsertBefore);
}
else
{
_charIndexToInsertBefore = 0;
}
return _charIndexToInsertBefore;
}
set
{
_charIndexToInsertBefore = value;
}
}
private int charIndexToAcceptAsMerging;
private double desiredBarX;
private readonly TextWidget internalTextWidget;
public bool MergeTypingDuringUndo { get; set; }
public event EventHandler InsertBarPositionChanged;
/// <summary>
/// This event fires when the user has finished editing the control.
/// Fired on leave event after editing, or on enter key for non-multi line controls.
/// </summary>
public event EventHandler EditComplete;
private Vector2 insertBarPosition;
public new bool DoubleBuffer
{
get
{
return internalTextWidget.DoubleBuffer;
}
set
{
internalTextWidget.DoubleBuffer = value;
}
}
public Vector2 InsertBarPosition
{
get
{
return insertBarPosition;
}
set
{
if (insertBarPosition != value)
{
insertBarPosition = value;
OnInsertBarPositionChanged(null);
}
}
}
public TypeFacePrinter Printer
{
get
{
return internalTextWidget.Printer;
}
}
/// <summary>
/// This is called when the user has modified the text control. It will
/// be triggered when the control looses focus or enter is pressed on non-multi-line control.
/// </summary>
/// <param name="e">The event args to pass on to EditComplete</param>
public virtual void OnEditComplete(EventArgs e)
{
EditComplete?.Invoke(this, e);
textWhenGotFocus = Text;
}
private void OnInsertBarPositionChanged(EventArgs e)
{
InsertBarPositionChanged?.Invoke(this, e);
}
public string Selection
{
get
{
if (Selecting)
{
// make local copies to make sure we aren't affected by any threading issues
var text = Text;
var charIndexToInsertBefore = Math.Max(0, Math.Min(text.Length, CharIndexToInsertBefore));
var selectionIndexToStartBefore = Math.Max(0, Math.Min(text.Length, SelectionIndexToStartBefore));
if (charIndexToInsertBefore < selectionIndexToStartBefore)
{
return text.Substring(charIndexToInsertBefore, selectionIndexToStartBefore - charIndexToInsertBefore);
}
else
{
return text.Substring(selectionIndexToStartBefore, charIndexToInsertBefore - selectionIndexToStartBefore);
}
}
return "";
}
}
public override string Text
{
get
{
return internalTextWidget.Text;
}
set
{
if (internalTextWidget.Text != value)
{
CharIndexToInsertBefore = 0;
internalTextWidget.Text = value;
OnTextChanged(null);
Invalidate();
}
}
}
public InternalTextEditWidget(string text, double pointSize, bool multiLine, int tabIndex, TypeFace typeFace = null)
{
TabIndex = tabIndex;
TabStop = true;
MergeTypingDuringUndo = true;
internalTextWidget = new TextWidget(text, pointSize: pointSize, ellipsisIfClipped: false, textColor: _textColor, typeFace: typeFace);
internalTextWidget.Selectable = false;
internalTextWidget.AutoExpandBoundsToText = true;
AddChild(internalTextWidget);
UpdateLocalBounds();
Multiline = multiLine;
FixBarPosition(DesiredXPositionOnLine.Set);
var newUndoData = new TextWidgetUndoCommand(this);
undoBuffer.Add(newUndoData);
Cursor = Cursors.IBeam;
internalTextWidget.TextChanged += new EventHandler(InternalTextWidget_TextChanged);
internalTextWidget.BoundsChanged += new EventHandler(InternalTextWidget_BoundsChanged);
}
private void UpdateLocalBounds()
{
// double padding = 5;
double width = Math.Max(internalTextWidget.Width + 2, 3);
double height = Math.Max(internalTextWidget.Height, internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels);
// LocalBounds = new RectangleDouble(this.BorderWidth - padding, this.BorderWidth - padding, width + this.BorderWidth + padding, height + this.BorderWidth + padding);
LocalBounds = new RectangleDouble(-1, 0, width, height);
// TODO: text widget should have some padding rather than the 1 on the x below. LBB 2013/02/03
internalTextWidget.OriginRelativeParent = new Vector2(1, -internalTextWidget.LocalBounds.Bottom);
}
private void InternalTextWidget_BoundsChanged(object sender, EventArgs e)
{
UpdateLocalBounds();
}
private void InternalTextWidget_TextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
public bool Multiline { get; set; } = true;
private Stopwatch timeSinceTurnOn = new Stopwatch();
private double barOnTime = .6;
private double barOffTime = .6;
private bool BarIsShowing { get { return timeSinceTurnOn.ElapsedMilliseconds < barOnTime * 1000; } }
public void OnIdle()
{
if (this.Focused
&& timeSinceTurnOn.ElapsedMilliseconds >= barOnTime * 950
&& !HasBeenClosed)
{
if (timeSinceTurnOn.ElapsedMilliseconds >= (barOnTime + barOffTime) * 950)
{
RestartBarFlash();
}
else
{
UiThread.RunOnIdle(OnIdle, barOffTime);
Invalidate();
}
}
else
{
timeSinceTurnOn.Stop();
}
}
private void RestartBarFlash()
{
timeSinceTurnOn.Restart();
UiThread.RunOnIdle(OnIdle, barOnTime);
Invalidate();
}
public bool SelectAllOnFocus { get; set; }
private bool selectAllOnMouseUpIfNoSelection = false;
private string textWhenGotFocus;
public override void OnFocusChanged(EventArgs e)
{
if (Focused)
{
if (!showingRightClickMenu)
{
// don't change the focus text if we were showing the right click menu
textWhenGotFocus = Text;
}
showingRightClickMenu = false;
RestartBarFlash();
timeSinceTurnOn.Restart();
if (SelectAllOnFocus)
{
selectAllOnMouseUpIfNoSelection = true;
}
}
else
{
// do not lose selection on focus changed
Invalidate();
if (TextHasChanged())
{
OnEditComplete(e);
}
else if (SelectAllOnFocus
&& selectedAllDueToFocus
&& !showingRightClickMenu)
{
// if we select all on focus and the selection happened due to focus and no change
Selecting = false;
}
}
base.OnFocusChanged(e);
}
public void MarkAsStartingState()
{
textWhenGotFocus = Text;
}
public bool TextHasChanged()
{
return textWhenGotFocus != Text;
}
public Color CursorColor { get; set; } = Color.DarkGray;
public Color HighlightColor { get; set; } = Color.Gray;
private Color _textColor = Color.Black;
private int _borderWidth = 0;
private bool selectedAllDueToFocus;
public int BorderRadius { get; set; } = 0;
public int BorderWidth
{
get
{
return this._borderWidth;
}
set
{
this._borderWidth = value;
UpdateLocalBounds();
}
}
public Color TextColor
{
get
{
return _textColor;
}
set
{
this._textColor = value;
internalTextWidget.TextColor = this._textColor;
}
}
public bool ReadOnly { get; set; }
public override void OnDraw(Graphics2D graphics2D)
{
double fontHeight = internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels;
if (Selecting
&& SelectionIndexToStartBefore != CharIndexToInsertBefore)
{
Vector2 selectPosition = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(SelectionIndexToStartBefore);
// for each selected line draw a rect for the chars of that line
if (selectPosition.Y == InsertBarPosition.Y)
{
var bar = new RectangleDouble(Math.Ceiling(selectPosition.X),
Math.Ceiling(internalTextWidget.Height + selectPosition.Y),
Math.Ceiling(InsertBarPosition.X + 1),
Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y - fontHeight));
var selectCursorRect = new RoundedRect(bar, 0);
graphics2D.Render(selectCursorRect, this.HighlightColor);
}
else
{
int firstCharToHighlight = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore);
int lastCharToHighlight = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore);
int lineStart = firstCharToHighlight;
Vector2 lineStartPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(lineStart);
int lineEnd = lineStart + 1;
Vector2 lineEndPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(lineEnd);
if (lineEndPos.Y != lineStartPos.Y)
{
// we are starting on a '\n', adjust so we will show the cr at the end of the line
lineEndPos = lineStartPos;
}
bool firstCharOfLine = false;
for (int i = lineEnd; i < lastCharToHighlight + 1; i++)
{
Vector2 nextPos = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(i);
if (firstCharOfLine)
{
if (lineEndPos.Y != lineStartPos.Y)
{
// we are starting on a '\n', adjust so we will show the cr at the end of the line
lineEndPos = lineStartPos;
}
firstCharOfLine = false;
}
if (nextPos.Y != lineStartPos.Y)
{
if (lineEndPos.X == lineStartPos.X)
{
lineEndPos.X += Printer.TypeFaceStyle.GetAdvanceForCharacter(' ');
}
var bar = new RectangleDouble(Math.Ceiling(lineStartPos.X),
Math.Ceiling(internalTextWidget.Height + lineStartPos.Y),
Math.Ceiling(lineEndPos.X + 1),
Math.Ceiling(internalTextWidget.Height + lineEndPos.Y - fontHeight));
var selectCursorRect = new RoundedRect(bar, 0);
graphics2D.Render(selectCursorRect, this.HighlightColor);
lineStartPos = nextPos;
firstCharOfLine = true;
}
else
{
lineEndPos = nextPos;
}
}
if (lineEndPos.X != lineStartPos.X)
{
var bar = new RectangleDouble(Math.Ceiling(lineStartPos.X),
Math.Ceiling(internalTextWidget.Height + lineStartPos.Y),
Math.Ceiling(lineEndPos.X + 1),
Math.Ceiling(internalTextWidget.Height + lineEndPos.Y - fontHeight));
var selectCursorRect = new RoundedRect(bar, 0);
graphics2D.Render(selectCursorRect, this.HighlightColor);
}
}
}
if (this.Focused && BarIsShowing)
{
double xFraction = graphics2D.GetTransform().tx;
xFraction = xFraction - (int)xFraction;
var bar2 = new RectangleDouble(Math.Ceiling(InsertBarPosition.X) - xFraction,
Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y - fontHeight),
Math.Ceiling(InsertBarPosition.X + 1) - xFraction,
Math.Ceiling(internalTextWidget.Height + InsertBarPosition.Y));
var cursorRect = new RoundedRect(bar2, 0);
graphics2D.Render(cursorRect, this.CursorColor);
}
base.OnDraw(graphics2D);
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
if (mouseEvent.Button == MouseButtons.Left)
{
StartSelectionIfRequired(null);
CharIndexToInsertBefore = internalTextWidget.Printer.GetCharacterIndexToStartBefore(new Vector2(mouseEvent.X, mouseEvent.Y));
if (mouseEvent.Clicks < 2 || ShiftKeyIsDown(null))
{
if (CharIndexToInsertBefore == -1)
{
// we could not find any characters when looking for mouse click position
CharIndexToInsertBefore = 0;
}
if (!ShiftKeyIsDown(null))
{
SelectionIndexToStartBefore = CharIndexToInsertBefore;
Selecting = false;
}
mouseIsDownLeft = true;
}
else if (IsDoubleClick(mouseEvent) && Text.Length > 0)
{
while (CharIndexToInsertBefore >= 0
&& (CharIndexToInsertBefore >= Text.Length
|| (CharIndexToInsertBefore > -1 && !WordBreakCharsAndCR.Contains(Text[CharIndexToInsertBefore]))))
{
CharIndexToInsertBefore--;
}
CharIndexToInsertBefore++;
SelectionIndexToStartBefore = CharIndexToInsertBefore + 1;
while (SelectionIndexToStartBefore < Text.Length && !WordBreakCharsAndCR.Contains(Text[SelectionIndexToStartBefore]))
{
SelectionIndexToStartBefore++;
}
Selecting = true;
}
RestartBarFlash();
FixBarPosition(DesiredXPositionOnLine.Set);
}
base.OnMouseDown(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
if (mouseIsDownLeft)
{
StartSelectionIfRequired(null);
CharIndexToInsertBefore = internalTextWidget.Printer.GetCharacterIndexToStartBefore(new Vector2(mouseEvent.X, mouseEvent.Y));
if (CharIndexToInsertBefore < 0)
{
CharIndexToInsertBefore = 0;
}
if (CharIndexToInsertBefore != SelectionIndexToStartBefore)
{
Selecting = true;
}
Invalidate();
FixBarPosition(DesiredXPositionOnLine.Set);
}
base.OnMouseMove(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
if (SelectAllOnFocus
&& selectAllOnMouseUpIfNoSelection
&& Selecting == false)
{
SelectAll();
selectedAllDueToFocus = true;
}
else
{
selectedAllDueToFocus = false;
}
if (mouseEvent.Button == MouseButtons.Left)
{
mouseIsDownLeft = false;
showingRightClickMenu = false;
}
else if (mouseEvent.Button == MouseButtons.Right)
{
if (DefaultRightClick != null)
{
showingRightClickMenu = true;
DefaultRightClick?.Invoke(this, mouseEvent);
}
}
selectAllOnMouseUpIfNoSelection = false;
base.OnMouseUp(mouseEvent);
}
public override string ToString()
{
return internalTextWidget.Text;
}
protected enum DesiredXPositionOnLine
{
Maintain,
Set
}
protected void FixBarPosition(DesiredXPositionOnLine desiredXPositionOnLine)
{
InsertBarPosition = internalTextWidget.Printer.GetOffsetLeftOfCharacterIndex(CharIndexToInsertBefore);
if (desiredXPositionOnLine == DesiredXPositionOnLine.Set)
{
desiredBarX = InsertBarPosition.X;
}
Invalidate();
}
private void DeleteIndexRange(int startIndexInclusive, int endIndexInclusive)
{
// first make sure we are deleting something that exists
startIndexInclusive = Math.Max(0, Math.Min(startIndexInclusive, internalTextWidget.Text.Length));
endIndexInclusive = Math.Max(startIndexInclusive, Math.Min(endIndexInclusive, internalTextWidget.Text.Length));
int lengthToDelete = endIndexInclusive + 1 - startIndexInclusive;
if (lengthToDelete > 0 && internalTextWidget.Text.Length - startIndexInclusive >= lengthToDelete)
{
var stringBuilder = new StringBuilder(internalTextWidget.Text);
stringBuilder.Remove(startIndexInclusive, lengthToDelete);
internalTextWidget.Text = stringBuilder.ToString();
}
}
public void DeleteSelection(bool createUndoMarker = true)
{
if (ReadOnly)
{
return;
}
if (Selecting)
{
if (CharIndexToInsertBefore < SelectionIndexToStartBefore)
{
DeleteIndexRange(CharIndexToInsertBefore, SelectionIndexToStartBefore - 1);
}
else
{
DeleteIndexRange(SelectionIndexToStartBefore, CharIndexToInsertBefore - 1);
CharIndexToInsertBefore = SelectionIndexToStartBefore;
}
if (createUndoMarker)
{
var newUndoDeleteData = new TextWidgetUndoCommand(this);
undoBuffer.Add(newUndoDeleteData);
}
Selecting = false;
}
}
public void SetSelection(int firstIndexSelected, int lastIndexSelected)
{
firstIndexSelected = Math.Max(0, Math.Min(firstIndexSelected, Text.Length - 1));
lastIndexSelected = Math.Max(0, Math.Min(lastIndexSelected, Text.Length));
SelectionIndexToStartBefore = firstIndexSelected;
CharIndexToInsertBefore = lastIndexSelected + 1;
Selecting = true;
FixBarPosition(DesiredXPositionOnLine.Set);
}
private void StartSelectionIfRequired(KeyEventArgs keyEvent)
{
if (!Selecting && ShiftKeyIsDown(keyEvent))
{
Selecting = true;
SelectionIndexToStartBefore = CharIndexToInsertBefore;
}
}
private bool ShiftKeyIsDown(KeyEventArgs keyEvent)
{
return Keyboard.IsKeyDown(Keys.Shift)
|| (keyEvent != null && keyEvent.Shift);
}
public override void OnKeyDown(KeyEventArgs keyEvent)
{
// this must be called first to ensure we get the correct Handled state
base.OnKeyDown(keyEvent);
if (!keyEvent.Handled)
{
RestartBarFlash();
bool setDesiredBarPosition = true;
bool turnOffSelection = false;
if (!ShiftKeyIsDown(keyEvent))
{
if (keyEvent.Control)
{
// don't let control keys get into the stream
keyEvent.Handled = true;
}
else if (Selecting)
{
turnOffSelection = true;
}
}
switch (keyEvent.KeyCode)
{
case Keys.Escape:
if (Selecting)
{
turnOffSelection = true;
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
}
break;
case Keys.Left:
StartSelectionIfRequired(keyEvent);
if (keyEvent.Control)
{
CharIndexToInsertBefore = IndexOfPreviousToken(internalTextWidget.Text, CharIndexToInsertBefore);
}
else if (CharIndexToInsertBefore > 0)
{
if (turnOffSelection)
{
CharIndexToInsertBefore = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore);
}
else
{
CharIndexToInsertBefore--;
}
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Right:
StartSelectionIfRequired(keyEvent);
if (keyEvent.Control)
{
CharIndexToInsertBefore = IndexOfNextToken(internalTextWidget.Text, CharIndexToInsertBefore);
}
else if (CharIndexToInsertBefore < internalTextWidget.Text.Length)
{
if (turnOffSelection)
{
CharIndexToInsertBefore = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore);
}
else
{
CharIndexToInsertBefore++;
}
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Up:
StartSelectionIfRequired(keyEvent);
if (turnOffSelection)
{
CharIndexToInsertBefore = Math.Min(CharIndexToInsertBefore, SelectionIndexToStartBefore);
}
GotoLineAbove();
setDesiredBarPosition = false;
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Down:
StartSelectionIfRequired(keyEvent);
if (turnOffSelection)
{
CharIndexToInsertBefore = Math.Max(CharIndexToInsertBefore, SelectionIndexToStartBefore);
}
GotoLineBelow();
setDesiredBarPosition = false;
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Space:
keyEvent.Handled = true;
break;
case Keys.PageDown:
StartSelectionIfRequired(keyEvent);
{
var scrollParent = Parent?.Parent;
if (scrollParent != null)
{
var downLines = (int)(scrollParent.Height / internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels);
// try to find downlines worth of cr and try to keep the same distance into the line
for (int i = 0; i < downLines; i++)
{
GotoLineBelow();
}
}
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.PageUp:
StartSelectionIfRequired(keyEvent);
{
var scrollParent = Parent?.Parent;
if (scrollParent != null)
{
var upLines = (int)(scrollParent.Height / internalTextWidget.Printer.TypeFaceStyle.EmSizeInPixels);
// try to find downlines worth of cr and try to keep the same distance into the line
for (int i = 0; i < upLines; i++)
{
GotoLineAbove();
}
}
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.End:
StartSelectionIfRequired(keyEvent);
if (keyEvent.Control)
{
CharIndexToInsertBefore = internalTextWidget.Text.Length;
}
else
{
GotoEndOfCurrentLine();
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Home:
StartSelectionIfRequired(keyEvent);
if (keyEvent.Control)
{
CharIndexToInsertBefore = 0;
}
else
{
CharIndexToInsertBefore = GotoStartOfCurrentLine(internalTextWidget.Text, CharIndexToInsertBefore);
}
keyEvent.SuppressKeyPress = true;
keyEvent.Handled = true;
break;
case Keys.Back:
if (!Selecting
&& CharIndexToInsertBefore > 0)
{
SelectionIndexToStartBefore = CharIndexToInsertBefore - 1;
Selecting = true;
}
DeleteSelection();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
break;
case Keys.Delete:
if (ShiftKeyIsDown(keyEvent))
{
CopySelection();
DeleteSelection();
keyEvent.SuppressKeyPress = true;
}
else
{
if (!Selecting
&& CharIndexToInsertBefore < internalTextWidget.Text.Length)
{
SelectionIndexToStartBefore = CharIndexToInsertBefore + 1;
Selecting = true;
}
DeleteSelection();
}
turnOffSelection = true;
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
break;
case Keys.Enter:
if (!Multiline)
{
// TODO: do the right thing.
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
if (EnterPressed != null)
{
EnterPressed(this, keyEvent);
}
if (TextHasChanged())
{
OnEditComplete(keyEvent);
}
}
break;
case Keys.Insert:
if (ShiftKeyIsDown(keyEvent))
{
turnOffSelection = true;
PasteFromClipboard();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
if (keyEvent.Control)
{
turnOffSelection = false;
CopySelection();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.A:
if (keyEvent.Control)
{
SelectAll();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.X:
if (keyEvent.Control)
{
CopySelection();
DeleteSelection();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.C:
if (keyEvent.Control)
{
turnOffSelection = false;
CopySelection();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.V:
if (keyEvent.Control)
{
PasteFromClipboard();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.Z:
if (keyEvent.Control)
{
if (keyEvent.Shift)
{
Redo();
}
else
{
Undo();
}
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
case Keys.Y:
if (keyEvent.Control)
{
Redo();
keyEvent.Handled = true;
keyEvent.SuppressKeyPress = true;
}
break;
}
if (setDesiredBarPosition)
{
FixBarPosition(DesiredXPositionOnLine.Set);
}
else
{
FixBarPosition(DesiredXPositionOnLine.Maintain);
}
// if we are not going to type a character, and therefore replace the selection, turn off the selection now if needed.
if (keyEvent.SuppressKeyPress && turnOffSelection)
{
Selecting = false;
}
Invalidate();
}
}
public void Undo()
{
undoBuffer.Undo();
FixBarPosition(DesiredXPositionOnLine.Set);
}
public void Redo()
{
undoBuffer.Redo();
FixBarPosition(DesiredXPositionOnLine.Set);
}
public void CopySelection()
{
if (Selecting)
{
var text = Text;
var charIndexToInsertBefore = Math.Max(0, Math.Min(text.Length, CharIndexToInsertBefore));
var selectionIndexToStartBefore = Math.Max(0, Math.Min(text.Length, SelectionIndexToStartBefore));
if (charIndexToInsertBefore < selectionIndexToStartBefore)
{
Clipboard.Instance.SetText(text.Substring(charIndexToInsertBefore, selectionIndexToStartBefore - charIndexToInsertBefore));
}
else
{
Clipboard.Instance.SetText(text.Substring(selectionIndexToStartBefore, charIndexToInsertBefore - selectionIndexToStartBefore));
}
}
else if (Multiline)
{
// copy the line?
}
}
public void PasteFromClipboard()
{
if (ReadOnly)
{
return;
}
if (Clipboard.Instance.ContainsText)
{
if (Selecting)
{
DeleteSelection(false);
}
var stringBuilder = new StringBuilder(internalTextWidget.Text);
string stringOnClipboard = Clipboard.Instance.GetText();
if (!Multiline)
{
stringOnClipboard = Regex.Replace(stringOnClipboard, @"\r\n?|\n", " ");
}
stringBuilder.Insert(CharIndexToInsertBefore, stringOnClipboard);
CharIndexToInsertBefore += stringOnClipboard.Length;
internalTextWidget.Text = stringBuilder.ToString();
var newUndoCommand = new TextWidgetUndoCommand(this);
undoBuffer.Add(newUndoCommand);
}
}
public override void OnKeyPress(KeyPressEventArgs keyPressEvent)
{
// this must be called first to ensure we get the correct Handled state
base.OnKeyPress(keyPressEvent);
if (!keyPressEvent.Handled)
{
if (keyPressEvent.KeyChar < 32
&& keyPressEvent.KeyChar != 13
&& keyPressEvent.KeyChar != 9)
{
return;
}
if (ReadOnly)
{
return;
}
if (Selecting)
{
DeleteSelection();
Selecting = false;
}
var tempString = new StringBuilder(internalTextWidget.Text);
if (keyPressEvent.KeyChar == '\r')
{
tempString.Insert(CharIndexToInsertBefore, "\n");
}
else
{
tempString.Insert(CharIndexToInsertBefore, keyPressEvent.KeyChar.ToString());
}
keyPressEvent.Handled = true;
CharIndexToInsertBefore++;
internalTextWidget.Text = tempString.ToString();
FixBarPosition(DesiredXPositionOnLine.Set);
var newUndoData = new TextWidgetUndoCommand(this);
if (MergeTypingDuringUndo
&& charIndexToAcceptAsMerging == CharIndexToInsertBefore - 1
&& keyPressEvent.KeyChar != '\n' && keyPressEvent.KeyChar != '\r')
{
undoBuffer.Add(newUndoData);
}
else
{
undoBuffer.Add(newUndoData);
}
charIndexToAcceptAsMerging = CharIndexToInsertBefore;
}
}
private int GetIndexOffset(int characterStartIndexInclusive, int maxCharacterEndIndexInclusive, double desiredPixelOffset)
{
int offsetIndex = 0;
int endOffsetIndex = maxCharacterEndIndexInclusive - characterStartIndexInclusive;
var offset = default(Vector2);
var lastOffset = default(Vector2);
while (true)
{
internalTextWidget.Printer.GetOffset(characterStartIndexInclusive, characterStartIndexInclusive + offsetIndex, out offset);
offsetIndex++;
if (offset.X >= desiredPixelOffset || offsetIndex >= endOffsetIndex)
{
if (Math.Abs(offset.Y) < .01
&& Math.Abs(lastOffset.X - desiredPixelOffset) < Math.Abs(offset.X - desiredPixelOffset))
{
offsetIndex--;
}
break;
}
lastOffset = offset;
}
int maxLength = Math.Min(maxCharacterEndIndexInclusive - characterStartIndexInclusive, offsetIndex);
return characterStartIndexInclusive + maxLength;
}
// the '\n' is always considered to be the end of the line.
// if startIndexInclusive == endIndexInclusive, the line is empty (other than the return)
private void GetStartAndEndIndexForLineContainingChar(int charToFindLineContaining, out int startIndexOfLineInclusive, out int endIndexOfLineInclusive)
{
startIndexOfLineInclusive = 0;
endIndexOfLineInclusive = internalTextWidget.Text.Length;
if (endIndexOfLineInclusive == 0)
{
return;
}
charToFindLineContaining = Math.Max(Math.Min(charToFindLineContaining, internalTextWidget.Text.Length), 0);
// first lets find the end of the line. Check if we are on a '\n'
if (charToFindLineContaining == internalTextWidget.Text.Length
|| internalTextWidget.Text[charToFindLineContaining] == '\n')
{
// we are on the end of the line
endIndexOfLineInclusive = charToFindLineContaining;
}
else
{
int endReturn = internalTextWidget.Text.IndexOf('\n', charToFindLineContaining + 1);
if (endReturn != -1)
{
endIndexOfLineInclusive = endReturn;
}
}
// check if the line is empty (the character to our left is the '\n' on the previous line
bool isIndex0AndNL = endIndexOfLineInclusive == 0 && internalTextWidget.Text[endIndexOfLineInclusive] == '\n';
if (isIndex0AndNL || internalTextWidget.Text[endIndexOfLineInclusive - 1] == '\n')
{
// the line is empty the start = the end.
startIndexOfLineInclusive = endIndexOfLineInclusive;
}
else
{
int returnAtStartOfCurrentLine = internalTextWidget.Text.LastIndexOf('\n', endIndexOfLineInclusive - 1);
if (returnAtStartOfCurrentLine != -1)
{
startIndexOfLineInclusive = returnAtStartOfCurrentLine + 1;
}
}
}
private void GotoLineAbove()
{
GetStartAndEndIndexForLineContainingChar(CharIndexToInsertBefore, out int startIndexInclusive, out int endIndexInclusive);
GetStartAndEndIndexForLineContainingChar(startIndexInclusive - 1, out int prevStartIndexInclusive, out int prevEndIndexInclusive);
// we found the extents of the line above now put the cursor in the right place.
CharIndexToInsertBefore = GetIndexOffset(prevStartIndexInclusive, prevEndIndexInclusive, desiredBarX);
}
private void GotoLineBelow()
{
GetStartAndEndIndexForLineContainingChar(CharIndexToInsertBefore, out int startIndexInclusive, out int endIndexInclusive);
GetStartAndEndIndexForLineContainingChar(endIndexInclusive + 1, out int nextStartIndexInclusive, out int nextEndIndexInclusive);
// we found the extents of the line above now put the cursor in the right place.
CharIndexToInsertBefore = GetIndexOffset(nextStartIndexInclusive, nextEndIndexInclusive, desiredBarX);
}
public static int IndexOfNextToken(string text, int cursor)
{
var insert = cursor;
var length = text.Length;
if (insert == text.Length)
{
// If we are already at the end, return.
return text.Length;
}
// if we are starting an a CR
if (text[insert] == '\n')
{
// If we are on a CR advance one (goto next line)
insert++;
// and skip ' ' and '\t'
while (insert < length
&& (text[insert] == ' ' || text[insert] == '\t'))
{
insert++;
}
return insert;
}
else if (WordBreakChars.Contains(text[insert]))
{
// we are starting on a work break char
// while we are on the same char advance
var current = text[insert];
while (insert < length && text[insert] == current)
{
insert++;
}
}
else
{
// we are starting on a normal character
while (insert < length && !WordBreakCharsAndCR.Contains(text[insert]))
{
insert++;
}
// and also skip ' ' and '\t'
while (insert < length
&& (text[insert] == ' ' || text[insert] == '\t'))
{
insert++;
}
}
return insert;
}
public static int IndexOfPreviousToken(string text, int cursor)
{
if (cursor == 0)
{
return 0;
}
int prevToken = Math.Max(0, Math.Min(text.Length - 1, cursor - 1));
var token = text[prevToken];
if (text[prevToken] == '\n')
{
if (prevToken > 0
&& text[prevToken - 1] == '\n')
{
return prevToken;
}
prevToken--;
}
else if (token == ' ' || token == '\t')
{
// the token to the left is a breaking character
while (--prevToken >= 0
&& (text[prevToken] == ' ' || text[prevToken] == '\t'))
{
// skip back the entire token
}
}
else if (WordBreakChars.Contains(token))
{
// the token to the left is a breaking character
while (--prevToken >= 0 && text[prevToken] == token)
{
// skip back the entire token
}
return prevToken + 1;
}
// the token to the left is normal character skip until a break
while (prevToken >= 0 && !WordBreakCharsAndCR.Contains(text[prevToken]))
{
// skip back until we are on a word break
prevToken--;
}
return prevToken + 1;
}
public void SelectAll()
{
CharIndexToInsertBefore = internalTextWidget.Text.Length;
SelectionIndexToStartBefore = 0;
Selecting = true;
FixBarPosition(DesiredXPositionOnLine.Set);
if (AllSelected != null)
{
AllSelected(this, null);
}
}
internal void GotoEndOfCurrentLine()
{
int indexOfReturn = internalTextWidget.Text.IndexOf('\n', CharIndexToInsertBefore);
if (indexOfReturn == -1)
{
CharIndexToInsertBefore = internalTextWidget.Text.Length;
}
else
{
CharIndexToInsertBefore = indexOfReturn;
}
FixBarPosition(DesiredXPositionOnLine.Set);
}
public static int GotoStartOfCurrentLine(string text, int cursor)
{
if (cursor > 0)
{
int indexOfReturn = text.LastIndexOf('\n', cursor - 1);
if (indexOfReturn == -1)
{
return 0;
}
else
{
var firstNonWhiteSpaceRegex = new Regex("[^\\t ]");
Match firstNonWhiteSpace = firstNonWhiteSpaceRegex.Match(text, indexOfReturn + 1);
if (firstNonWhiteSpace.Success)
{
if (firstNonWhiteSpace.Index < cursor
|| text[cursor - 1] == '\n')
{
return firstNonWhiteSpace.Index;
}
}
return indexOfReturn + 1;
}
}
return 0;
}
public void ClearUndoHistory()
{
undoBuffer.ClearHistory();
var newUndoData = new TextWidgetUndoCommand(this);
undoBuffer.Add(newUndoData);
}
}
} | 25.791492 | 169 | 0.669352 | [
"BSD-2-Clause"
] | 595787816/agg-sharp | Gui/TextWidgets/InternalTextEditWidget.cs | 36,987 | C# |
using NorthwindProject.Entities.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NorthwindProject.Entities.DTOs
{
public class DtoProduct : DtoBase
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int? SupplierId { get; set; }
public int? CategoryId { get; set; }
public string QuantityPerUnit { get; set; }
public decimal? UnitPrice { get; set; }
public short? UnitsInStock { get; set; }
public short? UnitsOnOrder { get; set; }
public short? ReorderLevel { get; set; }
public bool Discontinued { get; set; }
}
}
| 30.25 | 51 | 0.650138 | [
"MIT"
] | 142-Bupa-Acibadem-FullStack-Bootcamp/week-5-assignment-1-srgnbkr | NorthwindProject/src/Libraries/NorthwindProject.Entities/DTOs/DtoProduct.cs | 728 | C# |
namespace BlazorMud.Contracts.Services
{
/// <summary>
/// Result of a service call.
/// </summary>
public class ServiceResult
{
/// <summary>
/// <c>true</c> if the call was succesfull, <c>false</c> if an error occured.
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// Message for display to the user.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Creates a new <see cref="ServiceResult"/> instance with the specified parameters.
/// </summary>
/// <param name="isSuccess">Call success.</param>
/// <param name="message">Message to the user.</param>
public ServiceResult(bool isSuccess = true, string message = "")
{
IsSuccess = isSuccess;
Message = message;
}
}
/// <summary>
/// Result of a service call with service call return data.
/// </summary>
/// <typeparam name="TResult">The type of the result the service returns.</typeparam>
public sealed class ServiceResult<TResult> : ServiceResult
{
/// <summary>
/// The service call's return data.
/// </summary>
public TResult Result { get; set; }
/// <summary>
/// Creates a new <see cref="ServiceResult{TResult}"/> instance with the specified parameters.
/// </summary>
/// <param name="isSuccess">Call success.</param>
/// <param name="message">Message to the user.</param>
/// <param name="result">The service call return data.</param>
public ServiceResult(bool isSuccess = true, string message = "", TResult result = default)
: base(isSuccess, message)
{
Result = result;
}
}
}
| 33.62963 | 102 | 0.560573 | [
"MIT"
] | Pixelgamix/BlazorMud | BlazorMud.Contracts/Services/ServiceResult.cs | 1,818 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Threading.Tasks;
using Convey.Persistence.OpenStack.OCS.Http;
using Convey.Persistence.OpenStack.OCS.OcsTypes;
using Convey.Persistence.OpenStack.OCS.OcsTypes.Definition;
using Convey.Persistence.OpenStack.OCS.OpenStack.Responses;
using Convey.Persistence.OpenStack.OCS.RequestHandler;
using Newtonsoft.Json;
namespace Convey.Persistence.OpenStack.OCS.Client
{
internal class OcsClient : IOcsClient
{
private readonly IRequestHandler _requestHandler;
private readonly OcsOptions _ocsOptions;
private OcsClient() { }
public OcsClient(IRequestHandler requestHandler, OcsOptions ocsOptions)
{
_requestHandler = requestHandler;
_ocsOptions = ocsOptions;
}
public async Task<IOperationResult<byte[]>> GetObjectAsByteArray(params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithMethod(HttpMethod.Get)
.WithHeader("Content-Type", MediaTypeNames.Application.Octet)
.WithRelativeUrl(GetPath(relativePath)));
var validationResult = ValidateHttpResult(result);
return validationResult == OperationStatus.Success ?
new OperationResult<byte[]>(validationResult, await result.Content.ReadAsByteArrayAsync()) :
new OperationResult<byte[]>(validationResult);
}
public async Task<IOperationResult<Stream>> GetObjectAsStream(params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithMethod(HttpMethod.Get)
.WithHeader("Content-Type", MediaTypeNames.Application.Octet)
.WithRelativeUrl(GetPath(relativePath)));
var validationResult = ValidateHttpResult(result);
return validationResult == OperationStatus.Success ?
new OperationResult<Stream>(validationResult, await result.Content.ReadAsStreamAsync()) :
new OperationResult<Stream>(validationResult);
}
public async Task<IOperationResult<string>> GetObjectAsBase64String(params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithMethod(HttpMethod.Get)
.WithRelativeUrl(GetPath(relativePath)));
var validationResult = ValidateHttpResult(result);
return validationResult == OperationStatus.Success ?
new OperationResult<string>(validationResult, Convert.ToBase64String(await result.Content.ReadAsByteArrayAsync())) :
new OperationResult<string>(validationResult);
}
public async Task<IOperationResult<List<OcsObjectMetadata>>> GetDirectoryList(params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithRelativeUrl(GetPath(relativePath))
.WithMethod(HttpMethod.Get));
var validationResult = ValidateHttpResult(result);
if (validationResult != OperationStatus.Success)
{
return new OperationResult<List<OcsObjectMetadata>>(validationResult);
}
var openStackResponse = JsonConvert.DeserializeObject<List<ObjectMetadata>>(await result.Content.ReadAsStringAsync());
return new OperationResult<List<OcsObjectMetadata>>(validationResult, ObjectMapper.Map(openStackResponse).ToList());
}
public async Task<IOperationResult> UploadAsStream(Stream stream, params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithRelativeUrl(GetPath(relativePath))
.WithHeader("Content-Type", MediaTypeNames.Application.Octet)
.WithMethod(HttpMethod.Put)
.WithStreamContent(stream));
return new OperationResult(ValidateHttpResult(result));
}
public async Task<IOperationResult> UploadAsBase64String(string base64String, params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithRelativeUrl(GetPath(relativePath))
.WithHeader("Content-Type", MediaTypeNames.Application.Octet)
.WithMethod(HttpMethod.Put)
.WithStreamContent(new MemoryStream(Convert.FromBase64String(base64String))));
return new OperationResult(ValidateHttpResult(result));
}
public async Task<IOperationResult> CopyInternally(string relativeSourcePath, string relativeDestinationPath)
{
var result = await _requestHandler.Send(builder => builder
.WithHeader("Destination", $"{_ocsOptions.RootDirectory}/{relativeDestinationPath}")
.WithRelativeUrl(GetPath(relativeSourcePath))
.WithMethod(HttpMethodExtended.Copy));
return new OperationResult(ValidateHttpResult(result));
}
public async Task<IOperationResult> Delete(params string[] relativePath)
{
var result = await _requestHandler.Send(builder => builder
.WithRelativeUrl(GetPath(relativePath))
.WithMethod(HttpMethod.Delete));
return new OperationResult(ValidateHttpResult(result));
}
private OperationStatus ValidateHttpResult(HttpRequestResult result)
{
if (result.IsSuccess)
{
return OperationStatus.Success;
}
if (result.Exception is null)
{
switch (result.StatusCode)
{
case HttpStatusCode.NotFound:
return OperationStatus.NotFound;
}
}
return OperationStatus.Failed;
}
private string GetPath(string[] relativePath)
=> $"/{_ocsOptions.ProjectRelativeUrl}/{_ocsOptions.RootDirectory}/{string.Join('/', relativePath)}";
private string GetPath(string relativePath)
=> $"/{_ocsOptions.ProjectRelativeUrl}/{_ocsOptions.RootDirectory}/{relativePath}";
}
}
| 41.922581 | 132 | 0.642505 | [
"MIT"
] | 1n5an1ty/Convey | src/Convey.Persistence.OpenStack.OCS/src/Convey.Persistence.OpenStack.OCS/Client/OcsClient.cs | 6,500 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CameraPreview.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.225806 | 151 | 0.569597 | [
"MIT"
] | t-miyake/AngryMail | CameraPreview/Properties/Settings.Designer.cs | 1,094 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/SetupAPI.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public partial struct SP_CLASSIMAGELIST_DATA32
{
[NativeTypeName("DWORD")]
public uint cbSize;
public HIMAGELIST ImageList;
[NativeTypeName("ULONG_PTR")]
public nuint Reserved;
}
| 29.095238 | 145 | 0.762684 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/SetupAPI/SP_CLASSIMAGELIST_DATA32.Manual.cs | 613 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CodeCracker.CSharp.Performance
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseStaticRegexIsMatchCodeFixProvider)), Shared]
public class UseStaticRegexIsMatchCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(DiagnosticId.UseStaticRegexIsMatch.ToDiagnosticId());
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
context.RegisterCodeFix(CodeAction.Create("Use static Regex.IsMatch", c => UseStaticRegexIsMatchAsync(context.Document, diagnostic, c), nameof(UseStaticRegexIsMatchCodeFixProvider) + nameof(UseStaticRegexIsMatchAsync)), diagnostic);
context.RegisterCodeFix(CodeAction.Create("Use static and compiled Regex.IsMatch", c => UseCompiledAndStaticRegexAsync(context.Document, diagnostic, c), nameof(UseStaticRegexIsMatchCodeFixProvider) + nameof(UseCompiledAndStaticRegexAsync)), diagnostic);
context.RegisterCodeFix(CodeAction.Create("Use Compiled Regex", c => UseCompiledRegexAsync(context.Document, diagnostic, c), nameof(UseStaticRegexIsMatchCodeFixProvider) + nameof(UseCompiledRegexAsync)), diagnostic);
return Task.FromResult(0);
}
private async static Task<Document> UseStaticRegexIsMatchAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) =>
await MakeRegexStaticAsync(document, diagnostic, cancellationToken, makeCompiled: false).ConfigureAwait(false);
private async static Task<Document> UseCompiledAndStaticRegexAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) =>
await MakeRegexStaticAsync(document, diagnostic, cancellationToken, makeCompiled: true).ConfigureAwait(false);
private async static Task<Document> MakeRegexStaticAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken, bool makeCompiled)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var invocationDeclaration = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent.AncestorsAndSelf().OfType<InvocationExpressionSyntax>().First();
var originalDeclaration = await GetObjectCreationAsync(document, invocationDeclaration, cancellationToken).ConfigureAwait(false);
var newArgumentList = originalDeclaration.ArgumentList.Arguments.Insert(0, invocationDeclaration.ArgumentList.Arguments.FirstOrDefault());
if (makeCompiled)
newArgumentList = newArgumentList.Insert(2, SyntaxFactory.Argument(SyntaxFactory.IdentifierName("RegexOptions.Compiled")));
var memberExpression = (MemberAccessExpressionSyntax)invocationDeclaration.Expression;
var isMatchExpression = SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName("Regex.IsMatch"),
SyntaxFactory.ArgumentList(newArgumentList))
.WithLeadingTrivia(memberExpression.GetLeadingTrivia())
.WithTrailingTrivia(memberExpression.GetTrailingTrivia());
var newRoot = root.ReplaceNode(invocationDeclaration, isMatchExpression);
var newDeclaratorSyntax = newRoot.FindToken(originalDeclaration.SpanStart).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
newRoot = newRoot.RemoveNode(newDeclaratorSyntax, SyntaxRemoveOptions.KeepNoTrivia);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
private async static Task<Document> UseCompiledRegexAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var invocationDeclaration = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent.AncestorsAndSelf().OfType<InvocationExpressionSyntax>().First();
var originalDeclaration = await GetObjectCreationAsync(document, invocationDeclaration, cancellationToken).ConfigureAwait(false);
var newArgumentList = originalDeclaration.ArgumentList.AddArguments(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("RegexOptions.Compiled")));
var newDeclaration = originalDeclaration.WithArgumentList(newArgumentList);
var newRoot = root.ReplaceNode(originalDeclaration, newDeclaration);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
private static async Task<ObjectCreationExpressionSyntax> GetObjectCreationAsync(Document document, InvocationExpressionSyntax invocationDeclaration, CancellationToken cancellationToken)
{
var memberExpression = (MemberAccessExpressionSyntax)invocationDeclaration.Expression;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var variableSymbol = semanticModel.GetSymbolInfo(((IdentifierNameSyntax)memberExpression.Expression).Identifier.Parent, cancellationToken).Symbol;
var declaratorSyntax = ((VariableDeclaratorSyntax)variableSymbol.DeclaringSyntaxReferences.FirstOrDefault().GetSyntax());
var originalDeclaration = declaratorSyntax.Initializer.DescendantNodes().OfType<ObjectCreationExpressionSyntax>().FirstOrDefault();
return originalDeclaration;
}
}
} | 73.463415 | 265 | 0.769588 | [
"Apache-2.0"
] | dmgandini/code-cracker | src/CSharp/CodeCracker/Performance/UseStaticRegexIsMatchCodeFixProvider.cs | 6,026 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.RuntimeMembers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
/// <summary>
/// Binds the type for the syntax taking into account possibility of "var" type.
/// </summary>
/// <param name="syntax">Type syntax to bind.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="isVar">
/// Set to false if syntax binds to a type in the current context and true if
/// syntax is "var" and it binds to "var" keyword in the current context.
/// </param>
/// <returns>
/// Bound type if syntax binds to a type in the current context and
/// null if syntax binds to "var" keyword in the current context.
/// </returns>
internal TypeSymbolWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isVar)
{
var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar);
Debug.Assert(isVar == symbol.IsDefault);
return isVar ? default : UnwrapAlias(symbol, diagnostics, syntax).Type;
}
/// <summary>
/// Binds the type for the syntax taking into account possibility of "unmanaged" type.
/// </summary>
/// <param name="syntax">Type syntax to bind.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="isUnmanaged">
/// Set to false if syntax binds to a type in the current context and true if
/// syntax is "unmanaged" and it binds to "unmanaged" keyword in the current context.
/// </param>
/// <returns>
/// Bound type if syntax binds to a type in the current context and
/// null if syntax binds to "unmanaged" keyword in the current context.
/// </returns>
internal TypeSymbolWithAnnotations BindTypeOrUnmanagedKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isUnmanaged)
{
var symbol = BindTypeOrAliasOrUnmanagedKeyword(syntax, diagnostics, out isUnmanaged);
Debug.Assert(isUnmanaged == symbol.IsDefault);
return isUnmanaged ? default : UnwrapAlias(symbol, diagnostics, syntax).Type;
}
/// <summary>
/// Binds the type for the syntax taking into account possibility of "var" type.
/// </summary>
/// <param name="syntax">Type syntax to bind.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="isVar">
/// Set to false if syntax binds to a type in the current context and true if
/// syntax is "var" and it binds to "var" keyword in the current context.
/// </param>
/// <param name="alias">Alias symbol if syntax binds to an alias.</param>
/// <returns>
/// Bound type if syntax binds to a type in the current context and
/// null if syntax binds to "var" keyword in the current context.
/// </returns>
internal TypeSymbolWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias)
{
var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar);
Debug.Assert(isVar == symbol.IsDefault);
if (isVar)
{
alias = null;
return default;
}
else
{
return UnwrapAlias(symbol, out alias, diagnostics, syntax).Type;
}
}
/// <summary>
/// Binds the type for the syntax taking into account possibility of "var" type.
/// If the syntax binds to an alias symbol to a type, it returns the alias symbol.
/// </summary>
/// <param name="syntax">Type syntax to bind.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="isVar">
/// Set to false if syntax binds to a type or alias to a type in the current context and true if
/// syntax is "var" and it binds to "var" keyword in the current context.
/// </param>
/// <returns>
/// Bound type or alias if syntax binds to a type or alias to a type in the current context and
/// null if syntax binds to "var" keyword in the current context.
/// </returns>
private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isVar)
{
if (syntax.IsVar)
{
var symbol = BindTypeOrAliasOrKeyword(syntax, diagnostics, out isVar);
if (isVar)
{
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics);
}
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, symbol);
}
else
{
isVar = false;
return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null);
}
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrUnmanagedKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isUnmanaged)
{
if (syntax.IsUnmanaged)
{
var symbol = BindTypeOrAliasOrKeyword(syntax, diagnostics, out isUnmanaged);
if (isUnmanaged)
{
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics);
}
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, symbol);
}
else
{
isUnmanaged = false;
return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null);
}
}
/// <summary>
/// Binds the type for the syntax taking into account possibility of the type being a keyword.
/// If the syntax binds to an alias symbol to a type, it returns the alias symbol.
/// PREREQUISITE: syntax should be checked to match the keyword, like <see cref="TypeSyntax.IsVar"/> or <see cref="TypeSyntax.IsUnmanaged"/>.
/// Otherwise, call <see cref="Binder.BindTypeOrAlias(ExpressionSyntax, DiagnosticBag, ConsList{Symbol})"/> instead.
/// </summary>
private Symbol BindTypeOrAliasOrKeyword(TypeSyntax syntax, DiagnosticBag diagnostics, out bool isKeyword)
{
// Keywords can only be IdentifierNameSyntax
var identifierValueText = ((IdentifierNameSyntax)syntax).Identifier.ValueText;
Symbol symbol = null;
// Perform name lookup without generating diagnostics as it could possibly be a keyword in the current context.
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsInternal(lookupResult, identifierValueText, arity: 0, useSiteDiagnostics: ref useSiteDiagnostics, basesBeingResolved: null, options: LookupOptions.NamespacesOrTypesOnly, diagnose: false);
// We have following possible cases for lookup:
// 1) LookupResultKind.Empty: must be a keyword
// 2) LookupResultKind.Viable:
// a) Single viable result that corresponds to 1) a non-error type: cannot be a keyword
// 2) an error type: must be a keyword
// b) Single viable result that corresponds to namespace: must be a keyword
// c) Multi viable result (ambiguous result), we must return an error type: cannot be a keyword
// 3) Non viable, non empty lookup result: must be a keyword
// BREAKING CHANGE: Case (2)(c) is a breaking change from the native compiler.
// BREAKING CHANGE: Native compiler interprets lookup with ambiguous result to correspond to bind
// BREAKING CHANGE: to "var" keyword (isVar = true), rather than reporting an error.
// BREAKING CHANGE: See test SemanticErrorTests.ErrorMeansSuccess_var() for an example.
switch (lookupResult.Kind)
{
case LookupResultKind.Empty:
// Case (1)
isKeyword = true;
symbol = null;
break;
case LookupResultKind.Viable:
// Case (2)
DiagnosticBag resultDiagnostics = DiagnosticBag.GetInstance();
bool wasError;
symbol = ResultSymbol(
lookupResult,
identifierValueText,
arity: 0,
where: syntax,
diagnostics: resultDiagnostics,
suppressUseSiteDiagnostics: false,
wasError: out wasError);
// Here, we're mimicking behavior of dev10. If the identifier fails to bind
// as a type, even if the reason is (e.g.) a type/alias conflict, then treat
// it as the contextual keyword.
if (wasError && lookupResult.IsSingleViable)
{
// NOTE: don't report diagnostics - we're not going to use the lookup result.
resultDiagnostics.Free();
// Case (2)(a)(2)
goto default;
}
diagnostics.AddRange(resultDiagnostics);
resultDiagnostics.Free();
if (lookupResult.IsSingleViable)
{
var type = UnwrapAlias(symbol, diagnostics, syntax) as TypeSymbol;
if ((object)type != null)
{
// Case (2)(a)(1)
isKeyword = false;
}
else
{
// Case (2)(b)
Debug.Assert(UnwrapAliasNoDiagnostics(symbol) is NamespaceSymbol);
isKeyword = true;
symbol = null;
}
}
else
{
// Case (2)(c)
isKeyword = false;
}
break;
default:
// Case (3)
isKeyword = true;
symbol = null;
break;
}
lookupResult.Free();
return symbol;
}
// Binds the given expression syntax as Type.
// If the resulting symbol is an Alias to a Type, it unwraps the alias
// and returns it's target type.
internal TypeSymbolWithAnnotations BindType(ExpressionSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved = null)
{
var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved);
return UnwrapAlias(symbol, diagnostics, syntax, basesBeingResolved).Type;
}
// Binds the given expression syntax as Type.
// If the resulting symbol is an Alias to a Type, it stores the AliasSymbol in
// the alias parameter, unwraps the alias and returns it's target type.
internal TypeSymbolWithAnnotations BindType(ExpressionSyntax syntax, DiagnosticBag diagnostics, out AliasSymbol alias, ConsList<Symbol> basesBeingResolved = null)
{
var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved);
return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved).Type;
}
// Binds the given expression syntax as Type or an Alias to Type
// and returns the resultant symbol.
// NOTE: This method doesn't unwrap aliases.
internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(diagnostics != null);
var symbol = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null);
// symbol must be a TypeSymbol or an Alias to a TypeSymbol
if (symbol.IsType ||
(symbol.IsAlias && UnwrapAliasNoDiagnostics(symbol.Symbol, basesBeingResolved) is TypeSymbol))
{
if (symbol.IsType)
{
// Obsolete alias targets are reported in UnwrapAlias, but if it was a type (not an
// alias to a type) we report the obsolete type here.
symbol.Type.ReportDiagnosticsIfObsolete(this, syntax, diagnostics);
}
return symbol;
}
var diagnosticInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, syntax.Location, syntax, symbol.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize());
return TypeSymbolWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol.Symbol), symbol.Symbol, LookupResultKind.NotATypeOrNamespace, diagnosticInfo));
}
/// <summary>
/// The immediately containing namespace or named type, or the global
/// namespace if containing symbol is neither a namespace or named type.
/// </summary>
private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol)
{
return symbol.ContainingNamespaceOrType() ?? this.Compilation.Assembly.GlobalNamespace;
}
internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, DiagnosticBag diagnostics)
{
if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword)
{
return this.Compilation.GlobalNamespaceAlias;
}
else
{
bool wasError;
var plainName = node.Identifier.ValueText;
var result = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsWithFallback(result, plainName, 0, ref useSiteDiagnostics, null, LookupOptions.NamespaceAliasesOnly);
diagnostics.Add(node, useSiteDiagnostics);
Symbol bindingResult = ResultSymbol(result, plainName, 0, node, diagnostics, false, out wasError, options: LookupOptions.NamespaceAliasesOnly);
result.Free();
return bindingResult;
}
}
internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved = null)
{
return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null);
}
internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved, bool suppressUseSiteDiagnostics)
{
var result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics);
Debug.Assert(!result.IsDefault);
return UnwrapAlias(result, diagnostics, syntax, basesBeingResolved);
}
internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved, bool suppressUseSiteDiagnostics)
{
switch (syntax.Kind())
{
case SyntaxKind.NullableType:
{
var nullableSyntax = (NullableTypeSyntax)syntax;
TypeSyntax typeArgumentSyntax = nullableSyntax.ElementType;
TypeSymbolWithAnnotations typeArgument = BindType(typeArgumentSyntax, diagnostics, basesBeingResolved);
TypeSymbolWithAnnotations constructedType = typeArgument.SetIsAnnotated(Compilation);
reportNullableReferenceTypesIfNeeded(nullableSyntax.QuestionToken, typeArgument);
if (!ShouldCheckConstraints)
{
diagnostics.Add(new LazyUseSiteDiagnosticsInfoForNullableType(constructedType), syntax.GetLocation());
}
else if (constructedType.IsNullableType())
{
ReportUseSiteDiagnostics(constructedType.TypeSymbol.OriginalDefinition, diagnostics, syntax);
var type = (NamedTypeSymbol)constructedType.TypeSymbol;
var location = syntax.Location;
var conversions = this.Conversions.WithNullability(includeNullability: true);
if (!ShouldCheckConstraintsNullability)
{
diagnostics.Add(new LazyNullableContraintChecksDiagnosticInfo(type, conversions, this.Compilation), location);
conversions = conversions.WithNullability(includeNullability: false);
}
type.CheckConstraints(this.Compilation, conversions, location, diagnostics);
}
else if (constructedType.TypeSymbol.IsUnconstrainedTypeParameter())
{
diagnostics.Add(ErrorCode.ERR_NullableUnconstrainedTypeParameter, syntax.Location);
}
return constructedType;
}
case SyntaxKind.PredefinedType:
{
var type = BindPredefinedTypeSymbol((PredefinedTypeSyntax)syntax, diagnostics);
return TypeSymbolWithAnnotations.Create(NonNullTypesContext, type);
}
case SyntaxKind.IdentifierName:
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext,
BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt: null));
case SyntaxKind.GenericName:
return TypeSymbolWithAnnotations.Create(NonNullTypesContext,
BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt: null));
case SyntaxKind.AliasQualifiedName:
{
var node = (AliasQualifiedNameSyntax)syntax;
var bindingResult = BindNamespaceAliasSymbol(node.Alias, diagnostics);
var alias = bindingResult as AliasSymbol;
NamespaceOrTypeSymbol left = ((object)alias != null) ? alias.Target : (NamespaceOrTypeSymbol)bindingResult;
if (left.Kind == SymbolKind.NamedType)
{
return TypeSymbolWithAnnotations.Create(new ExtendedErrorTypeSymbol(left, LookupResultKind.NotATypeOrNamespace, diagnostics.Add(ErrorCode.ERR_ColColWithTypeAlias, node.Alias.Location, node.Alias.Identifier.Text)));
}
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, this.BindSimpleNamespaceOrTypeOrAliasSymbol(node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left));
}
case SyntaxKind.QualifiedName:
{
var node = (QualifiedNameSyntax)syntax;
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, BindQualifiedName(node.Left, node.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics));
}
case SyntaxKind.SimpleMemberAccessExpression:
{
var node = (MemberAccessExpressionSyntax)syntax;
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, BindQualifiedName(node.Expression, node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics));
}
case SyntaxKind.ArrayType:
{
var node = (ArrayTypeSyntax)syntax;
TypeSymbolWithAnnotations type = BindType(node.ElementType, diagnostics, basesBeingResolved);
if (type.IsStatic)
{
// CS0719: '{0}': array elements cannot be of static type
Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, node.ElementType, type.TypeSymbol);
}
if (ShouldCheckConstraints)
{
if (type.IsRestrictedType())
{
// CS0611: Array elements cannot be of type '{0}'
Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node.ElementType, type.TypeSymbol);
}
}
else
{
diagnostics.Add(new LazyArrayElementCantBeRefAnyDiagnosticInfo(type), node.ElementType.GetLocation());
}
for (int i = node.RankSpecifiers.Count - 1; i >= 0; i--)
{
var a = node.RankSpecifiers[i];
var array = ArrayTypeSymbol.CreateCSharpArray(this.Compilation.Assembly, type, a.Rank);
if (a.QuestionToken.IsKind(SyntaxKind.QuestionToken))
{
type = TypeSymbolWithAnnotations.Create(array, isNullableIfReferenceType: true);
reportNullableReferenceTypesIfNeeded(a.QuestionToken);
}
else
{
type = TypeSymbolWithAnnotations.Create(NonNullTypesContext, array);
}
}
return type;
}
case SyntaxKind.PointerType:
{
var node = (PointerTypeSyntax)syntax;
var elementType = BindType(node.ElementType, diagnostics, basesBeingResolved);
ReportUnsafeIfNotAllowed(node, diagnostics);
// Checking BinderFlags.GenericConstraintsClause to prevent cycles in binding
if (Flags.HasFlag(BinderFlags.GenericConstraintsClause) && elementType.TypeKind == TypeKind.TypeParameter)
{
// Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
Error(diagnostics, ErrorCode.ERR_BadConstraintType, node);
}
else if (elementType.IsManagedType)
{
// "Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')"
Error(diagnostics, ErrorCode.ERR_ManagedAddr, node, elementType.TypeSymbol);
}
return TypeSymbolWithAnnotations.Create(new PointerTypeSymbol(elementType));
}
case SyntaxKind.OmittedTypeArgument:
{
return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved);
}
case SyntaxKind.TupleType:
{
return TypeSymbolWithAnnotations.Create(NonNullTypesContext, BindTupleType((TupleTypeSyntax)syntax, diagnostics));
}
case SyntaxKind.RefType:
{
// ref needs to be handled by the caller
var refTypeSyntax = (RefTypeSyntax)syntax;
var refToken = refTypeSyntax.RefKeyword;
if (!syntax.HasErrors)
{
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refToken.GetLocation(), refToken.ToString());
}
return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics);
}
default:
throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
}
void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeSymbolWithAnnotations typeArgument = default)
{
// Inside a method body or other executable code, we can pull on NonNullTypes symbol or question IsValueType without causing cycles.
// We still need to delay that check when binding in an attribute argument
if (!InExecutableBinder || !ShouldCheckConstraintsNullability)
{
diagnostics.Add(new LazyMissingNonNullTypesContextDiagnosticInfo(Compilation, NonNullTypesContext, typeArgument), questionToken.GetLocation());
}
else
{
DiagnosticInfo info = LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded(Compilation, NonNullTypesContext, typeArgument);
if (!(info is null))
{
diagnostics.Add(info, questionToken.GetLocation());
}
}
}
}
private TypeSymbol BindTupleType(TupleTypeSyntax syntax, DiagnosticBag diagnostics)
{
int numElements = syntax.Elements.Count;
var types = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance(numElements);
var locations = ArrayBuilder<Location>.GetInstance(numElements);
ArrayBuilder<string> elementNames = null;
// set of names already used
var uniqueFieldNames = PooledHashSet<string>.GetInstance();
bool hasExplicitNames = false;
for (int i = 0; i < numElements; i++)
{
var argumentSyntax = syntax.Elements[i];
var argumentType = BindType(argumentSyntax.Type, diagnostics);
types.Add(argumentType);
string name = null;
SyntaxToken nameToken = argumentSyntax.Identifier;
if (nameToken.Kind() == SyntaxKind.IdentifierToken)
{
name = nameToken.ValueText;
// validate name if we have one
hasExplicitNames = true;
CheckTupleMemberName(name, i, nameToken, diagnostics, uniqueFieldNames);
locations.Add(nameToken.GetLocation());
}
else
{
locations.Add(argumentSyntax.Location);
}
CollectTupleFieldMemberName(name, i, numElements, ref elementNames);
}
uniqueFieldNames.Free();
if (hasExplicitNames)
{
// If the tuple type with names is bound we must have the TupleElementNamesAttribute to emit
// it is typically there though, if we have ValueTuple at all
// and we need System.String as well
// Report diagnostics if System.String doesn't exist
this.GetSpecialType(SpecialType.System_String, diagnostics, syntax);
if (!Compilation.HasTupleNamesAttributes)
{
var info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing,
AttributeDescription.TupleElementNamesAttribute.FullName);
Error(diagnostics, info, syntax);
}
}
var typesArray = types.ToImmutableAndFree();
var locationsArray = locations.ToImmutableAndFree();
if (typesArray.Length < 2)
{
throw ExceptionUtilities.UnexpectedValue(typesArray.Length);
}
return TupleTypeSymbol.Create(syntax.Location,
typesArray,
locationsArray,
elementNames == null ?
default(ImmutableArray<string>) :
elementNames.ToImmutableAndFree(),
this.Compilation,
this.ShouldCheckConstraints,
errorPositions: default(ImmutableArray<bool>),
syntax: syntax,
diagnostics: diagnostics);
}
private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder<string> elementNames)
{
// add the name to the list
// names would typically all be there or none at all
// but in case we need to handle this in error cases
if (elementNames != null)
{
elementNames.Add(name);
}
else
{
if (name != null)
{
elementNames = ArrayBuilder<string>.GetInstance(tupleSize);
for (int j = 0; j < elementIndex; j++)
{
elementNames.Add(null);
}
elementNames.Add(name);
}
}
}
private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, DiagnosticBag diagnostics, PooledHashSet<string> uniqueFieldNames)
{
int reserved = TupleTypeSymbol.IsElementNameReserved(name);
if (reserved == 0)
{
Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name);
return false;
}
else if (reserved > 0 && reserved != index + 1)
{
Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, reserved);
return false;
}
else if (!uniqueFieldNames.Add(name))
{
Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax);
return false;
}
return true;
}
private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, DiagnosticBag diagnostics)
{
return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, node);
}
/// <summary>
/// Binds a simple name or the simple name portion of a qualified name.
/// </summary>
private Symbol BindSimpleNamespaceOrTypeOrAliasSymbol(
SimpleNameSyntax syntax,
DiagnosticBag diagnostics,
ConsList<Symbol> basesBeingResolved,
bool suppressUseSiteDiagnostics,
NamespaceOrTypeSymbol qualifierOpt = null)
{
// Note that the comment above is a small lie; there is no such thing as the "simple name portion" of
// a qualified alias member expression. A qualified alias member expression has the form
// "identifier :: identifier optional-type-arguments" -- the right hand side of which
// happens to match the syntactic form of a simple name. As a convenience, we analyze the
// right hand side of the "::" here because it is so similar to a simple name; the left hand
// side is in qualifierOpt.
switch (syntax.Kind())
{
default:
return new ExtendedErrorTypeSymbol(qualifierOpt ?? this.Compilation.Assembly.GlobalNamespace, string.Empty, arity: 0, errorInfo: null);
case SyntaxKind.IdentifierName:
return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt);
case SyntaxKind.GenericName:
return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt);
}
}
private static bool IsViableType(LookupResult result)
{
if (!result.IsMultiViable)
{
return false;
}
foreach (var s in result.Symbols)
{
switch (s.Kind)
{
case SymbolKind.Alias:
if (((AliasSymbol)s).Target.Kind == SymbolKind.NamedType) return true;
break;
case SymbolKind.NamedType:
case SymbolKind.TypeParameter:
return true;
}
}
return false;
}
protected Symbol BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol(
IdentifierNameSyntax node,
DiagnosticBag diagnostics,
ConsList<Symbol> basesBeingResolved,
bool suppressUseSiteDiagnostics,
NamespaceOrTypeSymbol qualifierOpt)
{
var identifierValueText = node.Identifier.ValueText;
// If we are here in an error-recovery scenario, say, "goo<int, >(123);" then
// we might have an 'empty' simple name. In that case do not report an
// 'unable to find ""' error; we've already reported an error in the parser so
// just bail out with an error symbol.
if (string.IsNullOrWhiteSpace(identifierValueText))
{
return new ExtendedErrorTypeSymbol(
Compilation.Assembly.GlobalNamespace, identifierValueText, 0,
new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound));
}
var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, identifierValueText, 0, diagnostics);
if ((object)errorResult != null)
{
return errorResult;
}
var result = LookupResult.GetInstance();
LookupOptions options = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier());
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsSimpleName(result, qualifierOpt, identifierValueText, 0, basesBeingResolved, options, diagnose: true, useSiteDiagnostics: ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
Symbol bindingResult;
// If we were looking up the identifier "dynamic" at the topmost level and didn't find anything good,
// we actually have the type dynamic (assuming /langversion is at least 4).
if ((object)qualifierOpt == null &&
(node.Parent == null ||
node.Parent.Kind() != SyntaxKind.Attribute && // dynamic not allowed as an attribute type
SyntaxFacts.IsInTypeOnlyContext(node)) &&
node.Identifier.ValueText == "dynamic" &&
!IsViableType(result) &&
((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion >= MessageID.IDS_FeatureDynamic.RequiredVersion())
{
bindingResult = Compilation.DynamicType;
ReportUseSiteDiagnosticForDynamic(diagnostics, node);
}
else
{
bool wasError;
bindingResult = ResultSymbol(result, identifierValueText, 0, node, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options);
if (bindingResult.Kind == SymbolKind.Alias)
{
var aliasTarget = ((AliasSymbol)bindingResult).GetAliasTarget(basesBeingResolved);
if (aliasTarget.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)aliasTarget).ContainsDynamic())
{
ReportUseSiteDiagnosticForDynamic(diagnostics, node);
}
}
}
result.Free();
return bindingResult;
}
private void ReportUseSiteDiagnosticForDynamic(DiagnosticBag diagnostics, IdentifierNameSyntax node)
{
// Dynamic type might be bound in a declaration context where we need to synthesize the DynamicAttribute.
// Here we report the use site error (ERR_DynamicAttributeMissing) for missing DynamicAttribute type or it's constructors.
//
// BREAKING CHANGE: Native compiler reports ERR_DynamicAttributeMissing at emit time when synthesizing DynamicAttribute.
// Currently, in Roslyn we don't support reporting diagnostics while synthesizing attributes, these diagnostics are reported at bind time.
// Hence, we report this diagnostic here. Note that DynamicAttribute has two constructors, and either of them may be used while
// synthesizing the DynamicAttribute (see DynamicAttributeEncoder.Encode method for details).
// However, unlike the native compiler which reports use site diagnostic only for the specific DynamicAttribute constructor which is going to be used,
// we report it for both the constructors and also for boolean type (used by the second constructor).
// This is a breaking change for the case where only one of the two constructor of DynamicAttribute is missing, but we never use it for any of the synthesized DynamicAttributes.
// However, this seems like a very unlikely scenario and an acceptable break.
if (node.IsTypeInContextWhichNeedsDynamicAttribute())
{
if (!Compilation.HasDynamicEmitAttributes())
{
// CONSIDER: Native compiler reports error CS1980 for each syntax node which binds to dynamic type, we do the same by reporting a diagnostic here.
// However, this means we generate multiple duplicate diagnostics, when a single one would suffice.
// We may want to consider adding an "Unreported" flag to the DynamicTypeSymbol to suppress duplicate CS1980.
// CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference?
var info = new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, AttributeDescription.DynamicAttribute.FullName);
Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location);
}
this.GetSpecialType(SpecialType.System_Boolean, diagnostics, node);
}
}
// Gets the name lookup options for simple generic or non-generic name.
private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier)
{
if (SyntaxFacts.IsAttributeName(node))
{
// SPEC: By convention, attribute classes are named with a suffix of Attribute.
// SPEC: An attribute-name of the form type-name may either include or omit this suffix.
// SPEC: If an attribute class is found both with and without this suffix, an ambiguity
// SPEC: is present, and a compile-time error results. If the attribute-name is spelled
// SPEC: such that its right-most identifier is a verbatim identifier (§2.4.2), then only
// SPEC: an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved.
return isVerbatimIdentifier ? LookupOptions.VerbatimNameAttributeTypeOnly : LookupOptions.AttributeTypeOnly;
}
else
{
return LookupOptions.NamespacesOrTypesOnly;
}
}
private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList<Symbol> basesBeingResolved = null)
{
if (symbol.Kind == SymbolKind.Alias)
{
return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved);
}
return symbol;
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, DiagnosticBag diagnostics, SyntaxNode syntax, ConsList<Symbol> basesBeingResolved = null)
{
if (symbol.IsAlias)
{
AliasSymbol discarded;
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out discarded, diagnostics, syntax, basesBeingResolved));
}
return symbol;
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, DiagnosticBag diagnostics, SyntaxNode syntax, ConsList<Symbol> basesBeingResolved = null)
{
if (symbol.IsAlias)
{
return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(NonNullTypesContext, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved));
}
alias = null;
return symbol;
}
private Symbol UnwrapAlias(Symbol symbol, DiagnosticBag diagnostics, SyntaxNode syntax, ConsList<Symbol> basesBeingResolved = null)
{
AliasSymbol discarded;
return UnwrapAlias(symbol, out discarded, diagnostics, syntax, basesBeingResolved);
}
private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, DiagnosticBag diagnostics, SyntaxNode syntax, ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(syntax != null);
Debug.Assert(diagnostics != null);
if (symbol.Kind == SymbolKind.Alias)
{
alias = (AliasSymbol)symbol;
var result = alias.GetAliasTarget(basesBeingResolved);
var type = result as TypeSymbol;
if ((object)type != null)
{
// pass args in a value tuple to avoid allocating a closure
var args = (this, diagnostics, syntax);
type.VisitType((typePart, argTuple, isNested) =>
{
argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, argTuple.syntax, hasBaseReceiver: false);
return false;
}, args);
}
return result;
}
alias = null;
return symbol;
}
private NamedTypeSymbol BindGenericSimpleNamespaceOrTypeOrAliasSymbol(
GenericNameSyntax node,
DiagnosticBag diagnostics,
ConsList<Symbol> basesBeingResolved,
NamespaceOrTypeSymbol qualifierOpt)
{
// We are looking for a namespace, alias or type name and the user has given
// us an identifier followed by a type argument list. Therefore they
// must expect the result to be a generic type, and not a namespace or alias.
// The result of this method will therefore always be a type symbol of the
// correct arity, though it might have to be an error type.
// We might be asked to bind a generic simple name of the form "T<,,,>",
// which is only legal in the context of "typeof(T<,,,>)". If we are given
// no type arguments and we are not in such a context, we'll give an error.
// If we do have type arguments, then the result of this method will always
// be a generic type symbol constructed with the given type arguments.
// There are a number of possible error conditions. First, errors involving lookup:
//
// * Lookup could fail to find anything at all.
// * Lookup could find a type of the wrong arity
// * Lookup could find something but it is not a type.
//
// Second, we could be asked to resolve an unbound type T<,,,> when
// not in a context where it is legal to do so. Note that this is
// intended an improvement over the analysis performed by the
// native compiler; in the native compiler we catch bad uses of unbound
// types at parse time, not at semantic analysis time. That means that
// we end up giving confusing "unexpected comma" or "expected type"
// errors when it would be more informative to the user to simply
// tell them that an unbound type is not legal in this position.
//
// This also means that we can get semantic analysis of the open
// type in the IDE even in what would have been a syntax error case
// in the native compiler.
//
// We need a heuristic to deal with the situation where both kinds of errors
// are potentially in play: what if someone says "typeof(Bogus<>.Blah<int>)"?
// There are two errors there: first, that Bogus is not found, not a type,
// or not of the appropriate arity, and second, that it is illegal to make
// a partially unbound type.
//
// The heuristic we will use is that the former kind of error takes priority
// over the latter; if the meaning of "Bogus<>" cannot be successfully
// determined then there is no point telling the user that in addition,
// it is syntactically wrong. Moreover, at this point we do not know what they
// mean by the remainder ".Blah<int>" of the expression and so it seems wrong to
// deduce more errors from it.
var plainName = node.Identifier.ValueText;
SeparatedSyntaxList<TypeSyntax> typeArguments = node.TypeArgumentList.Arguments;
bool isUnboundTypeExpr = node.IsUnboundGenericName;
LookupOptions options = GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false);
NamedTypeSymbol unconstructedType = LookupGenericTypeName(
diagnostics, basesBeingResolved, qualifierOpt, node, plainName, node.Arity, options);
NamedTypeSymbol resultType;
if (isUnboundTypeExpr)
{
if (!IsUnboundTypeAllowed(node))
{
// If we already have an error type then skip reporting that the unbound type is illegal.
if (!unconstructedType.IsErrorType())
{
// error CS7003: Unexpected use of an unbound generic name
diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, node.Location);
}
resultType = unconstructedType.Construct(
UnboundArgumentErrorTypeSymbol.CreateTypeArguments(
unconstructedType.TypeParameters,
node.Arity,
errorInfo: null),
unbound: false);
}
else
{
resultType = unconstructedType.AsUnboundGenericType();
}
}
else
{
// It's not an unbound type expression, so we must have type arguments, and we have a
// generic type of the correct arity in hand (possibly an error type). Bind the type
// arguments and construct the final result.
resultType = ConstructNamedType(
unconstructedType,
node,
typeArguments,
BindTypeArguments(typeArguments, diagnostics, basesBeingResolved),
basesBeingResolved,
diagnostics);
}
if (options.IsAttributeTypeLookup())
{
// Generic type cannot be an attribute type.
// Parser error has already been reported, just wrap the result type with error type symbol.
Debug.Assert(unconstructedType.IsErrorType());
Debug.Assert(resultType.IsErrorType());
resultType = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(resultType), resultType,
LookupResultKind.NotAnAttributeType, errorInfo: null);
}
return resultType;
}
private NamedTypeSymbol LookupGenericTypeName(
DiagnosticBag diagnostics,
ConsList<Symbol> basesBeingResolved,
NamespaceOrTypeSymbol qualifierOpt,
GenericNameSyntax node,
string plainName,
int arity,
LookupOptions options)
{
var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics);
if ((object)errorResult != null)
{
return errorResult;
}
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsSimpleName(lookupResult, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, useSiteDiagnostics: ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
bool wasError;
Symbol lookupResultSymbol = ResultSymbol(lookupResult, plainName, arity, node, diagnostics, (basesBeingResolved != null), out wasError, qualifierOpt, options);
// As we said in the method above, there are three cases here:
//
// * Lookup could fail to find anything at all.
// * Lookup could find a type of the wrong arity
// * Lookup could find something but it is not a type.
//
// In the first two cases we will be given back an error type symbol of the appropriate arity.
// In the third case we will be given back the symbol -- say, a local variable symbol.
//
// In all three cases the appropriate error has already been reported. (That the
// type was not found, that the generic type found does not have that arity, that
// the non-generic type found cannot be used with a type argument list, or that
// the symbol found is not something that takes type arguments. )
// The first thing to do is to make sure that we have some sort of generic type in hand.
// (Note that an error type symbol is always a generic type.)
NamedTypeSymbol type = lookupResultSymbol as NamedTypeSymbol;
if ((object)type == null)
{
// We did a lookup with a generic arity, filtered to types and namespaces. If
// we got back something other than a type, there had better be an error info
// for us.
Debug.Assert(lookupResult.Error != null);
type = new ExtendedErrorTypeSymbol(
GetContainingNamespaceOrType(lookupResultSymbol),
ImmutableArray.Create<Symbol>(lookupResultSymbol),
lookupResult.Kind,
lookupResult.Error,
arity);
}
lookupResult.Free();
return type;
}
private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter(
CSharpSyntaxNode node,
NamespaceOrTypeSymbol qualifierOpt,
string name,
int arity,
DiagnosticBag diagnostics)
{
if (((object)qualifierOpt != null) && (qualifierOpt.Kind == SymbolKind.TypeParameter))
{
var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt);
diagnostics.Add(diagnosticInfo, node.Location);
return new ExtendedErrorTypeSymbol(this.Compilation, name, arity, diagnosticInfo, unreported: false);
}
return null;
}
private ImmutableArray<TypeSymbolWithAnnotations> BindTypeArguments(SeparatedSyntaxList<TypeSyntax> typeArguments, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved = null)
{
Debug.Assert(typeArguments.Count > 0);
var args = ArrayBuilder<TypeSymbolWithAnnotations>.GetInstance();
foreach (var argSyntax in typeArguments)
{
args.Add(BindTypeArgument(argSyntax, diagnostics, basesBeingResolved));
}
return args.ToImmutableAndFree();
}
private TypeSymbolWithAnnotations BindTypeArgument(TypeSyntax typeArgument, DiagnosticBag diagnostics, ConsList<Symbol> basesBeingResolved = null)
{
// Unsafe types can never be type arguments, but there's a special error code for that.
var binder = this.WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics);
var arg = typeArgument.Kind() == SyntaxKind.OmittedTypeArgument
? TypeSymbolWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance)
: binder.BindType(typeArgument, diagnostics, basesBeingResolved);
return arg;
}
/// <remarks>
/// Keep check and error in sync with ConstructBoundMethodGroupAndReportOmittedTypeArguments.
/// </remarks>
private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeSymbolWithAnnotations> typeArguments, DiagnosticBag diagnostics)
{
if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument))
{
// Note: lookup won't have reported this, since the arity was correct.
// CONSIDER: the text of this error message makes sense, but we might want to add a separate code.
Error(diagnostics, ErrorCode.ERR_BadArity, typeSyntax, type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count);
// If the syntax looks like an unbound generic type, then they probably wanted the definition.
// Give an error indicating that the syntax is incorrect and then use the definition.
// CONSIDER: we could construct an unbound generic type symbol, but that would probably be confusing
// outside a typeof.
return type;
}
else
{
// we pass an empty basesBeingResolved here because this invocation is not on any possible path of
// infinite recursion in binding base clauses.
return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, basesBeingResolved: null, diagnostics: diagnostics);
}
}
/// <remarks>
/// Keep check and error in sync with ConstructNamedTypeUnlessTypeArgumentOmitted.
/// </remarks>
private static BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments(
SyntaxNode syntax,
SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax,
ImmutableArray<TypeSymbolWithAnnotations> typeArguments,
BoundExpression receiver,
string plainName,
ArrayBuilder<Symbol> members,
LookupResult lookupResult,
BoundMethodGroupFlags methodGroupFlags,
bool hasErrors,
DiagnosticBag diagnostics)
{
if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument))
{
// Note: lookup won't have reported this, since the arity was correct.
// CONSIDER: the text of this error message makes sense, but we might want to add a separate code.
Error(diagnostics, ErrorCode.ERR_BadArity, syntax, plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count);
hasErrors = true;
}
Debug.Assert(members.Count > 0);
switch (members[0].Kind)
{
case SymbolKind.Method:
return new BoundMethodGroup(
syntax,
typeArguments,
receiver,
plainName,
members.SelectAsArray(s_toMethodSymbolFunc),
lookupResult,
methodGroupFlags,
hasErrors);
case SymbolKind.Property:
return new BoundPropertyGroup(
syntax,
members.SelectAsArray(s_toPropertySymbolFunc),
receiver,
lookupResult.Kind,
hasErrors);
default:
throw ExceptionUtilities.UnexpectedValue(members[0].Kind);
}
}
private static readonly Func<Symbol, MethodSymbol> s_toMethodSymbolFunc = s => (MethodSymbol)s;
private static readonly Func<Symbol, PropertySymbol> s_toPropertySymbolFunc = s => (PropertySymbol)s;
private NamedTypeSymbol ConstructNamedType(
NamedTypeSymbol type,
SyntaxNode typeSyntax,
SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax,
ImmutableArray<TypeSymbolWithAnnotations> typeArguments,
ConsList<Symbol> basesBeingResolved,
DiagnosticBag diagnostics)
{
Debug.Assert(!typeArguments.IsEmpty);
type = type.Construct(typeArguments);
if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type))
{
bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureStaticNullChecking);
var conversions = this.Conversions.WithNullability(includeNullability);
if (includeNullability && !ShouldCheckConstraintsNullability)
{
diagnostics.Add(new LazyNullableContraintChecksDiagnosticInfo(type, conversions, this.Compilation), typeSyntax.GetLocation());
conversions = conversions.WithNullability(includeNullability: false);
}
type.CheckConstraintsForNonTuple(conversions, typeSyntax, typeArgumentsSyntax, this.Compilation, basesBeingResolved, diagnostics);
}
type = (NamedTypeSymbol)TupleTypeSymbol.TransformToTupleIfCompatible(type);
return type;
}
/// <summary>
/// Check generic type constraints unless the type is used as part of a type or method
/// declaration. In those cases, constraints checking is handled by the caller.
/// </summary>
private bool ShouldCheckConstraints
{
get
{
return !this.Flags.Includes(BinderFlags.SuppressConstraintChecks);
}
}
private bool ShouldCheckConstraintsNullability
{
get
{
return ShouldCheckConstraints && !this.Flags.Includes(BinderFlags.AttributeArgument);
}
}
private NamespaceOrTypeSymbol BindQualifiedName(
ExpressionSyntax leftName,
SimpleNameSyntax rightName,
DiagnosticBag diagnostics,
ConsList<Symbol> basesBeingResolved,
bool suppressUseSiteDiagnostics)
{
var left = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol;
ReportDiagnosticsIfObsolete(diagnostics, left, leftName, hasBaseReceiver: false);
bool isLeftUnboundGenericType = left.Kind == SymbolKind.NamedType &&
((NamedTypeSymbol)left).IsUnboundGenericType;
if (isLeftUnboundGenericType)
{
// If left name bound to an unbound generic type,
// we want to perform right name lookup within
// left's original named type definition.
left = ((NamedTypeSymbol)left).OriginalDefinition;
}
// since the name is qualified, it cannot result in a using alias symbol, only a type or namespace
var right = this.BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left) as NamespaceOrTypeSymbol;
// If left name bound to an unbound generic type
// and right name bound to a generic type, we must
// convert right to an unbound generic type.
if (isLeftUnboundGenericType)
{
var namedTypeRight = right as NamedTypeSymbol;
if ((object)namedTypeRight != null && namedTypeRight.IsGenericType)
{
right = namedTypeRight.AsUnboundGenericType();
}
}
return right;
}
internal NamedTypeSymbol GetSpecialType(SpecialType typeId, DiagnosticBag diagnostics, SyntaxNode node)
{
return GetSpecialType(this.Compilation, typeId, node, diagnostics);
}
internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, DiagnosticBag diagnostics)
{
NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId);
Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found");
ReportUseSiteDiagnostics(typeSymbol, diagnostics, node);
return typeSymbol;
}
/// <summary>
/// This is a layer on top of the Compilation version that generates a diagnostic if the special
/// member isn't found.
/// </summary>
internal Symbol GetSpecialTypeMember(SpecialMember member, DiagnosticBag diagnostics, SyntaxNode syntax)
{
Symbol memberSymbol;
return TryGetSpecialTypeMember(this.Compilation, member, syntax, diagnostics, out memberSymbol)
? memberSymbol
: null;
}
internal static bool TryGetSpecialTypeMember<TSymbol>(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, DiagnosticBag diagnostics, out TSymbol symbol)
where TSymbol : Symbol
{
symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember);
if ((object)symbol == null)
{
MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember);
diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, descriptor.DeclaringTypeMetadataName, descriptor.Name);
return false;
}
var useSiteDiagnostic = symbol.GetUseSiteDiagnosticForSymbolOrContainingType();
if (useSiteDiagnostic != null)
{
Symbol.ReportUseSiteDiagnostic(useSiteDiagnostic, diagnostics, new SourceLocation(syntax));
}
return true;
}
/// <summary>
/// Reports use-site diagnostics for the specified symbol.
/// </summary>
/// <returns>
/// True if there was an error among the reported diagnostics
/// </returns>
internal static bool ReportUseSiteDiagnostics(Symbol symbol, DiagnosticBag diagnostics, SyntaxNode node)
{
DiagnosticInfo info = symbol.GetUseSiteDiagnostic();
return info != null && Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location);
}
/// <summary>
/// Reports use-site diagnostics for the specified symbol.
/// </summary>
/// <returns>
/// True if there was an error among the reported diagnostics
/// </returns>
internal static bool ReportUseSiteDiagnostics(Symbol symbol, DiagnosticBag diagnostics, Location location)
{
DiagnosticInfo info = symbol.GetUseSiteDiagnostic();
return info != null && Symbol.ReportUseSiteDiagnostic(info, diagnostics, location);
}
/// <summary>
/// This is a layer on top of the Compilation version that generates a diagnostic if the well-known
/// type isn't found.
/// </summary>
internal NamedTypeSymbol GetWellKnownType(WellKnownType type, DiagnosticBag diagnostics, SyntaxNode node)
{
NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type);
Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found");
ReportUseSiteDiagnostics(typeSymbol, diagnostics, node);
return typeSymbol;
}
/// <summary>
/// This is a layer on top of the Compilation version that generates a diagnostic if the well-known
/// type isn't found.
/// </summary>
internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type);
Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found");
HashSetExtensions.InitializeAndAdd(ref useSiteDiagnostics, typeSymbol.GetUseSiteDiagnostic());
return typeSymbol;
}
/// <summary>
/// Retrieves a well-known type member and reports diagnostics.
/// </summary>
/// <returns>Null if the symbol is missing.</returns>
internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, DiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false)
{
Debug.Assert((syntax != null) ^ (location != null));
DiagnosticInfo useSiteDiagnostic;
Symbol memberSymbol = GetWellKnownTypeMember(compilation, member, out useSiteDiagnostic, isOptional);
if (useSiteDiagnostic != null)
{
// report the diagnostic only for non-optional members:
Symbol.ReportUseSiteDiagnostic(useSiteDiagnostic, diagnostics, location ?? syntax.Location);
}
return memberSymbol;
}
internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out DiagnosticInfo diagnosticInfo, bool isOptional = false)
{
Symbol memberSymbol = compilation.GetWellKnownTypeMember(member);
if ((object)memberSymbol != null)
{
diagnosticInfo = memberSymbol.GetUseSiteDiagnosticForSymbolOrContainingType();
if (diagnosticInfo != null)
{
// Dev11 reports use-site diagnostics even for optional symbols that are found.
// We decided to silently ignore bad optional symbols.
// Report errors only for non-optional members:
if (isOptional)
{
var severity = diagnosticInfo.Severity;
// ignore warnings:
diagnosticInfo = null;
// if the member is optional and bad for whatever reason ignore it:
if (severity == DiagnosticSeverity.Error)
{
return null;
}
}
}
}
else if (!isOptional)
{
// member is missing
MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member);
diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name);
}
else
{
diagnosticInfo = null;
}
return memberSymbol;
}
private class ConsistentSymbolOrder : IComparer<Symbol>
{
public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder();
public int Compare(Symbol fst, Symbol snd)
{
if (snd == fst) return 0;
if ((object)fst == null) return -1;
if ((object)snd == null) return 1;
if (snd.Name != fst.Name) return string.CompareOrdinal(fst.Name, snd.Name);
if (snd.Kind != fst.Kind) return (int)fst.Kind - (int)snd.Kind;
int aLocationsCount = !snd.Locations.IsDefault ? snd.Locations.Length : 0;
int bLocationsCount = fst.Locations.Length;
if (aLocationsCount != bLocationsCount) return aLocationsCount - bLocationsCount;
if (aLocationsCount == 0 && bLocationsCount == 0) return Compare(fst.ContainingSymbol, snd.ContainingSymbol);
Location la = snd.Locations[0];
Location lb = fst.Locations[0];
if (la.IsInSource != lb.IsInSource) return la.IsInSource ? 1 : -1;
int containerResult = Compare(fst.ContainingSymbol, snd.ContainingSymbol);
if (!la.IsInSource) return containerResult;
if (containerResult == 0 && la.SourceTree == lb.SourceTree) return lb.SourceSpan.Start - la.SourceSpan.Start;
return containerResult;
}
}
// return the type or namespace symbol in a lookup result, or report an error.
internal Symbol ResultSymbol(
LookupResult result,
string simpleName,
int arity,
SyntaxNode where,
DiagnosticBag diagnostics,
bool suppressUseSiteDiagnostics,
out bool wasError,
NamespaceOrTypeSymbol qualifierOpt = null,
LookupOptions options = default(LookupOptions))
{
Debug.Assert(where != null);
Debug.Assert(diagnostics != null);
var symbols = result.Symbols;
wasError = false;
if (result.IsMultiViable)
{
if (symbols.Count > 1)
{
// gracefully handle symbols.Count > 2
symbols.Sort(ConsistentSymbolOrder.Instance);
var originalSymbols = symbols.ToImmutable();
for (int i = 0; i < symbols.Count; i++)
{
symbols[i] = UnwrapAlias(symbols[i], diagnostics, where);
}
BestSymbolInfo secondBest;
BestSymbolInfo best = GetBestSymbolInfo(symbols, out secondBest);
Debug.Assert(!best.IsNone);
Debug.Assert(!secondBest.IsNone);
if (best.IsFromCompilation && !secondBest.IsFromCompilation)
{
var srcSymbol = symbols[best.Index];
var mdSymbol = symbols[secondBest.Index];
//if names match, arities match, and containing symbols match (recursively), ...
if (srcSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat) ==
mdSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat))
{
if (srcSymbol.Equals(Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute)))
{
// Silently prefer the injected symbol
return originalSymbols[best.Index];
}
object arg0;
if (best.IsFromSourceModule)
{
SyntaxTree tree = srcSymbol.Locations.FirstOrNone().SourceTree;
arg0 = tree != null ? (object)tree.FilePath : MessageID.IDS_InjectedDeclaration.Localize();
}
else
{
Debug.Assert(best.IsFromAddedModule);
arg0 = srcSymbol.ContainingModule;
}
if (srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.NamedType)
{
// ErrorCode.WRN_SameFullNameThisNsAgg: The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'.
diagnostics.Add(ErrorCode.WRN_SameFullNameThisNsAgg, where.Location, originalSymbols,
arg0,
srcSymbol,
mdSymbol.ContainingAssembly,
mdSymbol);
return originalSymbols[best.Index];
}
else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.Namespace)
{
// ErrorCode.WRN_SameFullNameThisAggNs: The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'.
diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggNs, where.Location, originalSymbols,
arg0,
srcSymbol,
GetContainingAssembly(mdSymbol),
mdSymbol);
return originalSymbols[best.Index];
}
else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.NamedType)
{
// WRN_SameFullNameThisAggAgg: The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'.
diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggAgg, where.Location, originalSymbols,
arg0,
srcSymbol,
mdSymbol.ContainingAssembly,
mdSymbol);
return originalSymbols[best.Index];
}
else
{
// namespace would be merged with the source namespace:
Debug.Assert(!(srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.Namespace));
}
}
}
var first = symbols[best.Index];
var second = symbols[secondBest.Index];
Debug.Assert(originalSymbols[best.Index] != originalSymbols[secondBest.Index] || options.IsAttributeTypeLookup(),
"This kind of ambiguity is only possible for attributes.");
Debug.Assert(first != second || originalSymbols[best.Index] != originalSymbols[secondBest.Index],
"Why does the LookupResult contain the same symbol twice?");
CSDiagnosticInfo info;
bool reportError;
//if names match, arities match, and containing symbols match (recursively), ...
if (first != second &&
first.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat) ==
second.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat))
{
// suppress reporting the error if we found multiple symbols from source module
// since an error has already been reported from the declaration
reportError = !(best.IsFromSourceModule && secondBest.IsFromSourceModule);
if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType)
{
if (first.OriginalDefinition == second.OriginalDefinition)
{
// We imported different generic instantiations of the same generic type
// and have an ambiguous reference to a type nested in it
reportError = true;
// '{0}' is an ambiguous reference between '{1}' and '{2}'
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols,
new object[] {
(where as NameSyntax)?.ErrorDisplayName() ?? simpleName,
new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat),
new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) });
}
else
{
Debug.Assert(!best.IsFromCorLibrary);
// ErrorCode.ERR_SameFullNameAggAgg: The type '{1}' exists in both '{0}' and '{2}'
info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, originalSymbols,
new object[] { first.ContainingAssembly, first, second.ContainingAssembly });
// Do not report this error if the first is declared in source and the second is declared in added module,
// we already reported declaration error about this name collision.
// Do not report this error if both are declared in added modules,
// we will report assembly level declaration error about this name collision.
if (secondBest.IsFromAddedModule)
{
Debug.Assert(best.IsFromCompilation);
reportError = false;
}
else if (this.Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) &&
secondBest.IsFromCorLibrary)
{
// Ignore duplicate types from the cor library if necessary.
// (Specifically the framework assemblies loaded at runtime in
// the EE may contain types also available from mscorlib.dll.)
return first;
}
}
}
else if (first.Kind == SymbolKind.Namespace && second.Kind == SymbolKind.NamedType)
{
// ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}'
info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols,
new object[] { GetContainingAssembly(first), first, second.ContainingAssembly, second });
// Do not report this error if namespace is declared in source and the type is declared in added module,
// we already reported declaration error about this name collision.
if (best.IsFromSourceModule && secondBest.IsFromAddedModule)
{
reportError = false;
}
}
else if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.Namespace)
{
if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule)
{
// ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}'
info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols,
new object[] { GetContainingAssembly(second), second, first.ContainingAssembly, first });
}
else
{
Debug.Assert(secondBest.IsFromAddedModule);
// ErrorCode.ERR_SameFullNameThisAggThisNs: The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}'
object arg0;
if (best.IsFromSourceModule)
{
arg0 = first.Locations.First().SourceTree.FilePath;
}
else
{
Debug.Assert(best.IsFromAddedModule);
arg0 = first.ContainingModule;
}
ModuleSymbol arg2 = second.ContainingModule;
// Merged namespaces that span multiple modules don't have a containing module,
// so just use module with the smallest ordinal from the containing assembly.
if ((object)arg2 == null)
{
foreach (NamespaceSymbol ns in ((NamespaceSymbol)second).ConstituentNamespaces)
{
if (ns.ContainingAssembly == Compilation.Assembly)
{
ModuleSymbol module = ns.ContainingModule;
if ((object)arg2 == null || arg2.Ordinal > module.Ordinal)
{
arg2 = module;
}
}
}
}
Debug.Assert(arg2.ContainingAssembly == Compilation.Assembly);
info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, originalSymbols,
new object[] { arg0, first, arg2, second });
}
}
else if (first.Kind == SymbolKind.RangeVariable && second.Kind == SymbolKind.RangeVariable)
{
// We will already have reported a conflicting range variable declaration.
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols,
new object[] { first, second });
}
else
{
// TODO: this is not an appropriate error message here, but used as a fallback until the
// appropriate diagnostics are implemented.
// '{0}' is an ambiguous reference between '{1}' and '{2}'
//info = diagnostics.Add(ErrorCode.ERR_AmbigContext, location, readOnlySymbols,
// whereText,
// first,
// second);
// CS0229: Ambiguity between '{0}' and '{1}'
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols,
new object[] { first, second });
reportError = true;
}
}
else
{
Debug.Assert(originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name ||
originalSymbols[best.Index] != originalSymbols[secondBest.Index],
"Why was the lookup result viable if it contained non-equal symbols with the same name?");
reportError = true;
if (first is NamespaceOrTypeSymbol && second is NamespaceOrTypeSymbol)
{
if (options.IsAttributeTypeLookup() &&
first.Kind == SymbolKind.NamedType &&
second.Kind == SymbolKind.NamedType &&
originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name && // Use alias names, if available.
Compilation.IsAttributeType((NamedTypeSymbol)first) &&
Compilation.IsAttributeType((NamedTypeSymbol)second))
{
// SPEC: If an attribute class is found both with and without Attribute suffix, an ambiguity
// SPEC: is present, and a compile-time error results.
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, originalSymbols,
new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, first, second });
}
else
{
// '{0}' is an ambiguous reference between '{1}' and '{2}'
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols,
new object[] {
(where as NameSyntax)?.ErrorDisplayName() ?? simpleName,
new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat),
new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) });
}
}
else
{
// CS0229: Ambiguity between '{0}' and '{1}'
info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols,
new object[] { first, second });
}
}
wasError = true;
if (reportError)
{
diagnostics.Add(info, where.Location);
}
return new ExtendedErrorTypeSymbol(
GetContainingNamespaceOrType(originalSymbols[0]),
originalSymbols,
LookupResultKind.Ambiguous,
info,
arity);
}
else
{
// Single viable result.
var singleResult = symbols[0];
// Cannot reference System.Void directly.
var singleType = singleResult as TypeSymbol;
if ((object)singleType != null && singleType.PrimitiveTypeCode == Cci.PrimitiveTypeCode.Void && simpleName == "Void")
{
wasError = true;
var errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid);
diagnostics.Add(errorInfo, where.Location);
singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(singleResult), singleResult, LookupResultKind.NotReferencable, errorInfo); // UNDONE: Review resultkind.
}
// Check for bad symbol.
else
{
if (singleResult.Kind == SymbolKind.NamedType &&
((SourceModuleSymbol)this.Compilation.SourceModule).AnyReferencedAssembliesAreLinked)
{
// Complain about unembeddable types from linked assemblies.
Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)singleResult, where, diagnostics);
}
if (!suppressUseSiteDiagnostics)
{
wasError = ReportUseSiteDiagnostics(singleResult, diagnostics, where);
}
else if (singleResult.Kind == SymbolKind.ErrorType)
{
// We want to report ERR_CircularBase error on the spot to make sure
// that the right location is used for it.
var errorType = (ErrorTypeSymbol)singleResult;
if (errorType.Unreported)
{
DiagnosticInfo errorInfo = errorType.ErrorInfo;
if (errorInfo != null && errorInfo.Code == (int)ErrorCode.ERR_CircularBase)
{
wasError = true;
diagnostics.Add(errorInfo, where.Location);
singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorType), errorType.Name, errorType.Arity, errorInfo, unreported: false);
}
}
}
}
return singleResult;
}
}
// Below here is the error case; no viable symbols found (but maybe one or more non-viable.)
wasError = true;
if (result.Kind == LookupResultKind.Empty)
{
string aliasOpt = null;
SyntaxNode node = where;
while (node is ExpressionSyntax)
{
if (node.Kind() == SyntaxKind.AliasQualifiedName)
{
aliasOpt = ((AliasQualifiedNameSyntax)node).Alias.Identifier.ValueText;
break;
}
node = node.Parent;
}
CSDiagnosticInfo info = NotFound(where, simpleName, arity, (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, diagnostics, aliasOpt, qualifierOpt, options);
return new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, simpleName, arity, info);
}
Debug.Assert(symbols.Count > 0);
// Report any errors we encountered with the symbol we looked up.
if (!suppressUseSiteDiagnostics)
{
for (int i = 0; i < symbols.Count; i++)
{
ReportUseSiteDiagnostics(symbols[i], diagnostics, where);
}
}
// result.Error might be null if we have already generated parser errors,
// e.g. when generic name is used for attribute name.
if (result.Error != null &&
((object)qualifierOpt == null || qualifierOpt.Kind != SymbolKind.ErrorType)) // Suppress cascading.
{
diagnostics.Add(new CSDiagnostic(result.Error, where.Location));
}
if ((symbols.Count > 1) || (symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol) ||
result.Kind == LookupResultKind.NotATypeOrNamespace || result.Kind == LookupResultKind.NotAnAttributeType)
{
// Bad type or namespace (or things expected as types/namespaces) are packaged up as error types, preserving the symbols and the result kind.
// We do this if there are multiple symbols too, because just returning one would be losing important information, and they might
// be of different kinds.
return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), result.Kind, result.Error, arity);
}
else
{
// It's a single non-type-or-namespace; error was already reported, so just return it.
return symbols[0];
}
}
private static AssemblySymbol GetContainingAssembly(Symbol symbol)
{
// Merged namespaces that span multiple assemblies don't have a containing assembly,
// so just use the containing assembly of the first constituent.
return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly;
}
[Flags]
private enum BestSymbolLocation
{
None,
FromSourceModule,
FromAddedModule,
FromReferencedAssembly,
FromCorLibrary,
}
[DebuggerDisplay("Location = {_location}, Index = {_index}")]
private struct BestSymbolInfo
{
private readonly BestSymbolLocation _location;
private readonly int _index;
/// <summary>
/// Returns -1 if None.
/// </summary>
public int Index
{
get
{
return IsNone ? -1 : _index;
}
}
public bool IsFromSourceModule
{
get
{
return _location == BestSymbolLocation.FromSourceModule;
}
}
public bool IsFromAddedModule
{
get
{
return _location == BestSymbolLocation.FromAddedModule;
}
}
public bool IsFromCompilation
{
get
{
return (_location == BestSymbolLocation.FromSourceModule) || (_location == BestSymbolLocation.FromAddedModule);
}
}
public bool IsNone
{
get
{
return _location == BestSymbolLocation.None;
}
}
public bool IsFromCorLibrary
{
get
{
return _location == BestSymbolLocation.FromCorLibrary;
}
}
public BestSymbolInfo(BestSymbolLocation location, int index)
{
Debug.Assert(location != BestSymbolLocation.None);
_location = location;
_index = index;
}
/// <summary>
/// Prefers symbols from source module, then from added modules, then from referenced assemblies.
/// Returns true if values were swapped.
/// </summary>
public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second)
{
if (IsSecondLocationBetter(first._location, second._location))
{
BestSymbolInfo temp = first;
first = second;
second = temp;
return true;
}
return false;
}
/// <summary>
/// Returns true if the second is a better location than the first.
/// </summary>
public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation)
{
Debug.Assert(secondLocation != 0);
return (firstLocation == BestSymbolLocation.None) || (firstLocation > secondLocation);
}
}
/// <summary>
/// Prefer symbols from source module, then from added modules, then from referenced assemblies.
/// </summary>
private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder<Symbol> symbols, out BestSymbolInfo secondBest)
{
BestSymbolInfo first = default(BestSymbolInfo);
BestSymbolInfo second = default(BestSymbolInfo);
var compilation = this.Compilation;
for (int i = 0; i < symbols.Count; i++)
{
var symbol = symbols[i];
BestSymbolLocation location;
if (symbol.Kind == SymbolKind.Namespace)
{
location = BestSymbolLocation.None;
foreach (var ns in ((NamespaceSymbol)symbol).ConstituentNamespaces)
{
var current = GetLocation(compilation, ns);
if (BestSymbolInfo.IsSecondLocationBetter(location, current))
{
location = current;
if (location == BestSymbolLocation.FromSourceModule)
{
break;
}
}
}
}
else
{
location = GetLocation(compilation, symbol);
}
var third = new BestSymbolInfo(location, i);
if (BestSymbolInfo.Sort(ref second, ref third))
{
BestSymbolInfo.Sort(ref first, ref second);
}
}
Debug.Assert(!first.IsNone);
Debug.Assert(!second.IsNone);
secondBest = second;
return first;
}
private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol)
{
var containingAssembly = symbol.ContainingAssembly;
if (containingAssembly == compilation.SourceAssembly)
{
return (symbol.ContainingModule == compilation.SourceModule) ?
BestSymbolLocation.FromSourceModule :
BestSymbolLocation.FromAddedModule;
}
else
{
return (containingAssembly == containingAssembly.CorLibrary) ?
BestSymbolLocation.FromCorLibrary :
BestSymbolLocation.FromReferencedAssembly;
}
}
/// <remarks>
/// This is only intended to be called when the type isn't found (i.e. not when it is found but is inaccessible, has the wrong arity, etc).
/// </remarks>
private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, DiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options)
{
var location = where.Location;
// Lookup totally ignores type forwarders, but we want the type lookup diagnostics
// to distinguish between a type that can't be found and a type that is only present
// as a type forwarder. We'll look for type forwarders in the containing and
// referenced assemblies and report more specific diagnostics if they are found.
AssemblySymbol forwardedToAssembly;
string fullName;
// for attributes, suggest both, but not for verbatim name
if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup())
{
// just recurse one level, so cheat and OR verbatim name option :)
NotFound(where, simpleName, arity, whereText + "Attribute", diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly);
}
if ((object)qualifierOpt != null)
{
if (qualifierOpt.IsType)
{
var errorQualifier = qualifierOpt as ErrorTypeSymbol;
if ((object)errorQualifier != null && errorQualifier.ErrorInfo != null)
{
return (CSDiagnosticInfo)errorQualifier.ErrorInfo;
}
return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt);
}
else
{
Debug.Assert(qualifierOpt.IsNamespace);
bool qualifierIsCompilationGlobalNamespace = ReferenceEquals(qualifierOpt, Compilation.GlobalNamespace);
fullName = MetadataHelpers.ComposeAritySuffixedMetadataName(simpleName, arity);
if (!qualifierIsCompilationGlobalNamespace)
{
fullName = qualifierOpt.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) + "." + fullName;
}
forwardedToAssembly = GetForwardedToAssembly(fullName, arity, diagnostics, location);
if (qualifierIsCompilationGlobalNamespace)
{
Debug.Assert(aliasOpt == null || aliasOpt == SyntaxFacts.GetText(SyntaxKind.GlobalKeyword));
return (object)forwardedToAssembly == null
? diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText, qualifierOpt)
: diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly);
}
else
{
object container = qualifierOpt;
// If there was an alias (e.g. A::C) and the given qualifier is the global namespace of the alias,
// then use the alias name in the error message, since it's more helpful than "<global namespace>".
if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace)
{
container = aliasOpt;
}
return (object)forwardedToAssembly == null
? diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, container)
: diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, container, forwardedToAssembly);
}
}
}
if (options == LookupOptions.NamespaceAliasesOnly)
{
return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText);
}
if ((where as IdentifierNameSyntax)?.Identifier.Text == "var" && !options.IsAttributeTypeLookup())
{
var code = (where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound;
return diagnostics.Add(code, location);
}
fullName = MetadataHelpers.ComposeAritySuffixedMetadataName(simpleName, arity);
forwardedToAssembly = GetForwardedToAssembly(fullName, arity, diagnostics, location);
return (object)forwardedToAssembly == null
? diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText)
: diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly);
}
/// <summary>
/// Look for a type forwarder for the given type in the containing assembly and any referenced assemblies.
/// If one is found, search again in the target assembly. Return the last assembly in the chain.
/// </summary>
/// <param name="fullName">The metadata name of the (potentially) forwarded type, including the arity (if non-zero).</param>
/// <param name="arity">The arity of the forwarded type.</param>
/// <param name="diagnostics">Will be used to report non-fatal errors during look up.</param>
/// <param name="location">Location to report errors on.</param>
/// <returns></returns>
/// <remarks>
/// Since this method is intended to be used for error reporting, it stops as soon as it finds
/// any type forwarder (or an error to report). It does not check other assemblies for consistency or better results.
/// </remarks>
private AssemblySymbol GetForwardedToAssembly(string fullName, int arity, DiagnosticBag diagnostics, Location location)
{
Debug.Assert(arity == 0 || fullName.EndsWith("`" + arity, StringComparison.Ordinal));
// If we are in the process of binding assembly level attributes, we might get into an infinite cycle
// if any of the referenced assemblies forwards type to this assembly. Since forwarded types
// are specified through assembly level attributes, an attempt to resolve the forwarded type
// might require us to examine types forwarded by this assembly, thus binding assembly level
// attributes again. And the cycle continues.
// So, we won't do the analysis in this case, at the expense of better diagnostics.
if ((this.Flags & BinderFlags.InContextualAttributeBinder) != 0)
{
var current = this;
do
{
var contextualAttributeBinder = current as ContextualAttributeBinder;
if (contextualAttributeBinder != null)
{
if ((object)contextualAttributeBinder.AttributeTarget != null &&
contextualAttributeBinder.AttributeTarget.Kind == SymbolKind.Assembly)
{
return null;
}
break;
}
current = current.Next;
}
while (current != null);
}
// NOTE: This won't work if the type isn't using CLS-style generic naming (i.e. `arity), but this code is
// only intended to improve diagnostic messages, so false negatives in corner cases aren't a big deal.
var metadataName = MetadataTypeName.FromFullName(fullName, useCLSCompliantNameArityEncoding: true, forcedArity: arity);
var containingAssembly = this.Compilation.Assembly;
// This method is only called after lookup has failed, so the containing (source!) assembly can't
// have a forwarder to another assembly.
NamedTypeSymbol forwardedType = null;
foreach (var referencedAssembly in containingAssembly.Modules[0].GetReferencedAssemblySymbols())
{
forwardedType = referencedAssembly.TryLookupForwardedMetadataType(ref metadataName);
if ((object)forwardedType != null)
{
break;
}
}
if ((object)forwardedType != null)
{
if (forwardedType.Kind == SymbolKind.ErrorType)
{
DiagnosticInfo diagInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo;
if (diagInfo.Code == (int)ErrorCode.ERR_CycleInTypeForwarder)
{
Debug.Assert((object)forwardedType.ContainingAssembly != null, "How did we find a cycle if there was no forwarding?");
diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, forwardedType.ContainingAssembly.Name);
}
else if (diagInfo.Code == (int)ErrorCode.ERR_TypeForwardedToMultipleAssemblies)
{
diagnostics.Add(diagInfo, location);
return null; // Cannot determine a suitable forwarding assembly
}
}
return forwardedType.ContainingAssembly;
}
return null;
}
internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag diagnostics, Location locationOpt = null)
{
return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, locationOpt ?? syntax.GetLocation());
}
internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag diagnostics, Location location)
{
CSDiagnosticInfo error = GetFeatureAvailabilityDiagnosticInfo(tree, feature);
if (error is null)
{
return true;
}
diagnostics.Add(new CSDiagnostic(error, location));
return false;
}
private static CSDiagnosticInfo GetFeatureAvailabilityDiagnosticInfo(SyntaxTree tree, MessageID feature)
{
CSharpParseOptions options = (CSharpParseOptions)tree.Options;
if (options.IsFeatureEnabled(feature))
{
return null;
}
string requiredFeature = feature.RequiredFeature();
if (requiredFeature != null)
{
return new CSDiagnosticInfo(ErrorCode.ERR_FeatureIsExperimental, feature.Localize(), requiredFeature);
}
LanguageVersion availableVersion = options.LanguageVersion;
LanguageVersion requiredVersion = feature.RequiredVersion();
if (requiredVersion > availableVersion)
{
return new CSDiagnosticInfo(availableVersion.GetErrorCode(), feature.Localize(), new CSharpRequiredLanguageVersion(requiredVersion));
}
return null;
}
}
}
| 49.868758 | 257 | 0.560791 | [
"Apache-2.0"
] | Mongooz/roslyn | src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs | 112,856 | C# |
namespace More.Composition.Hosting
{
using More.ComponentModel;
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using static System.StringComparison;
internal sealed class ViewModelSpecification : SpecificationBase<Type>
{
private const string ViewModel = "ViewModel";
private static bool MatchesTypeNameOrNamespace( TypeInfo typeInfo )
{
Contract.Requires( typeInfo != null );
return typeInfo.Name.Contains( ViewModel, OrdinalIgnoreCase )
|| typeInfo.Namespace.Contains( ViewModel, OrdinalIgnoreCase );
}
public override bool IsSatisfiedBy( Type item )
{
if ( item == null )
return false;
var ti = item.GetTypeInfo();
return ti.IsPublic && ti.IsClass && !ti.IsAbstract && MatchesTypeNameOrNamespace( ti );
}
}
}
| 29.870968 | 99 | 0.62959 | [
"MIT"
] | pashcovich/More | src/Hosting/Hosting.Windows.Shared/Composition.Hosting/ViewModelSpecification.cs | 928 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using Microsoft.Xna.Framework;
namespace LBE.Assets
{
public class AssetInstantiationResult
{
public Object Instance = null;
public IEnumerable<IAssetDependency> Dependencies = Enumerable.Empty<IAssetDependency>();
}
public class AssetInstanciator
{
public static AssetInstantiationResult CreateInstance(AssetDefinition assetDef, Type baseType)
{
var dependencies = new List<IAssetDependency>();
Type assetType = baseType;
if (assetDef.Type != null)
assetType = ResolveType(assetDef.Type);
if (assetType == null)
return null;
//Make sure 'T' can be assigned from the assset type
if (!baseType.IsAssignableFrom(assetType))
{
Engine.Log.Exception(String.Format("Can't assign type {0} from {1} in asset \"{2}\"", baseType.Name, assetType.Name, assetDef.Name));
return null;
}
//Instantiate and initialize the new object
if (assetType.IsArray)
{
Type arrayType = assetType.GetElementType();
Array array = Array.CreateInstance(arrayType, assetDef.Fields.Values.Count);
int idx = 0;
foreach (Object element in assetDef.Fields.Values)
{
var resolveResult = ResolveValue(element, arrayType);
array.SetValue(resolveResult.Instance, idx++);
dependencies.AddRange(resolveResult.Dependencies);
}
return new AssetInstantiationResult() { Instance = array, Dependencies = dependencies };
}
else
{
Object newObject = Activator.CreateInstance(assetType);
//Set field values for the new object
foreach (FieldInfo fieldInfo in assetType.GetFields())
{
if (assetDef.Fields.Keys.Contains(fieldInfo.Name))
{
var resolveResult = ResolveValue(assetDef.Fields[fieldInfo.Name], fieldInfo.FieldType);
if (fieldInfo.FieldType.IsAssignableFrom(resolveResult.Instance.GetType()))
{
fieldInfo.SetValue(newObject, resolveResult.Instance);
dependencies.AddRange(resolveResult.Dependencies);
}
else
{
TypeConverter conv = TypeDescriptor.GetConverter(fieldInfo.FieldType);
if (conv.CanConvertFrom(resolveResult.Instance.GetType()))
{
object value = conv.ConvertFrom(resolveResult.Instance);
fieldInfo.SetValue(newObject, value);
dependencies.AddRange(resolveResult.Dependencies);
};
}
}
}
//Set property values for the new object
foreach (PropertyInfo propInfo in assetType.GetProperties())
{
if (assetDef.Fields.Keys.Contains(propInfo.Name))
{
var resolveResult = ResolveValue(assetDef.Fields[propInfo.Name], propInfo.PropertyType);
propInfo.SetValue(newObject, resolveResult.Instance, null);
if (propInfo.PropertyType.IsAssignableFrom(resolveResult.Instance.GetType()))
{
propInfo.SetValue(newObject, resolveResult.Instance, null);
dependencies.AddRange(resolveResult.Dependencies);
}
else
{
TypeConverter conv = TypeDescriptor.GetConverter(propInfo.PropertyType);
if (conv.CanConvertFrom(resolveResult.Instance.GetType()))
{
object value = conv.ConvertFrom(resolveResult.Instance);
propInfo.SetValue(value, value, null);
dependencies.AddRange(resolveResult.Dependencies);
};
}
}
}
return new AssetInstantiationResult() { Instance = newObject, Dependencies = dependencies };
}
}
static AssetInstantiationResult ResolveValue(Object value, Type type)
{
//Value is a reference to an existing asset
if (value is AssetReference)
{
try
{
MethodInfo resolveRefMethod = typeof(AssetInstanciator).GetMethod("ResolveReference");
resolveRefMethod = resolveRefMethod.MakeGenericMethod(type);
return resolveRefMethod.Invoke(null, new Object[] { value }) as AssetInstantiationResult;
}
catch (System.Exception ex)
{
//If an exception occur during the Invoke() call, it will be rapper in a TargetInvocationException
//Just get the inner exception
Engine.Log.Exception(ex.InnerException);
}
return null;
}
//Value is a nested table
else if (value is AssetDefinition)
{
return CreateInstance((AssetDefinition)value, type);
}
else
{
//Convert to enum type
if (type.IsEnum)
{
return new AssetInstantiationResult() { Instance = Enum.Parse(type, value as String, true) };
}
else if (type == typeof(int))
{
return new AssetInstantiationResult() { Instance = Convert.ToInt32(value) };
}
else if (type == typeof(float))
{
return new AssetInstantiationResult() { Instance = Convert.ToSingle(value) };
}
else if (type == typeof(bool))
{
return new AssetInstantiationResult() { Instance = Convert.ToBoolean(value) };
}
else if (type == typeof(byte))
{
return new AssetInstantiationResult() { Instance = Convert.ToByte(value) };
}
else if (type == typeof(Vector2))
{
return new AssetInstantiationResult() { Instance = Vector2.Zero };
}
else
{
return new AssetInstantiationResult() { Instance = value };
}
}
}
public static AssetInstantiationResult ResolveReference<T>(AssetReference reference)
{
Type refType = typeof(T);
if (refType.IsGenericType)
{
var genericParams = refType.GetGenericArguments();
var genericDef = refType.GetGenericTypeDefinition();
if (genericDef == typeof(Asset<int>).GetGenericTypeDefinition())
{
MethodInfo resolveRefMethod = typeof(AssetManager).GetMethod("GetAsset");
resolveRefMethod = resolveRefMethod.MakeGenericMethod(genericParams[0]);
var genericAsset = resolveRefMethod.Invoke(Engine.AssetManager, new Object[] { reference.Path, true });
return new AssetInstantiationResult() { Instance = genericAsset, Dependencies = new IAssetDependency[] { genericAsset as IAssetDependency } };
}
}
Asset<T> asset = Engine.AssetManager.GetAsset<T>(reference.Path);
return new AssetInstantiationResult() { Instance = asset.Content, Dependencies = new IAssetDependency[] { asset } };
}
static Type ResolveType(String typeName)
{
return Engine.AssetManager.TypeDatabase.GetType(typeName);
}
}
}
| 44.052083 | 162 | 0.519863 | [
"MIT"
] | CollectifBlueprint/GoalRush | Project/02 - Engine/LittleBigEngine/Assets/AssetInstanciator.cs | 8,460 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
namespace trabalho1.Properties {
using System;
/// <summary>
/// Uma classe de recurso de tipo de alta segurança, para pesquisar cadeias de caracteres localizadas etc.
/// </summary>
// Essa classe foi gerada automaticamente pela classe StronglyTypedResourceBuilder
// através de uma ferramenta como ResGen ou Visual Studio.
// Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente
// com a opção /str, ou recrie o projeto do VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Retorna a instância de ResourceManager armazenada em cache usada por essa classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("trabalho1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Substitui a propriedade CurrentUICulture do thread atual para todas as
/// pesquisas de recursos que usam essa classe de recurso de tipo de alta segurança.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap _lock {
get {
object obj = ResourceManager.GetObject("lock", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap conecte_se {
get {
object obj = ResourceManager.GetObject("conecte-se", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap enter {
get {
object obj = ResourceManager.GetObject("enter", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap user {
get {
object obj = ResourceManager.GetObject("user", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 42.269231 | 175 | 0.591219 | [
"MIT"
] | GabrielAlonso1/Trabalho-para-enviar-git | trabalho1/trabalho1/Properties/Resources.Designer.cs | 4,413 | C# |
#if UNITY_IOS
using System;
using System.Runtime.InteropServices;
namespace UnityEngine.Monetization
{
public class IosNativePromoAdapter : INativePromoAdapter
{
[DllImport("__Internal")]
static extern IntPtr UnityMonetizationCreateNativePromoAdapter(IntPtr pPlacementContent);
[DllImport("__Internal")]
static extern void UnityMonetizationReleaseNativePromoAdapter(IntPtr pNativePromoAdapter);
[DllImport("__Internal")]
static extern void UnityMonetizationNativePromoAdapterOnShown(IntPtr pNativePromoAdapter, int showType);
[DllImport("__Internal")]
static extern void UnityMonetizationNativePromoAdapterOnClicked(IntPtr pNativePromoAdapter);
[DllImport("__Internal")]
static extern void UnityMonetizationNativePromoAdapterOnClosed(IntPtr pNativePromoAdapter);
private PromoAdPlacementContent placementContent { get; }
private IntPtr nativePromoAdapter { get; }
public IosNativePromoAdapter(PromoAdPlacementContent placementContent)
{
metadata = placementContent.metadata;
var operations = placementContent.placementContentOperations as IosPlacementContentOperations;
if (operations != null)
{
var ptr = operations.placementContentPtr;
this.placementContent = placementContent;
nativePromoAdapter = UnityMonetizationCreateNativePromoAdapter(ptr);
}
}
~IosNativePromoAdapter()
{
UnityMonetizationReleaseNativePromoAdapter(nativePromoAdapter);
}
public PromoMetadata metadata { get; }
public void OnShown()
{
OnShown(PromoShowType.Full);
}
public void OnShown(PromoShowType type)
{
UnityMonetizationNativePromoAdapterOnShown(nativePromoAdapter, (int)type);
}
public void OnClosed()
{
UnityMonetizationNativePromoAdapterOnClosed(nativePromoAdapter);
}
public void OnClicked()
{
UnityMonetizationNativePromoAdapterOnClicked(nativePromoAdapter);
}
}
}
#endif
| 35.777778 | 113 | 0.663265 | [
"MIT"
] | Tpierga/2I_ProjetDetectionIA | Projet_Detection_IA/Library/PackageCache/com.unity.ads@3.4.5/Runtime/Monetization/IosNativePromoAdapter.cs | 2,254 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.