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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO" /> struct.</summary>
public static unsafe class D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFOTests
{
/// <summary>Validates that the <see cref="D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO>(), Is.EqualTo(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO)));
}
/// <summary>Validates that the <see cref="D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO), Is.EqualTo(24));
}
}
}
| 47.527778 | 172 | 0.732905 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/d3d12/D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFOTests.cs | 1,713 | C# |
using System;
using System.Net;
using xGame.Memory;
namespace xGame.Transport
{
public interface ITransportManager
{
ITransport CreateTransport(string ip, int port);
ITransport CreateTransport(string ip, int port, int connectTimeout);
ITransport CreateTransport(string ip, int port, int connectTimeout, int sendTimeout, int receiveTimeout);
ITransport CreateTransport(string ip, int port, int connectTimeout, int sendTimeout, int receiveTimeout, int heartBeatInterval);
ITransport CreateTransport(string ip, int port, int connectTimeout, int sendTimeout, int receiveTimeout, int heartBeatInterval, int heartBeatTimeout);
ITransport CreateTransport(int port);
ITransport CreateTransport(int port, int sendTimeout, int receiveTimeout);
ITransport CreateTransport(int port, int sendTimeout, int receiveTimeout, int heartBeatInterval);
ITransport CreateTransport(int port, int sendTimeout, int receiveTimeout, int heartBeatInterval, int heartBeatTimeout);
void RemoveTransport(ITransport transport);
void RemoveTransport(string ip, int port);
void RemoveTransport(IPEndPoint endPoint);
void RemoveAllTransport();
ITransport GetTransport(int id);
ITransport GetTransport(string ip, int port);
ITransport GetTransport(IPEndPoint endPoint);
void WriteWithTransport(string ip, int port, IMemory data);
void WriteWithTransport(IPEndPoint endPoint, IMemory data);
void WriteWithTransport(int id, IMemory data);
void WriteAllTranspoet(IMemory data);
}
} | 33.346939 | 158 | 0.734394 | [
"MIT"
] | NullFlyGames/xGame | xGame/Transport/ITransportManager.cs | 1,634 | C# |
//
// VR-Studies
// Created by miuccie miurror on 11/04/2016.
// Copyright 2016 Yumemi.Inc / miuccie miurror
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PenSample : GrabControllerTarget {
public Color inkColor;
LineRenderer lineRenderer;
List<Vector3> points = new List<Vector3>();
void Start () {
lineRenderer = gameObject.AddComponent<LineRenderer> ();
lineRenderer.SetWidth( 0.02f, 0.02f );
//lineRenderer.material = new Material(Shader.Find("Particles/Alpha Blended"));
lineRenderer.material = new Material(Shader.Find("Particles/Additive (Soft)"));
lineRenderer.SetColors ( inkColor, inkColor );
}
void Update () {
// ラインレンダラーで線を描く
if( base.isGrabbed ){
var pt = transform.position + new Vector3( 0.03f, 0, -0.01f );
points.Add ( pt );
lineRenderer.SetVertexCount( points.Count );
lineRenderer.SetPositions( points.ToArray() );
}
}
}
| 24.684211 | 81 | 0.711087 | [
"MIT"
] | yumemi-inc/vr-studies | vol1/VR-studies/Assets/VR-studies/2_VR-controller/2-3_GrabController/PenSample.cs | 966 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using ServerlessWorkflow.Sdk.Models;
using Synapse.Domain.Models;
using Synapse.Runner.Application.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Synapse.Runner.Application.Services.Processors
{
/// <summary>
/// Represents a <see cref="IWorkflowActivityProcessor"/> used to process <see cref="EventStateDefinition"/>s
/// </summary>
public class EventStateProcessor
: StateProcessor<EventStateDefinition>
{
/// <summary>
/// Initializes a new <see cref="EventStateProcessor"/>
/// </summary>
/// <param name="loggerFactory">The service used to create <see cref="ILogger"/>s</param>
/// <param name="executionContext">The current <see cref="IWorkflowExecutionContext"/></param>
/// <param name="activityProcessorFactory">The service used to create <see cref="IWorkflowActivityProcessor"/>s</param>
/// <param name="options">The service used to access the current <see cref="ApplicationOptions"/></param>
/// <param name="activity">The <see cref="V1WorkflowActivity"/> to process</param>
/// <param name="state">The <see cref="EventStateDefinition"/> to process</param>
public EventStateProcessor(ILoggerFactory loggerFactory, IWorkflowExecutionContext executionContext, IWorkflowActivityProcessorFactory activityProcessorFactory, IOptions<ApplicationOptions> options, V1WorkflowActivity activity, EventStateDefinition state)
: base(loggerFactory, executionContext, activityProcessorFactory, options, activity, state)
{
}
/// <inheritdoc/>
protected override IWorkflowActivityProcessor CreateProcessorFor(V1WorkflowActivity activity)
{
EventStateTriggerProcessor processor = base.CreateProcessorFor(activity) as EventStateTriggerProcessor;
processor.SubscribeAsync
(
async result => await this.OnTriggerResultAsync(processor, result, this.CancellationTokenSource.Token),
async ex => await this.OnErrorAsync(ex, this.CancellationTokenSource.Token),
async () => await this.OnTriggerCompletedAsync(processor, this.CancellationTokenSource.Token)
);
return processor;
}
/// <inheritdoc/>
protected override async Task InitializeAsync(CancellationToken cancellationToken)
{
if (this.Activity.Status <= V1WorkflowActivityStatus.Initializing)
{
foreach (EventStateTriggerDefinition trigger in this.State.Triggers)
{
await this.ExecutionContext.CreateActivityAsync(V1WorkflowActivity.EventStateTrigger(this.ExecutionContext.Instance, this.State, trigger, this.Activity.Data, this.Activity), cancellationToken);
}
}
foreach (V1WorkflowActivity childActivity in await this.ExecutionContext.ListActiveChildActivitiesAsync(this.Activity, cancellationToken))
{
this.CreateProcessorFor(childActivity);
}
}
/// <inheritdoc/>
protected override async Task ProcessAsync(CancellationToken cancellationToken)
{
foreach (IWorkflowActivityProcessor childProcessor in this.Processors.ToList())
{
await childProcessor.ProcessAsync(cancellationToken);
}
}
/// <summary>
/// Handles the next <see cref="IWorkflowActivityProcessor"/>'s <see cref="V1WorkflowExecutionResult"/>
/// </summary>
/// <param name="processor">The <see cref="IWorkflowActivityProcessor"/> that returned the <see cref="V1WorkflowExecutionResult"/></param>
/// <param name="result">The <see cref="V1WorkflowExecutionResult"/> to handle</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/></param>
/// <returns>A new awaitable <see cref="Task"/></returns>
protected virtual async Task OnTriggerResultAsync(IWorkflowActivityProcessor processor, V1WorkflowExecutionResult result, CancellationToken cancellationToken)
{
using(await this.Lock.LockAsync(cancellationToken))
{
if (this.Activity.Status == V1WorkflowActivityStatus.Executed)
return;
List<V1WorkflowActivity> childActivities = (await this.ExecutionContext.ListChildActivitiesAsync(this.Activity, true, cancellationToken))
.Where(p => p.Type == V1WorkflowActivityType.EventStateTrigger && p.Status == V1WorkflowActivityStatus.Executed)
.ToList();
if (this.State.Exclusive
|| childActivities.Count == this.State.Triggers.Count)
{
JObject output = new();
foreach (V1WorkflowActivity childPointer in childActivities
.Where(p => p.Result.Type == V1WorkflowExecutionResultType.Next && p.Result.Output != null))
{
output.Merge(childPointer.Result.Output);
}
await this.OnResultAsync(new V1WorkflowExecutionResult(V1WorkflowExecutionResultType.Next, output), cancellationToken);
await this.OnCompletedAsync(cancellationToken);
}
}
}
/// <summary>
/// Handles the completion of the specified <see cref="IWorkflowActivityProcessor"/>
/// </summary>
/// <param name="processor">The <see cref="IWorkflowActivityProcessor"/> to handle the completion of</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/></param>
/// <returns>A new awaitable <see cref="Task"/></returns>
protected virtual Task OnTriggerCompletedAsync(IWorkflowActivityProcessor processor, CancellationToken cancellationToken)
{
this.Processors.TryRemove(processor);
processor.Dispose();
return Task.CompletedTask;
}
}
}
| 51.04918 | 263 | 0.658157 | [
"Apache-2.0"
] | manuelstein/synapse | src/Runner/Synapse.Runner.Application/Services/Processors/EventStateProcessor.cs | 6,230 | C# |
using System;
using System.Net;
namespace NewLife.Data
{
/// <summary>数据帧接口</summary>
public interface IData
{
#region 属性
/// <summary>原始数据包</summary>
Packet Packet { get; set; }
/// <summary>远程地址</summary>
IPEndPoint Remote { get; set; }
/// <summary>解码后的消息</summary>
Object Message { get; set; }
/// <summary>用户自定义数据</summary>
Object UserState { get; set; }
#endregion
}
} | 21.608696 | 40 | 0.521127 | [
"MIT"
] | NewLifeX/X | NewLife.Core/Data/IData.cs | 557 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Melville.Lists.Caches
{
public sealed class SimpleCache<TKey, TResult>
{
private readonly int size;
private readonly Func<TKey, TResult> create;
private List<(TKey, TResult)> data;
public SimpleCache(Func<TKey, TResult> create) : this(int.MaxValue, create)
{
// do nothing
}
public IEnumerable<TResult> CachedItems => data.Select(i => i.Item2);
public SimpleCache(int size, Func<TKey, TResult> create)
{
this.size = size;
this.create = create;
// if size is maxInt then the class is a buffer, a cache that grows without bound.
data = size == int.MaxValue ? new List<(TKey, TResult)>() : new List<(TKey, TResult)>(size);
}
private bool TryGet(TKey key, out (TKey, TResult) result)
{
foreach (var candidate in data.Where(candidate => candidate.Item1?.Equals(key) ?? false))
{
result = candidate;
return true;
}
result = default;
return false;
}
public TResult Get(TKey key)
{
lock (data)
{
var item = GetOrCreateRequestedItem(key);
data.Insert(0, item);
return item.Item2;
}
}
private (TKey, TResult) GetOrCreateRequestedItem(TKey key)
{
if (TryGet(key, out var item))
{
data.Remove(item);
return item;
}
else
{
MakeSpaceForNewItem();
return (key, create(key));
}
}
private void MakeSpaceForNewItem()
{
if (data.Count >= size)
{
RemoveItem(data[data.Count - 1]);
}
}
public void Dump()
{
lock (data)
{
data.Clear();
}
}
public void Forget(TKey key)
{
lock (data)
{
if (TryGet(key, out var item))
{
RemoveItem(item);
};
}
}
private void RemoveItem((TKey, TResult) itemToRemove)
{
(itemToRemove.Item2 as IDisposable)?.Dispose();
data.Remove(itemToRemove);
}
public void Rekey(Func<TKey, TKey> func)
{
lock (data)
{
data = data.Select(i => (func(i.Item1), i.Item2)).ToList();
}
}
public void Clear()
{
lock (data)
{
data.ForEach(i => (i.Item2 as IDisposable)?.Dispose());
data.Clear();
}
}
}
}
| 20.672414 | 98 | 0.552544 | [
"MIT"
] | DrJohnMelville/Melville | src/Melville.Lists/Caches/SimpleCache.cs | 2,400 | C# |
using System;
using StandardUtils.Helpers;
using StandardUtils.Models.Requests;
namespace Translation.Common.Models.Requests.Label.LabelTranslation
{
public sealed class LabelTranslationReadRequest : BaseAuthenticatedRequest
{
public Guid LabelTranslationUid { get; }
public LabelTranslationReadRequest(long currentUserId, Guid labelTranslationUid) : base(currentUserId)
{
if (labelTranslationUid.IsEmptyGuid())
{
ThrowArgumentException(nameof(labelTranslationUid), labelTranslationUid);
}
LabelTranslationUid = labelTranslationUid;
}
}
} | 29.590909 | 110 | 0.698925 | [
"MIT"
] | Enisbeygorus/translation | Source/Translation.Common/Models/Requests/Label/LabelTranslation/LabelTranslationReadRequest.cs | 653 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ProjBobcat.Class.Model.ServerPing;
public class ServerPingModInfo
{
[JsonProperty("type")] public string Type { get; set; }
[JsonProperty("modList")] public List<ModInfo> ModList { get; set; }
}
public class ModInfo
{
[JsonProperty("modid")] public string ModId { get; set; }
[JsonProperty("version")] public string Version { get; set; }
} | 22.578947 | 72 | 0.708625 | [
"MIT"
] | Corona-Studio/ProjBobcat | ProjBobcat/ProjBobcat/Class/Model/ServerPing/ServerPingModInfo.cs | 431 | C# |
using UnityEngine;
using System.Collections;
public static class Tags
{
//Player root GameObject
public static string player = "Player";
public static string camera = "MainCamera";
public static string interactable = "Interactable";
}
| 23 | 55 | 0.731225 | [
"MIT"
] | lucasrumney94/JDPolterGhost | JDPolterGhost/Assets/Scripts/Static/Tags.cs | 255 | C# |
using System.Collections.Generic;
using NUnit.Framework;
using System.Linq;
namespace TestStack.BDDfy.Tests.Scanner
{
// ToDo: I really need to clean this class up
[TestFixture]
public class WhenTestClassFollowsGivenWhenThenNamingConvention
{
private List<Step> _steps;
private TypeWithoutAttribute _typeWithoutAttribute;
private class TypeWithoutAttribute
{
public void EstablishContext() {}
public void Setup(){}
public void AndThenAnotherThingIsTrue() {}
public void AndWhenSomethingElseHappens() {}
public void And_When_another_THING_Happens() {}
public void GivenSomeState() {}
public void AndSomethingElseToo() { }
public void WhenSomethingHappens() {}
public void AndGivenAnotherState() { }
public void And_Given_Some_OTHER_state() { }
public void AndGiven_some_other_initial_state() { }
public void ThenSomethingIsTrue(){}
public void TearDown(){}
public void And_YET_another_thing(){}
public void AndThen_something_else() {}
public void And_then_there_was_that_one_time() {}
}
[SetUp]
public void Setup()
{
_typeWithoutAttribute = new TypeWithoutAttribute();
_steps = new DefaultMethodNameStepScanner().Scan(TestContext.GetContext(_typeWithoutAttribute)).ToList();
}
[Test]
public void AllMethodsFollowingTheNamingConventionAreReturnedAsSteps()
{
Assert.That(_steps.Count, Is.EqualTo(16));
}
private static void AssertStep(Step step, string stepTitle, ExecutionOrder order, bool asserts = false, bool shouldReport = true)
{
Assert.That(step.Title.Trim(), Is.EqualTo(stepTitle));
Assert.That(step.Asserts, Is.EqualTo(asserts));
Assert.That(step.ExecutionOrder, Is.EqualTo(order));
Assert.That(step.ShouldReport, Is.EqualTo(shouldReport));
}
[Test]
public void EndsWithContext_IsReturnedFirst()
{
AssertStep(_steps[0], "Establish context", ExecutionOrder.Initialize, false, false);
}
[Test]
public void Setup_IsReturnedSecond()
{
AssertStep(_steps[1], "Setup", ExecutionOrder.Initialize, false, false);
}
[Test]
public void Given_IsTurnedIntoA_Given_Step()
{
AssertStep(_steps[2], "Given some state", ExecutionOrder.SetupState);
}
[Test]
public void AndGiven_IsTurnedIntoAn_AndGiven_Step()
{
AssertStep(_steps[3], "And another state", ExecutionOrder.ConsecutiveSetupState);
}
[Test]
public void And_Given_IsTurnedIntoAn_AndGiven_Step()
{
AssertStep(_steps[4], "And Some OTHER state", ExecutionOrder.ConsecutiveSetupState);
}
[Test]
public void AndGiven_InAnUnderscoredMethod_IsTurnedIntoAn_AndGiven_Step()
{
AssertStep(_steps[5], "And some other initial state", ExecutionOrder.ConsecutiveSetupState);
}
[Test]
public void WhenIsReturnedAfterGivens()
{
AssertStep(_steps[6], "When something happens", ExecutionOrder.Transition);
}
[Test]
public void AndWhenIsTurnedIntoAn_AndWhen_Step()
{
AssertStep(_steps[7], "And something else happens", ExecutionOrder.ConsecutiveTransition);
}
[Test]
public void And_When_IsTurnedIntoAn_AndWhen_Step()
{
AssertStep(_steps[8], "And another THING Happens", ExecutionOrder.ConsecutiveTransition);
}
[Test]
public void ThenIsReturnedAfterWhens()
{
AssertStep(_steps[9], "Then something is true", ExecutionOrder.Assertion, true);
}
[Test]
public void AndThen_IsReturnedAsAn_AndThen_StepAfterThen()
{
AssertStep(_steps[10], "And another thing is true", ExecutionOrder.ConsecutiveAssertion, true);
}
[Test]
public void And_IsReturnedAsAn_AndThen_Step()
{
AssertStep(_steps[11], "And something else too", ExecutionOrder.ConsecutiveAssertion, true);
}
[Test]
public void And_IsReturnedAsAn_AndThen_WithTheRightCasing()
{
AssertStep(_steps[12], "And YET another thing", ExecutionOrder.ConsecutiveAssertion, true);
}
[Test]
public void AndThen_IsReturnedAsAn_AndThen_WithUnderscoredMethodName()
{
AssertStep(_steps[13], "And something else", ExecutionOrder.ConsecutiveAssertion, true);
}
[Test]
public void And_Then_IsReturnedAsAn_AndThen_WithUnderscoredMethodName()
{
AssertStep(_steps[14], "And there was that one time", ExecutionOrder.ConsecutiveAssertion, true);
}
[Test]
public void TearDownMethodIsReturnedInTheCorrectSpot()
{
AssertStep(_steps[15], "Tear down", ExecutionOrder.TearDown, asserts:false, shouldReport:false);
}
}
} | 34.635762 | 137 | 0.626386 | [
"MIT"
] | jason-roberts/TestStack.BDDfy | TestStack.BDDfy.Tests/Scanner/WhenTestClassFollowsGivenWhenThenNamingConvention.cs | 5,230 | C# |
using System.Threading;
using Gossip.Transactions;
namespace Gossip.Connection.Fluent
{
public class QueryConfiguration
{
private ITransaction _transaction;
public QueryConfiguration()
{
Transaction = new NullTransaction();
}
public string Query { get; set; }
public object Parameters { get; set; }
/// <summary>
/// In seconds
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Whether to buffer the results in memory
/// </summary>
/// <remarks>This ACTUALLY only works for <code>Query{T}()</code> (not even QueryAsync) as Dapper only exposes it there</remarks>
public bool Unbuffered { get; set; }
public CancellationToken CancellationToken { get; set; }
public ITransaction Transaction
{
get => _transaction;
set => _transaction = value ?? new NullTransaction();
}
}
} | 30.147059 | 138 | 0.564878 | [
"Apache-2.0"
] | DanCNo/Gossip | src/Connection/Fluent/QueryConfiguration.cs | 1,027 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20210201
{
public static class GetIpAllocation
{
/// <summary>
/// IpAllocation resource.
/// </summary>
public static Task<GetIpAllocationResult> InvokeAsync(GetIpAllocationArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetIpAllocationResult>("azure-native:network/v20210201:getIpAllocation", args ?? new GetIpAllocationArgs(), options.WithVersion());
}
public sealed class GetIpAllocationArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Expands referenced resources.
/// </summary>
[Input("expand")]
public string? Expand { get; set; }
/// <summary>
/// The name of the IpAllocation.
/// </summary>
[Input("ipAllocationName", required: true)]
public string IpAllocationName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetIpAllocationArgs()
{
}
}
[OutputType]
public sealed class GetIpAllocationResult
{
/// <summary>
/// IpAllocation tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? AllocationTags;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// The IPAM allocation ID.
/// </summary>
public readonly string? IpamAllocationId;
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The address prefix for the IpAllocation.
/// </summary>
public readonly string? Prefix;
/// <summary>
/// The address prefix length for the IpAllocation.
/// </summary>
public readonly int? PrefixLength;
/// <summary>
/// The address prefix Type for the IpAllocation.
/// </summary>
public readonly string? PrefixType;
/// <summary>
/// The Subnet that using the prefix of this IpAllocation resource.
/// </summary>
public readonly Outputs.SubResourceResponse Subnet;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// The VirtualNetwork that using the prefix of this IpAllocation resource.
/// </summary>
public readonly Outputs.SubResourceResponse VirtualNetwork;
[OutputConstructor]
private GetIpAllocationResult(
ImmutableDictionary<string, string>? allocationTags,
string etag,
string? id,
string? ipamAllocationId,
string? location,
string name,
string? prefix,
int? prefixLength,
string? prefixType,
Outputs.SubResourceResponse subnet,
ImmutableDictionary<string, string>? tags,
string type,
Outputs.SubResourceResponse virtualNetwork)
{
AllocationTags = allocationTags;
Etag = etag;
Id = id;
IpamAllocationId = ipamAllocationId;
Location = location;
Name = name;
Prefix = prefix;
PrefixLength = prefixLength;
PrefixType = prefixType;
Subnet = subnet;
Tags = tags;
Type = type;
VirtualNetwork = virtualNetwork;
}
}
}
| 29.858108 | 185 | 0.572301 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20210201/GetIpAllocation.cs | 4,419 | 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 route53-2013-04-01.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.Route53.Model
{
/// <summary>
/// A complex type that contains the response for the request.
/// </summary>
public partial class ListHostedZonesByNameResponse : AmazonWebServiceResponse
{
private List<HostedZone> _hostedZones = new List<HostedZone>();
private string _dnsName;
private string _hostedZoneId;
private bool? _isTruncated;
private string _nextDNSName;
private string _nextHostedZoneId;
private string _maxItems;
/// <summary>
/// Gets and sets the property HostedZones.
/// <para>
/// A complex type that contains information about the hosted zones associated with the
/// current AWS account.
/// </para>
/// </summary>
public List<HostedZone> HostedZones
{
get { return this._hostedZones; }
set { this._hostedZones = value; }
}
// Check to see if HostedZones property is set
internal bool IsSetHostedZones()
{
return this._hostedZones != null && this._hostedZones.Count > 0;
}
/// <summary>
/// Gets and sets the property DNSName.
/// <para>
/// The <code>DNSName</code> value sent in the request.
/// </para>
/// </summary>
public string DNSName
{
get { return this._dnsName; }
set { this._dnsName = value; }
}
// Check to see if DNSName property is set
internal bool IsSetDNSName()
{
return this._dnsName != null;
}
/// <summary>
/// Gets and sets the property HostedZoneId.
/// <para>
/// The <code>HostedZoneId</code> value sent in the request.
/// </para>
/// </summary>
public string HostedZoneId
{
get { return this._hostedZoneId; }
set { this._hostedZoneId = value; }
}
// Check to see if HostedZoneId property is set
internal bool IsSetHostedZoneId()
{
return this._hostedZoneId != null;
}
/// <summary>
/// Gets and sets the property IsTruncated.
/// <para>
/// A flag indicating whether there are more hosted zones to be listed. If your results
/// were truncated, you can make a follow-up request for the next page of results by using
/// the <code>NextDNSName</code> and <code>NextHostedZoneId</code> elements.
/// </para>
///
/// <para>
/// Valid Values: <code>true</code> | <code>false</code>
/// </para>
/// </summary>
public bool IsTruncated
{
get { return this._isTruncated.GetValueOrDefault(); }
set { this._isTruncated = value; }
}
// Check to see if IsTruncated property is set
internal bool IsSetIsTruncated()
{
return this._isTruncated.HasValue;
}
/// <summary>
/// Gets and sets the property NextDNSName.
/// <para>
/// If the value of <code>IsTruncated</code> in the <code>ListHostedZonesByNameResponse</code>
/// is <code>true</code>, there are more hosted zones associated with the current AWS
/// account. To get the next page of results, make another request to <code>ListHostedZonesByName</code>.
/// Specify the value of <code>NextDNSName</code> in the <code>DNSName</code> parameter.
/// Specify <code>NextHostedZoneId</code> in the <code>HostedZoneId</code> parameter.
/// </para>
/// </summary>
public string NextDNSName
{
get { return this._nextDNSName; }
set { this._nextDNSName = value; }
}
// Check to see if NextDNSName property is set
internal bool IsSetNextDNSName()
{
return this._nextDNSName != null;
}
/// <summary>
/// Gets and sets the property NextHostedZoneId.
/// <para>
/// If the value of <code>IsTruncated</code> in the <code>ListHostedZonesByNameResponse</code>
/// is <code>true</code>, there are more hosted zones associated with the current AWS
/// account. To get the next page of results, make another request to <code>ListHostedZonesByName</code>.
/// Specify the value of <code>NextDNSName</code> in the <code>DNSName</code> parameter.
/// Specify <code>NextHostedZoneId</code> in the <code>HostedZoneId</code> parameter.
/// </para>
/// </summary>
public string NextHostedZoneId
{
get { return this._nextHostedZoneId; }
set { this._nextHostedZoneId = value; }
}
// Check to see if NextHostedZoneId property is set
internal bool IsSetNextHostedZoneId()
{
return this._nextHostedZoneId != null;
}
/// <summary>
/// Gets and sets the property MaxItems.
/// <para>
/// The maximum number of hosted zones to be included in the response body. If the number
/// of hosted zones associated with this AWS account exceeds <code>MaxItems</code>, the
/// value of <code>IsTruncated</code> in the <code>ListHostedZonesByNameResponse</code>
/// is <code>true</code>. Call <code>ListHostedZonesByName</code> again and specify the
/// value of <code>NextDNSName</code> and <code>NextHostedZoneId</code> elements from
/// the previous response to get the next page of results.
/// </para>
/// </summary>
public string MaxItems
{
get { return this._maxItems; }
set { this._maxItems = value; }
}
// Check to see if MaxItems property is set
internal bool IsSetMaxItems()
{
return this._maxItems != null;
}
}
} | 35.789474 | 113 | 0.595735 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/Route53/Generated/Model/ListHostedZonesByNameResponse.cs | 6,800 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Test.Shared.Completion;
using Microsoft.PowerShell.EditorServices.Test.Shared.Definition;
using Microsoft.PowerShell.EditorServices.Test.Shared.Occurrences;
using Microsoft.PowerShell.EditorServices.Test.Shared.ParameterHint;
using Microsoft.PowerShell.EditorServices.Test.Shared.References;
using Microsoft.PowerShell.EditorServices.Test.Shared.SymbolDetails;
using Microsoft.PowerShell.EditorServices.Test.Shared.Symbols;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.PowerShell.EditorServices.Utility;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using System.Runtime.InteropServices;
namespace Microsoft.PowerShell.EditorServices.Test.Language
{
public class LanguageServiceTests : IDisposable
{
private Workspace workspace;
private LanguageService languageService;
private PowerShellContext powerShellContext;
private static readonly string s_baseSharedScriptPath =
TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/");
public LanguageServiceTests()
{
var logger = Logging.NullLogger;
this.powerShellContext = PowerShellContextFactory.Create(logger);
this.workspace = new Workspace(this.powerShellContext.LocalPowerShellVersion.Version, logger);
this.languageService = new LanguageService(this.powerShellContext, logger);
}
public void Dispose()
{
this.powerShellContext.Dispose();
}
[Fact]
public async Task LanguageServiceCompletesCommandInFile()
{
CompletionResults completionResults =
await this.GetCompletionResults(
CompleteCommandInFile.SourceDetails);
Assert.NotEmpty(completionResults.Completions);
Assert.Equal(
CompleteCommandInFile.ExpectedCompletion,
completionResults.Completions[0]);
}
[Fact]
public async Task LanguageServiceCompletesCommandFromModule()
{
CompletionResults completionResults =
await this.GetCompletionResults(
CompleteCommandFromModule.SourceDetails);
Assert.NotEmpty(completionResults.Completions);
Assert.Equal(
CompleteCommandFromModule.ExpectedCompletion,
completionResults.Completions[0]);
}
[Fact]
public async Task LanguageServiceCompletesVariableInFile()
{
CompletionResults completionResults =
await this.GetCompletionResults(
CompleteVariableInFile.SourceDetails);
Assert.Single(completionResults.Completions);
Assert.Equal(
CompleteVariableInFile.ExpectedCompletion,
completionResults.Completions[0]);
}
[Fact]
public async Task LanguageServiceCompletesAttributeValue()
{
CompletionResults completionResults =
await this.GetCompletionResults(
CompleteAttributeValue.SourceDetails);
Assert.NotEmpty(completionResults.Completions);
Assert.Equal(
CompleteAttributeValue.ExpectedRange,
completionResults.ReplacedRange);
}
[Fact]
public async Task LanguageServiceCompletesFilePath()
{
CompletionResults completionResults =
await this.GetCompletionResults(
CompleteFilePath.SourceDetails);
Assert.NotEmpty(completionResults.Completions);
// TODO: Since this is a path completion, this test will need to be
// platform specific. Probably something like:
// - Windows: C:\Program
// - macOS: /User
// - Linux: /hom
//Assert.Equal(
// CompleteFilePath.ExpectedRange,
// completionResults.ReplacedRange);
}
[Fact]
public async Task LanguageServiceFindsParameterHintsOnCommand()
{
ParameterSetSignatures paramSignatures =
await this.GetParamSetSignatures(
FindsParameterSetsOnCommand.SourceDetails);
Assert.NotNull(paramSignatures);
Assert.Equal("Get-Process", paramSignatures.CommandName);
Assert.Equal(6, paramSignatures.Signatures.Count());
}
[Fact]
public async Task LanguageServiceFindsCommandForParamHintsWithSpaces()
{
ParameterSetSignatures paramSignatures =
await this.GetParamSetSignatures(
FindsParameterSetsOnCommandWithSpaces.SourceDetails);
Assert.NotNull(paramSignatures);
Assert.Equal("Write-Host", paramSignatures.CommandName);
Assert.Single(paramSignatures.Signatures);
}
[Fact]
public async Task LanguageServiceFindsFunctionDefinition()
{
GetDefinitionResult definitionResult =
await this.GetDefinition(
FindsFunctionDefinition.SourceDetails);
SymbolReference definition = definitionResult.FoundDefinition;
Assert.Equal(1, definition.ScriptRegion.StartLineNumber);
Assert.Equal(10, definition.ScriptRegion.StartColumnNumber);
Assert.Equal("My-Function", definition.SymbolName);
}
[Fact]
public async Task LanguageServiceFindsFunctionDefinitionInDotSourceReference()
{
GetDefinitionResult definitionResult =
await this.GetDefinition(
FindsFunctionDefinitionInDotSourceReference.SourceDetails);
SymbolReference definition = definitionResult.FoundDefinition;
Assert.True(
definitionResult.FoundDefinition.FilePath.EndsWith(
FindsFunctionDefinition.SourceDetails.File),
"Unexpected reference file: " + definitionResult.FoundDefinition.FilePath);
Assert.Equal(1, definition.ScriptRegion.StartLineNumber);
Assert.Equal(10, definition.ScriptRegion.StartColumnNumber);
Assert.Equal("My-Function", definition.SymbolName);
}
[Fact]
public async Task LanguageServiceFindsDotSourcedFile()
{
GetDefinitionResult definitionResult =
await this.GetDefinition(
FindsDotSourcedFile.SourceDetails);
SymbolReference definition = definitionResult.FoundDefinition;
Assert.True(
definitionResult.FoundDefinition.FilePath.EndsWith(
Path.Combine("References", "ReferenceFileE.ps1")),
"Unexpected reference file: " + definitionResult.FoundDefinition.FilePath);
Assert.Equal(1, definition.ScriptRegion.StartLineNumber);
Assert.Equal(1, definition.ScriptRegion.StartColumnNumber);
Assert.Equal("./ReferenceFileE.ps1", definition.SymbolName);
}
[Fact]
public async Task LanguageServiceFindsFunctionDefinitionInWorkspace()
{
var definitionResult =
await this.GetDefinition(
FindsFunctionDefinitionInWorkspace.SourceDetails,
new Workspace(this.powerShellContext.LocalPowerShellVersion.Version, Logging.NullLogger)
{
WorkspacePath = Path.Combine(s_baseSharedScriptPath, @"References")
});
var definition = definitionResult.FoundDefinition;
Assert.EndsWith("ReferenceFileE.ps1", definition.FilePath);
Assert.Equal("My-FunctionInFileE", definition.SymbolName);
}
[Fact]
public async Task LanguageServiceFindsVariableDefinition()
{
GetDefinitionResult definitionResult =
await this.GetDefinition(
FindsVariableDefinition.SourceDetails);
SymbolReference definition = definitionResult.FoundDefinition;
Assert.Equal(6, definition.ScriptRegion.StartLineNumber);
Assert.Equal(1, definition.ScriptRegion.StartColumnNumber);
Assert.Equal("$things", definition.SymbolName);
}
[Fact]
public void LanguageServiceFindsOccurrencesOnFunction()
{
FindOccurrencesResult occurrencesResult =
this.GetOccurrences(
FindsOccurrencesOnFunction.SourceDetails);
Assert.Equal(3, occurrencesResult.FoundOccurrences.Count());
Assert.Equal(10, occurrencesResult.FoundOccurrences.Last().ScriptRegion.StartLineNumber);
Assert.Equal(1, occurrencesResult.FoundOccurrences.Last().ScriptRegion.StartColumnNumber);
}
[Fact]
public void LanguageServiceFindsOccurrencesOnParameter()
{
FindOccurrencesResult occurrencesResult =
this.GetOccurrences(
FindOccurrencesOnParameter.SourceDetails);
Assert.Equal("$myInput", occurrencesResult.FoundOccurrences.Last().SymbolName);
Assert.Equal(2, occurrencesResult.FoundOccurrences.Count());
Assert.Equal(3, occurrencesResult.FoundOccurrences.Last().ScriptRegion.StartLineNumber);
}
[Fact]
public async Task LanguageServiceFindsReferencesOnCommandWithAlias()
{
FindReferencesResult refsResult =
await this.GetReferences(
FindsReferencesOnBuiltInCommandWithAlias.SourceDetails);
SymbolReference[] foundRefs = refsResult.FoundReferences.ToArray();
Assert.Equal(4, foundRefs.Length);
Assert.Equal("gci", foundRefs[1].SymbolName);
Assert.Equal("Get-ChildItem", foundRefs[foundRefs.Length - 1].SymbolName);
}
[Fact]
public async Task LanguageServiceFindsReferencesOnAlias()
{
FindReferencesResult refsResult =
await this.GetReferences(
FindsReferencesOnBuiltInCommandWithAlias.SourceDetails);
Assert.Equal(4, refsResult.FoundReferences.Count());
Assert.Equal("dir", refsResult.FoundReferences.ToArray()[2].SymbolName);
Assert.Equal("Get-ChildItem", refsResult.FoundReferences.Last().SymbolName);
}
[Fact]
public async Task LanguageServiceFindsReferencesOnFileWithReferencesFileB()
{
FindReferencesResult refsResult =
await this.GetReferences(
FindsReferencesOnFunctionMultiFileDotSourceFileB.SourceDetails);
Assert.Equal(4, refsResult.FoundReferences.Count());
}
[Fact]
public async Task LanguageServiceFindsReferencesOnFileWithReferencesFileC()
{
FindReferencesResult refsResult =
await this.GetReferences(
FindsReferencesOnFunctionMultiFileDotSourceFileC.SourceDetails);
Assert.Equal(4, refsResult.FoundReferences.Count());
}
[Fact]
public async Task LanguageServiceFindsDetailsForBuiltInCommand()
{
SymbolDetails symbolDetails =
await this.languageService.FindSymbolDetailsAtLocationAsync(
this.GetScriptFile(FindsDetailsForBuiltInCommand.SourceDetails),
FindsDetailsForBuiltInCommand.SourceDetails.StartLineNumber,
FindsDetailsForBuiltInCommand.SourceDetails.StartColumnNumber);
Assert.NotNull(symbolDetails.Documentation);
Assert.NotEqual("", symbolDetails.Documentation);
}
[Fact]
public void LanguageServiceFindsSymbolsInFile()
{
FindOccurrencesResult symbolsResult =
this.FindSymbolsInFile(
FindSymbolsInMultiSymbolFile.SourceDetails);
Assert.Equal(4, symbolsResult.FoundOccurrences.Where(symbolReference => symbolReference.SymbolType == SymbolType.Function).Count());
Assert.Equal(3, symbolsResult.FoundOccurrences.Where(symbolReference => symbolReference.SymbolType == SymbolType.Variable).Count());
Assert.Single(symbolsResult.FoundOccurrences.Where(symbolReference => symbolReference.SymbolType == SymbolType.Workflow));
SymbolReference firstFunctionSymbol = symbolsResult.FoundOccurrences.Where(r => r.SymbolType == SymbolType.Function).First();
Assert.Equal("AFunction", firstFunctionSymbol.SymbolName);
Assert.Equal(7, firstFunctionSymbol.ScriptRegion.StartLineNumber);
Assert.Equal(1, firstFunctionSymbol.ScriptRegion.StartColumnNumber);
SymbolReference lastVariableSymbol = symbolsResult.FoundOccurrences.Where(r => r.SymbolType == SymbolType.Variable).Last();
Assert.Equal("$Script:ScriptVar2", lastVariableSymbol.SymbolName);
Assert.Equal(3, lastVariableSymbol.ScriptRegion.StartLineNumber);
Assert.Equal(1, lastVariableSymbol.ScriptRegion.StartColumnNumber);
SymbolReference firstWorkflowSymbol = symbolsResult.FoundOccurrences.Where(r => r.SymbolType == SymbolType.Workflow).First();
Assert.Equal("AWorkflow", firstWorkflowSymbol.SymbolName);
Assert.Equal(23, firstWorkflowSymbol.ScriptRegion.StartLineNumber);
Assert.Equal(1, firstWorkflowSymbol.ScriptRegion.StartColumnNumber);
// TODO: Bring this back when we can use AstVisitor2 again (#276)
//Assert.Equal(1, symbolsResult.FoundOccurrences.Where(r => r.SymbolType == SymbolType.Configuration).Count());
//SymbolReference firstConfigurationSymbol = symbolsResult.FoundOccurrences.Where(r => r.SymbolType == SymbolType.Configuration).First();
//Assert.Equal("AConfiguration", firstConfigurationSymbol.SymbolName);
//Assert.Equal(25, firstConfigurationSymbol.ScriptRegion.StartLineNumber);
//Assert.Equal(1, firstConfigurationSymbol.ScriptRegion.StartColumnNumber);
}
[Fact]
public void LanguageServiceFindsSymbolsInPesterFile()
{
var symbolsResult = this.FindSymbolsInFile(FindSymbolsInPesterFile.SourceDetails);
Assert.Equal(5, symbolsResult.FoundOccurrences.Count());
}
[Fact]
public void LangServerFindsSymbolsInPSDFile()
{
var symbolsResult = this.FindSymbolsInFile(FindSymbolsInPSDFile.SourceDetails);
Assert.Equal(3, symbolsResult.FoundOccurrences.Count());
}
[Fact]
public void LanguageServiceFindsSymbolsInNoSymbolsFile()
{
FindOccurrencesResult symbolsResult =
this.FindSymbolsInFile(
FindSymbolsInNoSymbolsFile.SourceDetails);
Assert.Empty(symbolsResult.FoundOccurrences);
}
private ScriptFile GetScriptFile(ScriptRegion scriptRegion)
{
string resolvedPath =
Path.Combine(
s_baseSharedScriptPath,
scriptRegion.File);
return
this.workspace.GetFile(
resolvedPath);
}
private async Task<CompletionResults> GetCompletionResults(ScriptRegion scriptRegion)
{
// Run the completions request
return
await this.languageService.GetCompletionsInFileAsync(
GetScriptFile(scriptRegion),
scriptRegion.StartLineNumber,
scriptRegion.StartColumnNumber);
}
private async Task<ParameterSetSignatures> GetParamSetSignatures(ScriptRegion scriptRegion)
{
return
await this.languageService.FindParameterSetsInFileAsync(
GetScriptFile(scriptRegion),
scriptRegion.StartLineNumber,
scriptRegion.StartColumnNumber);
}
private async Task<GetDefinitionResult> GetDefinition(ScriptRegion scriptRegion, Workspace workspace)
{
ScriptFile scriptFile = GetScriptFile(scriptRegion);
SymbolReference symbolReference =
this.languageService.FindSymbolAtLocation(
scriptFile,
scriptRegion.StartLineNumber,
scriptRegion.StartColumnNumber);
Assert.NotNull(symbolReference);
return
await this.languageService.GetDefinitionOfSymbolAsync(
scriptFile,
symbolReference,
workspace);
}
private async Task<GetDefinitionResult> GetDefinition(ScriptRegion scriptRegion)
{
return await GetDefinition(scriptRegion, this.workspace);
}
private async Task<FindReferencesResult> GetReferences(ScriptRegion scriptRegion)
{
ScriptFile scriptFile = GetScriptFile(scriptRegion);
SymbolReference symbolReference =
this.languageService.FindSymbolAtLocation(
scriptFile,
scriptRegion.StartLineNumber,
scriptRegion.StartColumnNumber);
Assert.NotNull(symbolReference);
return
await this.languageService.FindReferencesOfSymbolAsync(
symbolReference,
this.workspace.ExpandScriptReferences(scriptFile),
this.workspace);
}
private FindOccurrencesResult GetOccurrences(ScriptRegion scriptRegion)
{
return
this.languageService.FindOccurrencesInFile(
GetScriptFile(scriptRegion),
scriptRegion.StartLineNumber,
scriptRegion.StartColumnNumber);
}
private FindOccurrencesResult FindSymbolsInFile(ScriptRegion scriptRegion)
{
return
this.languageService.FindSymbolsInFile(
GetScriptFile(scriptRegion));
}
}
}
| 41.655405 | 149 | 0.643309 | [
"MIT"
] | Benny1007/PowerShellEditorServices | test/PowerShellEditorServices.Test/Language/LanguageServiceTests.cs | 18,497 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.Vulkan
{
[NativeName("Name", "VkPerformanceOverrideInfoINTEL")]
public unsafe partial struct PerformanceOverrideInfoINTEL
{
public PerformanceOverrideInfoINTEL
(
StructureType? sType = StructureType.PerformanceOverrideInfoIntel,
void* pNext = null,
PerformanceOverrideTypeINTEL? type = null,
Bool32? enable = null,
ulong? parameter = null
) : this()
{
if (sType is not null)
{
SType = sType.Value;
}
if (pNext is not null)
{
PNext = pNext;
}
if (type is not null)
{
Type = type.Value;
}
if (enable is not null)
{
Enable = enable.Value;
}
if (parameter is not null)
{
Parameter = parameter.Value;
}
}
/// <summary></summary>
[NativeName("Type", "VkStructureType")]
[NativeName("Type.Name", "VkStructureType")]
[NativeName("Name", "sType")]
public StructureType SType;
/// <summary></summary>
[NativeName("Type", "void*")]
[NativeName("Type.Name", "void")]
[NativeName("Name", "pNext")]
public void* PNext;
/// <summary></summary>
[NativeName("Type", "VkPerformanceOverrideTypeINTEL")]
[NativeName("Type.Name", "VkPerformanceOverrideTypeINTEL")]
[NativeName("Name", "type")]
public PerformanceOverrideTypeINTEL Type;
/// <summary></summary>
[NativeName("Type", "VkBool32")]
[NativeName("Type.Name", "VkBool32")]
[NativeName("Name", "enable")]
public Bool32 Enable;
/// <summary></summary>
[NativeName("Type", "uint64_t")]
[NativeName("Type.Name", "uint64_t")]
[NativeName("Name", "parameter")]
public ulong Parameter;
}
}
| 28.559524 | 78 | 0.569821 | [
"MIT"
] | DmitryGolubenkov/Silk.NET | src/Vulkan/Silk.NET.Vulkan/Structs/PerformanceOverrideInfoINTEL.gen.cs | 2,399 | C# |
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.Mvc;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Swashbuckle.AspNetCore.Filters
{
public class FeatureManagementFilter : SwaggerGen.IDocumentFilter
{
private readonly IServiceProvider _provider;
public FeatureManagementFilter(IServiceProvider provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var contextApiDescription in context.ApiDescriptions)
{
var actionDescriptor = (ControllerActionDescriptor)contextApiDescription.ActionDescriptor;
if (actionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(FeatureGateAttribute), true).Length > 0 ||
actionDescriptor.MethodInfo.GetCustomAttributes(typeof(FeatureGateAttribute), true).Length > 0)
{
using var scope = _provider.CreateScope();
var featureManager = scope.ServiceProvider.GetRequiredService<IFeatureManagerSnapshot>();
var actionAttributes = actionDescriptor.MethodInfo.GetCustomAttributes(typeof(FeatureGateAttribute), true);
foreach (var attr in actionAttributes)
{
foreach (var feature in (attr as FeatureGateAttribute).Features)
{
if (!featureManager.IsEnabledAsync(feature).GetAwaiter().GetResult())
{
var key = "/" + contextApiDescription.RelativePath.TrimEnd('/');
var operation = (OperationType)Enum.Parse(typeof(OperationType), contextApiDescription.HttpMethod, true);
swaggerDoc.Paths[key].Operations.Remove(operation);
// drop the entire route of there are no operations left
if (!swaggerDoc.Paths[key].Operations.Any())
{
swaggerDoc.Paths.Remove(key);
}
swaggerDoc.Components?.Schemas?.Clear();
break;
}
}
}
}
}
}
}
}
| 40.393939 | 137 | 0.571643 | [
"Apache-2.0"
] | kdcllc/FeatureManagementDemo | src/FeatureManagementWeb/SwaggerFilters/FeatureManagementFilter.cs | 2,668 | C# |
using System;
using System.Threading.Tasks;
using System.Linq;
using StackExchange.Redis;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
namespace SocketCore.Server.AspNetCore
{
public class RedisConnectionManager : IConnectionManager, IDisposable
{
private Task _DrumBeatTask = null;
private readonly string _NodeId = Guid.NewGuid().ToString();
private readonly string _Prefix = "$";
private ConnectionMultiplexer _Instance = null;
public RedisConnectionManager(string configuration, TextWriter log = null, string prefix = "$")
{
_Instance = ConnectionMultiplexer.Connect(configuration, log);
_Prefix = prefix;
}
public RedisConnectionManager(ConfigurationOptions configuration, TextWriter log = null, string prefix = "$")
{
_Instance = ConnectionMultiplexer.Connect(configuration, log);
_Prefix = prefix;
}
public RedisConnectionManager(string configuration, string prefix)
: this(configuration, null, prefix)
{
}
public RedisConnectionManager(TextWriter log = null)
: this("localhost", log)
{
}
~RedisConnectionManager()
{
//free only unmanaged resources
Dispose(false);
}
public void Dispose()
{
//free managed and unmanaged resources
Dispose(true);
//remove this object from finalization queue because it is already cleaned up
GC.SuppressFinalize(this);
}
public string NodeId
{
get
{
return _NodeId;
}
}
private void Dispose(bool disposing)
{
//free unmanaged resources
if (disposing)
{
//free managed resources
if (_Instance != null)
{
_Instance.Dispose();
_Instance = null;
}
if (_DrumBeatTask != null)
{
_DrumBeatTask.Dispose();
_DrumBeatTask = null;
}
}
}
public async Task<object> ConnectAsync(string connectionId, Func<object, Task> callback)
{
var handler = new Action<RedisChannel, RedisValue>(async (chn, msg) =>
{
var message = JsonConvert.DeserializeObject<object>(msg);
await callback(message);
});
await Task.WhenAll(
RedisSubscribeAsync($"{_Prefix}all", handler),
RedisSubscribeAsync($"{_Prefix}c_{connectionId}", handler));
await EnsureDrumBeatStarted(connectionId);
await _Instance.SADD($"{_Prefix}n_{_NodeId}", connectionId);
return handler;
}
public Task DisconnectAsync(string connectionId, object handle)
{
return Task.WhenAll(
_Instance.SREM($"{_Prefix}n_{_NodeId}", connectionId),
RedisSetRemoveMatchAsync($"{_Prefix}g_*", connectionId),
RedisUnsubscribeAsync($"{_Prefix}c_{connectionId}", handle as Action<RedisChannel, RedisValue>),
RedisUnsubscribeAsync($"{_Prefix}all", handle as Action<RedisChannel, RedisValue>));
}
public Task AddToGroupAsync(string connectionId, string group)
{
return _Instance.SADD($"{_Prefix}g_{group}", connectionId);
}
public Task RemoveFromGroupAsync(string connectionId, string group)
{
return _Instance.SREM($"{_Prefix}g_{group}", connectionId);
}
public async Task<IEnumerable<string>> GetConnectionsAsync()
{
var channels = await _Instance.CHANNELS($"{_Prefix}c_*");
return channels.Select(a => a.Replace($"{_Prefix}c_", string.Empty)).ToArray();
}
public async Task<IEnumerable<string>> GetGroupsAsync()
{
var groups = await _Instance.KEYS($"{_Prefix}g_*");
return groups.Select(a => a.Replace($"{_Prefix}g_", string.Empty)).ToArray();
}
public Task SendToConnectionsAsync(object data, params string[] connectionIds)
{
return Task.WhenAll(connectionIds.Select(connectionId => RedisPublishAsync($"{_Prefix}c_{connectionId}", data)));
}
public Task SendToGroupsAsync(object data, params string[] groups)
{
return Task.WhenAll(groups.Select(group => RedisSetPublishAsync($"{_Prefix}g_{group}", data)));
}
public Task SendToAllAsync(object data)
{
return RedisPublishAsync($"{_Prefix}all", data);
}
public async Task CleanupEmptyGroups()
{
//create temp set of all connections id
var nodes = await _Instance.KEYS($"{_Prefix}n_*");
var tmpKey = $"{_Prefix}{Guid.NewGuid().ToString()}";
await _Instance.SUNIONSTORE(tmpKey, nodes);
//remove from groups not existing connections id
var groups = await _Instance.KEYS($"{_Prefix}g_*");
await Task.WhenAll(groups.Select(g => _Instance.SUNIONSTORE(g, g, tmpKey)));
//remove temp set
await _Instance.DEL(tmpKey);
}
private async Task EnsureDrumBeatStarted(string connectionId)
{
if (!await _Instance.GetDatabase().KeyExistsAsync($"{_Prefix}n_{_NodeId}"))
{
_DrumBeatTask = Task.Factory.StartNew(async () =>
{
while (true)
{
await _Instance.GetDatabase().KeyExpireAsync($"{_Prefix}n_{_NodeId}", TimeSpan.FromSeconds(10));
await Task.Delay(5000);
}
});
}
}
private Task RedisSetPublishAsync(string setName, object messages)
{
var script = $@"
local channels = redis.call('SMEMBERS', KEYS[1])
local res = {{}}
for i = 1, #channels do
table.insert(res, redis.call('PUBLISH', '{_Prefix}c_' .. channels[i], ARGV[1]))
end
return res";
RedisValue[] values = { JsonConvert.SerializeObject(messages) };
return _Instance.GetDatabase().ScriptEvaluateAsync(script, new RedisKey[] { setName }, values);
}
private Task RedisPublishAsync(string channel, object messages)
{
return _Instance.GetSubscriber().PublishAsync(channel, JsonConvert.SerializeObject(messages));
}
private Task RedisSubscribeAsync(string channel, Action<RedisChannel, RedisValue> handler)
{
return _Instance.GetSubscriber().SubscribeAsync(channel, handler);
}
private Task RedisUnsubscribeAsync(string channel, Action<RedisChannel, RedisValue> handler)
{
return _Instance.GetSubscriber().UnsubscribeAsync(channel, handler);
}
private Task RedisSetRemoveMatchAsync(string pattern, RedisValue value)
{
var script = @"
local keys = redis.call('KEYS', '" + pattern + @"')
local res = {}
for i = 1, #keys do
table.insert(res, redis.call('SREM', keys[i], ARGV[1]))
end
return res";
return _Instance.GetDatabase().ScriptEvaluateAsync(script, new RedisKey[] { pattern }, new RedisValue[] { value });
}
}
} | 34.392857 | 127 | 0.564512 | [
"MIT"
] | janusznoszczynski/SocketCore.Server.AspNetCore | src/RedisConnectionManager.cs | 7,704 | C# |
using System;
namespace WebService.Models {
public class PostModel {
public string Body { get; set; }
public int Score { get; set; }
public DateTime CreationDate { get; set; }
public string Author { get; set; }
public string Answers { get; set; }
public string Comments { get; set; }
public string ClickHereToMark { get; set; }
}
} | 30.538462 | 51 | 0.599496 | [
"MIT"
] | WilliamHerrgott/rawdata-porfolio-sova | WebService/Models/PostModel.cs | 399 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Cognifide.PowerShell.Core.Extensions;
using Cognifide.PowerShell.Core.Modules;
using Cognifide.PowerShell.Core.Settings.Authorization;
using Cognifide.PowerShell.Core.Utility;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Text;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
namespace Cognifide.PowerShell.Client.Commands.MenuItems
{
[Serializable]
public class ScriptLibraryMenuItem : Command
{
public string IntegrationPoint { get; protected set; }
public override CommandState QueryState(CommandContext context)
{
return ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
false)
? CommandState.Enabled
: CommandState.Hidden;
}
public void SetupIntegrationPoint(CommandContext context)
{
Assert.IsNotNull(context, "Context is null.");
IntegrationPoint = !string.IsNullOrEmpty(context.Parameters["integrationPoint"])
? context.Parameters["integrationPoint"]
: string.Empty;
}
public override void Execute(CommandContext context)
{
SheerResponse.DisableOutput();
var subMenu = new ContextMenu();
var menuItems = new List<Control>();
var menuItemId = context.Parameters["menuItemId"];
if (string.IsNullOrEmpty(menuItemId))
{
// a bit of a hacky way to determine the caller so we can display the menu
// in proximity to the triggering control
var parameters = new UrlString("?" + Context.Items["SC_FORM"]);
menuItemId = parameters.Parameters["__EVENTTARGET"];
}
SetupIntegrationPoint(context);
var contextItem = context.Items.Length == 1
? context.Items[0]
: string.IsNullOrEmpty(context.Parameters["db"]) || string.IsNullOrEmpty(context.Parameters["id"])
? null
: Database.GetDatabase(context.Parameters["db"]).GetItem(new ID(context.Parameters["id"]));
if (string.IsNullOrEmpty(IntegrationPoint))
{
var submenu =
Factory.GetDatabase(context.Parameters["scriptDB"]).GetItem(context.Parameters["scriptPath"]);
GetLibraryMenuItems(contextItem, menuItems, submenu);
}
else
{
foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoint))
{
GetLibraryMenuItems(contextItem, menuItems, root);
}
}
foreach (var item in menuItems)
{
var menuItem = item as MenuItem;
if (menuItem == null) continue;
var subItem = subMenu.Add(menuItem.ID, menuItem.Header, menuItem.Icon, menuItem.Hotkey,
menuItem.Click,
menuItem.Checked, menuItem.Radiogroup, menuItem.Type);
subItem.Disabled = menuItem.Disabled;
}
SheerResponse.EnableOutput();
subMenu.Visible = true;
SheerResponse.ShowContextMenu(menuItemId, "right", subMenu);
}
public override Control[] GetSubmenuItems(CommandContext context)
{
if (context.Items.Length != 1)
return null;
SetupIntegrationPoint(context);
var menuItems = new List<Control>();
foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.ContentEditorContextMenuFeature))
{
GetLibraryMenuItems(context.Items[0], menuItems, root);
}
return menuItems.ToArray();
}
internal static void GetLibraryMenuItems(Item contextItem, List<Control> menuItems, Item parent)
{
if (parent == null)
{
return;
}
if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
false))
{
return;
}
var scriptTemplateId = new ID("{DD22F1B3-BD87-4DB2-9E7D-F7A496888D43}");
var scriptLibaryTemplateId = new ID("{AB154D3D-1126-4AB4-AC21-8B86E6BD70EA}");
foreach (var scriptItem in parent.Children.Where(p => p.TemplateID == scriptTemplateId || p.TemplateID == scriptLibaryTemplateId))
{
if (!RulesUtils.EvaluateRules(scriptItem["ShowRule"], contextItem))
{
continue;
}
var menuItem = new MenuItem
{
Header = scriptItem.DisplayName,
Icon = scriptItem.Appearance.Icon,
ID = scriptItem.ID.ToShortID().ToString(),
Disabled = !RulesUtils.EvaluateRules(scriptItem["EnableRule"], contextItem)
};
if (scriptItem.IsPowerShellScript())
{
menuItem.Click = contextItem != null ? $"item:executescript(id={contextItem.ID},db={contextItem.Database.Name},script={scriptItem.ID},scriptDb={scriptItem.Database.Name})" : $"item:executescript(script={scriptItem.ID},scriptDb={scriptItem.Database.Name})";
}
else
{
menuItem.Type = MenuItemType.Submenu;
menuItem.Click = contextItem != null ? $"item:scriptlibrary(id={contextItem.ID},db={contextItem.Database.Name},scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})" : $"item:scriptlibrary(scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})";
}
menuItems.Add(menuItem);
}
}
public override string GetClick(CommandContext context, string click)
{
return string.Empty;
}
}
} | 40.127389 | 350 | 0.592222 | [
"MIT"
] | hetaldave/SCUniversitySession8 | Cognifide.PowerShell/Client/Commands/MenuItems/ScriptLibraryMenuItem.cs | 6,302 | C# |
using DataDynamics.PageFX.Common.Services;
using DataDynamics.PageFX.Common.TypeSystem;
using DataDynamics.PageFX.Common.Utilities;
using DataDynamics.PageFX.Flash.Abc;
namespace DataDynamics.PageFX.Flash.Core.CodeGeneration.Corlib
{
internal sealed class EnvironmentTypeImpl
{
private readonly AbcGenerator _generator;
private LazyValue<AbcMethod>[] _methods;
public EnvironmentTypeImpl(AbcGenerator generator)
{
_generator = generator;
}
public AbcMethod this[EnvironmentMethodId id]
{
get { return EnvironmentMethods[(int)id].Value; }
}
public IType Type
{
get { return _generator.Corlib.GetType(CorlibTypeId.Environment); }
}
public AbcInstance Instance
{
get { return _generator.Corlib.GetInstance(CorlibTypeId.Environment); }
}
private LazyValue<AbcMethod>[] EnvironmentMethods
{
get
{
return _methods ?? (_methods =
new[]
{
_generator.MethodBuilder.LazyMethod(Type, "get_StackTrace")
});
}
}
}
internal enum EnvironmentMethodId
{
StackTrace,
}
} | 23.52 | 86 | 0.653061 | [
"MIT"
] | GrapeCity/pagefx | source/libs/Flash/Core/CodeGeneration/Corlib/EnvironmentTypeImpl.cs | 1,178 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class CTests
{
const int TimeLimit = 2000;
const double RelativeError = 1e-9;
[TestMethod, Timeout(TimeLimit)]
public void Test1()
{
const string input = @"20
";
const string output = @"0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0
";
Tester.InOutTest(Tasks.C.Solve, input, output);
}
}
}
| 11.560976 | 59 | 0.563291 | [
"CC0-1.0"
] | AconCavy/AtCoder.Tasks.CS | ABC-Like/AISING2020/Tests/CTests.cs | 474 | C# |
/*
* Copyright 2010 Joern Schou-Rode
*
* 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 Autofac;
using NCron.Fluent;
namespace NCron.Integration.Autofac
{
/// <summary>
/// Provides extension methods on the fluent API, allowing job registrations using Autofac as resolving container.
/// </summary>
public static class AutofacIntegration
{
/// <summary>
/// Gets or sets the root container from which nested containers are created for each job execution.
/// This property should usually only be set once, and its value is never disposed.
/// </summary>
public static IContainer RootContainer { private get; set; }
/// <summary>
/// Registers a job to be executed using Autofac as resolving container.
/// </summary>
/// <typeparam name="TJob">The type of job to be registered. Must implement <see cref="ICronJob"/>.</typeparam>
/// <param name="part">The fluent part upon which the job is to be registered.</param>
/// <returns>A part that allows chained fluent method calls.</returns>
public static JobPart Run<TJob>(this SchedulePart part)
where TJob : ICronJob
{
return part.With(() => RootContainer.CreateInnerContainer()).Run(c => c.Resolve<TJob>());
}
/// <summary>
/// Registers a job to be executed using Autofac as resolving container.
/// </summary>
/// <param name="part">The fluent part upon which the job is to be registered.</param>
/// <param name="serviceName">The name used when registering the component with Autofac.</param>
/// <returns>A part that allows chained fluent method calls.</returns>
public static JobPart Run(this SchedulePart part, string serviceName)
{
return part.With(() => RootContainer.CreateInnerContainer()).Run(c => c.Resolve<ICronJob>(serviceName));
}
}
}
| 44.298246 | 120 | 0.649901 | [
"Apache-2.0"
] | arisoyang/ncron | src/NCron.Integration.Autofac/AutofacIntegration.cs | 2,527 | C# |
/*******************************************************************************
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.S3.Model;
using Amazon.S3.Model.Internal.MarshallTransformations;
using Amazon.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Linq;
namespace Amazon.S3.Util
{
/// <summary>
/// Provides utilities used by the Amazon S3 client implementation.
/// These utilities might be useful to consumers of the Amazon S3
/// library.
/// </summary>
public static partial class AmazonS3Util
{
private static Dictionary<string, string> extensionToMime = new Dictionary<string, string>(200, StringComparer.OrdinalIgnoreCase)
{
{ ".ai", "application/postscript" },
{ ".aif", "audio/x-aiff" },
{ ".aifc", "audio/x-aiff" },
{ ".aiff", "audio/x-aiff" },
{ ".asc", "text/plain" },
{ ".au", "audio/basic" },
{ ".avi", "video/x-msvideo" },
{ ".bcpio", "application/x-bcpio" },
{ ".bin", "application/octet-stream" },
{ ".c", "text/plain" },
{ ".cc", "text/plain" },
{ ".ccad", "application/clariscad" },
{ ".cdf", "application/x-netcdf" },
{ ".class", "application/octet-stream" },
{ ".cpio", "application/x-cpio" },
{ ".cpp", "text/plain" },
{ ".cpt", "application/mac-compactpro" },
{ ".cs", "text/plain" },
{ ".csh", "application/x-csh" },
{ ".css", "text/css" },
{ ".dcr", "application/x-director" },
{ ".dir", "application/x-director" },
{ ".dms", "application/octet-stream" },
{ ".doc", "application/msword" },
{ ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ ".dot", "application/msword" },
{ ".drw", "application/drafting" },
{ ".dvi", "application/x-dvi" },
{ ".dwg", "application/acad" },
{ ".dxf", "application/dxf" },
{ ".dxr", "application/x-director" },
{ ".eps", "application/postscript" },
{ ".etx", "text/x-setext" },
{ ".exe", "application/octet-stream" },
{ ".ez", "application/andrew-inset" },
{ ".f", "text/plain" },
{ ".f90", "text/plain" },
{ ".fli", "video/x-fli" },
{ ".gif", "image/gif" },
{ ".gtar", "application/x-gtar" },
{ ".gz", "application/x-gzip" },
{ ".h", "text/plain" },
{ ".hdf", "application/x-hdf" },
{ ".hh", "text/plain" },
{ ".hqx", "application/mac-binhex40" },
{ ".htm", "text/html" },
{ ".html", "text/html" },
{ ".ice", "x-conference/x-cooltalk" },
{ ".ief", "image/ief" },
{ ".iges", "model/iges" },
{ ".igs", "model/iges" },
{ ".ips", "application/x-ipscript" },
{ ".ipx", "application/x-ipix" },
{ ".jpe", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".jpg", "image/jpeg" },
{ ".js", "application/x-javascript" },
{ ".json", "application/json" },
{ ".kar", "audio/midi" },
{ ".latex", "application/x-latex" },
{ ".lha", "application/octet-stream" },
{ ".lsp", "application/x-lisp" },
{ ".lzh", "application/octet-stream" },
{ ".m", "text/plain" },
{ ".m3u8", "application/x-mpegURL" },
{ ".man", "application/x-troff-man" },
{ ".me", "application/x-troff-me" },
{ ".mesh", "model/mesh" },
{ ".mid", "audio/midi" },
{ ".midi", "audio/midi" },
{ ".mime", "www/mime" },
{ ".mov", "video/quicktime" },
{ ".movie", "video/x-sgi-movie" },
{ ".mp2", "audio/mpeg" },
{ ".mp3", "audio/mpeg" },
{ ".mpe", "video/mpeg" },
{ ".mpeg", "video/mpeg" },
{ ".mpg", "video/mpeg" },
{ ".mpga", "audio/mpeg" },
{ ".ms", "application/x-troff-ms" },
{ ".msi", "application/x-ole-storage" },
{ ".msh", "model/mesh" },
{ ".nc", "application/x-netcdf" },
{ ".oda", "application/oda" },
{ ".pbm", "image/x-portable-bitmap" },
{ ".pdb", "chemical/x-pdb" },
{ ".pdf", "application/pdf" },
{ ".pgm", "image/x-portable-graymap" },
{ ".pgn", "application/x-chess-pgn" },
{ ".png", "image/png" },
{ ".pnm", "image/x-portable-anymap" },
{ ".pot", "application/mspowerpoint" },
{ ".ppm", "image/x-portable-pixmap" },
{ ".pps", "application/mspowerpoint" },
{ ".ppt", "application/mspowerpoint" },
{ ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
{ ".ppz", "application/mspowerpoint" },
{ ".pre", "application/x-freelance" },
{ ".prt", "application/pro_eng" },
{ ".ps", "application/postscript" },
{ ".qt", "video/quicktime" },
{ ".ra", "audio/x-realaudio" },
{ ".ram", "audio/x-pn-realaudio" },
{ ".ras", "image/cmu-raster" },
{ ".rgb", "image/x-rgb" },
{ ".rm", "audio/x-pn-realaudio" },
{ ".roff", "application/x-troff" },
{ ".rpm", "audio/x-pn-realaudio-plugin" },
{ ".rtf", "text/rtf" },
{ ".rtx", "text/richtext" },
{ ".scm", "application/x-lotusscreencam" },
{ ".set", "application/set" },
{ ".sgm", "text/sgml" },
{ ".sgml", "text/sgml" },
{ ".sh", "application/x-sh" },
{ ".shar", "application/x-shar" },
{ ".silo", "model/mesh" },
{ ".sit", "application/x-stuffit" },
{ ".skd", "application/x-koan" },
{ ".skm", "application/x-koan" },
{ ".skp", "application/x-koan" },
{ ".skt", "application/x-koan" },
{ ".smi", "application/smil" },
{ ".smil", "application/smil" },
{ ".snd", "audio/basic" },
{ ".sol", "application/solids" },
{ ".spl", "application/x-futuresplash" },
{ ".src", "application/x-wais-source" },
{ ".step", "application/STEP" },
{ ".stl", "application/SLA" },
{ ".stp", "application/STEP" },
{ ".sv4cpio", "application/x-sv4cpio" },
{ ".sv4crc", "application/x-sv4crc" },
{ ".svg", "image/svg+xml" },
{ ".swf", "application/x-shockwave-flash" },
{ ".t", "application/x-troff" },
{ ".tar", "application/x-tar" },
{ ".tcl", "application/x-tcl" },
{ ".tex", "application/x-tex" },
{ ".tif", "image/tiff" },
{ ".tiff", "image/tiff" },
{ ".tr", "application/x-troff" },
{ ".ts", "video/MP2T" },
{ ".tsi", "audio/TSP-audio" },
{ ".tsp", "application/dsptype" },
{ ".tsv", "text/tab-separated-values" },
{ ".txt", "text/plain" },
{ ".unv", "application/i-deas" },
{ ".ustar", "application/x-ustar" },
{ ".vcd", "application/x-cdlink" },
{ ".vda", "application/vda" },
{ ".vrml", "model/vrml" },
{ ".wav", "audio/x-wav" },
{ ".wrl", "model/vrml" },
{ ".xbm", "image/x-xbitmap" },
{ ".xlc", "application/vnd.ms-excel" },
{ ".xll", "application/vnd.ms-excel" },
{ ".xlm", "application/vnd.ms-excel" },
{ ".xls", "application/vnd.ms-excel" },
{ ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ ".xlw", "application/vnd.ms-excel" },
{ ".xml", "text/xml" },
{ ".xpm", "image/x-xpixmap" },
{ ".xwd", "image/x-xwindowdump" },
{ ".xyz", "chemical/x-pdb" },
{ ".zip", "application/zip" },
{ ".m4v", "video/x-m4v" },
{ ".webm", "video/webm" },
{ ".ogv", "video/ogv" },
{ ".xap", "application/x-silverlight-app" },
{ ".mp4", "video/mp4" },
{ ".wmv", "video/x-ms-wmv" }
};
/// <summary>
/// Determines MIME type from a file extension
/// </summary>
/// <param name="ext">The extension of the file</param>
/// <returns>The MIME type for the extension, or text/plain</returns>
public static string MimeTypeFromExtension(string ext)
{
if (extensionToMime.ContainsKey(ext))
{
return extensionToMime[ext];
}
else
{
return "application/octet-stream";
}
}
/// <summary>
/// URL encodes a string. If the path property is specified,
/// the accepted path characters {/+:} are not encoded.
/// </summary>
/// <param name="data">The string to encode</param>
/// <param name="path">Whether the string is a URL path or not</param>
/// <returns></returns>
public static string UrlEncode(string data, bool path)
{
return AWSSDKUtils.UrlEncode(data, path);
}
/// <summary>
/// Converts a non-seekable stream into a System.IO.MemoryStream.
/// A MemoryStream's position can be moved arbitrarily
/// </summary>
/// <param name="input">The stream to be converted</param>
/// <returns>A seekable MemoryStream</returns>
/// <remarks>MemoryStreams use byte arrays as their backing store.
/// Please use this judicially as it is likely that a very large
/// stream will cause system resources to be used up.
/// </remarks>
public static System.IO.Stream MakeStreamSeekable(System.IO.Stream input)
{
System.IO.MemoryStream output = new System.IO.MemoryStream();
const int readSize = 32 * 1024;
byte[] buffer = new byte[readSize];
int count = 0;
using (input)
{
while ((count = input.Read(buffer, 0, readSize)) > 0)
{
output.Write(buffer, 0, count);
}
}
output.Position = 0;
return output;
}
/// <summary>
/// Formats the current date as a GMT timestamp
/// </summary>
/// <returns>A GMT formatted string representation
/// of the current date and time
/// </returns>
public static string FormattedCurrentTimestamp
{
get
{
return AWSSDKUtils.FormattedCurrentTimestampGMT;
}
}
/// <summary>
/// Generates an MD5 Digest for the string-based content
/// </summary>
/// <param name="content">The content for which the MD5 Digest needs
/// to be computed.
/// </param>
/// <param name="fBase64Encode">Whether the returned checksum should be
/// base64 encoded.
/// </param>
/// <returns>A string representation of the hash with or w/o base64 encoding
/// </returns>
public static string GenerateChecksumForContent(string content, bool fBase64Encode)
{
return AWSSDKUtils.GenerateChecksumForContent(content, fBase64Encode);
}
internal static string ComputeEncodedMD5FromEncodedString(string base64EncodedString)
{
var unencodedValue = Convert.FromBase64String(base64EncodedString);
var valueMD5 = CryptoUtilFactory.CryptoInstance.ComputeMD5Hash(unencodedValue);
var encodedMD5 = Convert.ToBase64String(valueMD5);
return encodedMD5;
}
internal static void SetMetadataHeaders(IRequest request, MetadataCollection metadata)
{
foreach (var name in metadata.Keys)
{
request.Headers[name] = AWSConfigsS3.EnableUnicodeEncodingForObjectMetadata
? EscapeNonAscii(metadata[name]) : metadata[name];
}
}
/// <summary>
/// Only escape non-ascii characters in a string
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static string EscapeNonAscii(string text)
{
var sb = new StringBuilder("");
foreach (char c in text)
{
sb.Append(
((int)c > 127)
? Uri.EscapeDataString(c.ToString())
: c.ToString()
);
}
return sb.ToString();
}
internal static DateTime? ParseExpiresHeader(string rawValue, string requestId)
{
if (!string.IsNullOrEmpty(rawValue))
{
try
{
return S3Transforms.ToDateTime(rawValue);
}
catch (FormatException e)
{
throw new AmazonDateTimeUnmarshallingException(
requestId,
string.Empty,
string.Empty,
rawValue,
message: string.Format(
CultureInfo.InvariantCulture,
"The value {0} cannot be converted to a DateTime instance.",
rawValue),
innerException: e);
}
}
else
{
return default(DateTime);
}
}
/// <summary>
/// Version2 S3 buckets adhere to RFC 1035:
/// <list type="number">
/// <item>Less than 255 characters, with each label less than 63 characters.</item>
/// <item>Label must start with a letter</item>
/// <item>Label must end with a letter or digit</item>
/// <item>Label can have a string of letter, digits and hyphens in the middle.</item>
/// <item>Although names can be case-sensitive, no significance is attached to the case.</item>
/// <item>RFC 1123: Allow label to start with letter or digit (e.g. 3ware.com works)</item>
/// <item>RFC 2181: No restrictions apart from the length restrictions.</item>
/// </list>
/// S3 V2 will start with RFCs 1035 and 1123 and impose the following additional restrictions:
/// <list type="number">
/// <item>Length between 3 and 63 characters (to allow headroom for upper-level domains,
/// as well as to avoid separate length restrictions for bucket-name and its labels</item>
/// <item>Only lower-case to avoid user confusion.</item>
/// <item>No dotted-decimal IPv4-like strings</item>
/// </list>
/// </summary>
/// <param name="bucketName">The BucketName to validate if V2 addressing should be used</param>
/// <returns>True if the BucketName should use V2 bucket addressing, false otherwise</returns>
/// <seealso href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/index.html?BucketRestrictions.html">
/// S3 v2 Bucket restrictions</seealso>
public static bool ValidateV2Bucket(string bucketName)
{
if (String.IsNullOrEmpty(bucketName))
{
throw new ArgumentNullException("bucketName", "Please specify a bucket name");
}
if (bucketName.StartsWith("s3.amazonaws.com", StringComparison.Ordinal))
{
return false;
}
// If the entire S3 URL is passed instead of just the bucketName,
// strip out the Amazon S3 part of the URL
int idx = bucketName.IndexOf(".s3.amazonaws.com", StringComparison.Ordinal);
if (idx > 0)
{
bucketName = bucketName.Substring(0, idx);
}
if (bucketName.Length < S3Constants.MinBucketLength ||
bucketName.Length > S3Constants.MaxBucketLength ||
bucketName.StartsWith(".", StringComparison.Ordinal) ||
bucketName.EndsWith(".", StringComparison.Ordinal))
{
return false;
}
// Check not IPv4-like
Regex ipv4 = new Regex("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$");
if (ipv4.IsMatch(bucketName))
{
return false;
}
// Check each label
Regex v2Regex = new Regex("^[a-z0-9]([a-z0-9\\-]*[a-z0-9])?$");
string[] labels = bucketName.Split("\\.".ToCharArray());
foreach (string label in labels)
{
if (!v2Regex.IsMatch(label))
{
return false;
}
}
return true;
}
internal static void AddQueryStringParameter(StringBuilder queryString, string parameterName, string parameterValue)
{
AddQueryStringParameter(queryString, parameterName, parameterValue, null);
}
internal static void AddQueryStringParameter(StringBuilder queryString, string parameterName, string parameterValue, IDictionary<string, string> parameterMap)
{
if (queryString.Length > 0)
queryString.Append("&");
queryString.AppendFormat("{0}={1}", AWSSDKUtils.UrlEncode(parameterName, false), AWSSDKUtils.UrlEncode(parameterValue, false));
if (parameterMap != null)
parameterMap.Add(parameterName, parameterValue);
}
internal static string TagSetToQueryString(List<Tag> tags)
{
StringBuilder builder = new StringBuilder();
foreach(var tag in tags)
{
AddQueryStringParameter(builder, tag.Key, tag.Value);
}
return builder.ToString();
}
internal static void SerializeTagToXml(XmlWriter xmlWriter, Tag tag)
{
xmlWriter.WriteStartElement("Tag", "");
if (tag.IsSetKey())
{
xmlWriter.WriteElementString("Key", "", S3Transforms.ToXmlStringValue(tag.Key));
}
if (tag.IsSetValue())
{
xmlWriter.WriteElementString("Value", "", S3Transforms.ToXmlStringValue(tag.Value));
}
xmlWriter.WriteEndElement();
}
internal static void SerializeTagSetToXml(XmlWriter xmlWriter, List<Tag> tagset)
{
xmlWriter.WriteStartElement("TagSet", "");
if (tagset != null && tagset.Count > 0)
{
foreach (var tag in tagset)
{
SerializeTagToXml(xmlWriter, tag);
}
}
xmlWriter.WriteEndElement();
}
internal static string SerializeTaggingToXml(Tagging tagging)
{
var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = Encoding.UTF8, OmitXmlDeclaration = true }))
{
xmlWriter.WriteStartElement("Tagging", "");
SerializeTagSetToXml(xmlWriter, tagging.TagSet);
xmlWriter.WriteEndElement();
}
return stringWriter.ToString();
}
internal static void ParseAmzRestoreHeader(string header, out bool restoreInProgress, out DateTime? restoreExpiration)
{
const string ONGOING_REQUEST = "ongoing-request";
const string EXPIRY_DATE = "expiry-date";
restoreExpiration = null;
restoreInProgress = false;
if (header == null)
return;
int pos = header.IndexOf(ONGOING_REQUEST, StringComparison.Ordinal);
if (pos != -1)
{
int startPos = header.IndexOf('"', pos) + 1;
int endPos = header.IndexOf('"', startPos + 1);
string value = header.Substring(startPos, endPos - startPos);
bool parseBool;
if (Boolean.TryParse(value, out parseBool))
restoreInProgress = parseBool;
}
pos = header.IndexOf(EXPIRY_DATE, StringComparison.Ordinal);
if (pos != -1)
{
int startPos = header.IndexOf('"', pos) + 1;
int endPos = header.IndexOf('"', startPos + 1);
string value = header.Substring(startPos, endPos - startPos);
DateTime parseDate;
if (DateTime.TryParseExact(value, Amazon.Util.AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out parseDate))
restoreExpiration = parseDate;
}
}
internal static bool IsInstructionFile(string key)
{
return key.EndsWith(S3Constants.EncryptionInstructionfileSuffix, StringComparison.Ordinal) ||
key.EndsWith(S3Constants.EncryptionInstructionfileSuffixV2, StringComparison.Ordinal);
}
internal static string RemoveLeadingSlash(string key)
{
return key.StartsWith("/", StringComparison.Ordinal)
? key.Substring(1)
: key;
}
/// <summary>
/// Check if the request resource is an outpost resource
/// </summary>
/// <param name="request">The S3 request object</param>
/// <returns></returns>
internal static bool ResourcePathContainsOutpostsResource(IRequest request)
{
var separators = new char[] { '/', '?' };
Func<string, bool> IsOutpostResource = p => Arn.IsArn(p) && Arn.Parse(p).IsOutpostArn();
return IsOutpostResource(request.ResourcePath.Trim().Trim(separators))
|| request.PathResources.Any(pr => IsOutpostResource(pr.Value.Trim().Trim(separators)));
}
#if AWS_ASYNC_API
/// <summary>
/// Determines whether an S3 bucket exists or not.
/// </summary>
/// <param name="bucketName">The name of the bucket to check.</param>
/// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
/// <returns>False is returned in case S3 responds with a NoSuchBucket error.
/// True is returned in case of success, AccessDenied error or PermanentRedirect error.
/// An exception is thrown in case of any other error.</returns>
/// <remarks>This method calls GetACL for the bucket.</remarks>
public static async System.Threading.Tasks.Task<bool> DoesS3BucketExistV2Async(IAmazonS3 s3Client, string bucketName)
{
try
{
await s3Client.GetACLAsync(bucketName).ConfigureAwait(false);
}
catch (AmazonS3Exception e)
{
switch (e.ErrorCode)
{
// A redirect error or a forbidden error means the bucket exists.
case "AccessDenied":
case "PermanentRedirect":
return true;
case "NoSuchBucket":
return false;
default:
throw;
}
}
return true;
}
/// <summary>
/// Determines whether an S3 bucket exists or not.
/// This is done by:
/// 1. Creating a PreSigned Url for the bucket. To work with Signature V4 only regions, as
/// well as Signature V4-optional regions, we keep the expiry to within the maximum for V4
/// (which is one week).
/// 2. Making a HEAD request to the Url
/// </summary>
/// <param name="bucketName">The name of the bucket to check.</param>
/// <param name="s3Client">The Amazon S3 Client to use for S3 specific operations.</param>
/// <returns></returns>
[Obsolete("This method is deprecated: its behavior is inconsistent and always uses HTTP. Please use DoesS3BucketExistV2Async instead.")]
public static async System.Threading.Tasks.Task<bool> DoesS3BucketExistAsync(IAmazonS3 s3Client, string bucketName)
{
if (s3Client == null)
{
throw new ArgumentNullException("s3Client", "The s3Client cannot be null!");
}
if (String.IsNullOrEmpty(bucketName))
{
throw new ArgumentNullException("bucketName", "The bucketName cannot be null or the empty string!");
}
var request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Expires = s3Client.Config.CorrectedUtcNow.ToLocalTime().AddDays(1),
Verb = HttpVerb.HEAD,
Protocol = Protocol.HTTP
};
var url = s3Client.GetPreSignedURL(request);
var uri = new Uri(url);
var httpRequest = WebRequest.Create(uri) as HttpWebRequest;
httpRequest.Method = "HEAD";
var concreteClient = s3Client as AmazonS3Client;
if (concreteClient != null)
{
concreteClient.ConfigureProxy(httpRequest);
}
try
{
using (var httpResponse = await httpRequest.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse)
{
// If all went well, the bucket was found!
return true;
}
}
catch (WebException we)
{
using (var errorResponse = we.Response as HttpWebResponse)
{
if (errorResponse != null)
{
var code = errorResponse.StatusCode;
return code != HttpStatusCode.NotFound &&
code != HttpStatusCode.BadRequest;
}
// The Error Response is null which is indicative of either
// a bad request or some other problem
return false;
}
}
}
#endif
}
}
| 41.803807 | 167 | 0.500665 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/S3/Custom/Util/AmazonS3Util.cs | 28,554 | C# |
using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
// Standard ComponentSystem example with Pure ECS
//public class CubeFloaterSystem : ComponentSystem
//{
// public struct SystemData
// {
// public int Length;
// public ComponentDataArray<Position> position;
// [ReadOnly]
// public ComponentDataArray<CubeFloaterComponent> cubeFloaterComponent;
// }
// // Injects all entities with the specified ComponentDataArray's we specified in SystemData
// [Inject]
// private SystemData cubes;
// protected override void OnUpdate()
// {
// var dt = Time.deltaTime;
// for (int i = 0; i < cubes.Length; i++)
// {
// // Read
// var position = cubes.position[i];
// // Modify
// position.Value += cubes.cubeFloaterComponent[i].floatDirection * cubes.cubeFloaterComponent[i].floatSpeed * dt;
// // Write
// cubes.position[i] = position;
// }
// }
//}
// Same as above, but using the Job System instead
// This change alone made the application move from ~200fps to ~650fps at 10k entities
public class EntityFloaterSystem : JobComponentSystem
{
[BurstCompile]
struct EntityFloaterJob : IJobProcessComponentData<Position, FloaterComponent>
{
[ReadOnly] public float dt;
public void Execute([WriteOnly]ref Position position, [ReadOnly]ref FloaterComponent floater)
{
position.Value += floater.floatDirection * floater.floatSpeed * dt;
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var floaterJob = new EntityFloaterJob() { dt = Time.deltaTime };
return floaterJob.Schedule(this, inputDeps);
}
} | 30.269841 | 125 | 0.660199 | [
"MIT"
] | hedvik/Unity-Toybox | ExperimentalScenes/Assets/Scripts/ECS/Systems/Pure/EntityFloaterSystem.cs | 1,909 | 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/DirectML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="DML_RESAMPLE_OPERATOR_DESC" /> struct.</summary>
public static unsafe partial class DML_RESAMPLE_OPERATOR_DESCTests
{
/// <summary>Validates that the <see cref="DML_RESAMPLE_OPERATOR_DESC" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<DML_RESAMPLE_OPERATOR_DESC>(), Is.EqualTo(sizeof(DML_RESAMPLE_OPERATOR_DESC)));
}
/// <summary>Validates that the <see cref="DML_RESAMPLE_OPERATOR_DESC" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(DML_RESAMPLE_OPERATOR_DESC).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="DML_RESAMPLE_OPERATOR_DESC" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(DML_RESAMPLE_OPERATOR_DESC), Is.EqualTo(32));
}
else
{
Assert.That(sizeof(DML_RESAMPLE_OPERATOR_DESC), Is.EqualTo(20));
}
}
}
}
| 38.522727 | 145 | 0.658407 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/DirectML/DML_RESAMPLE_OPERATOR_DESCTests.cs | 1,697 | C# |
using ColorMixer.Tests;
using ColorMixer.Tests.Attributes;
using ColorMixer.ViewModels;
using FluentAssertions;
using Ninject;
using Xunit;
namespace ViewModels
{
public class Connection
{
private readonly IKernel kernel;
public Connection()
{
kernel = new StandardKernel();
kernel.Bind<IConnectionViewModel>()
.To<ConnectionViewModel>()
.InSingletonScope(); // system under test
}
[Fact]
public void SetsActivator()
=> kernel.Get<IConnectionViewModel>()
.Activator.Should().NotBeNull();
[Theory]
[InlineAutoNSubstituteData(nameof(IConnectionViewModel.From))]
public void SetsOutProperties(string property,
IOutConnectorViewModel initial,
IOutConnectorViewModel expected)
=> kernel.Get<IConnectionViewModel>()
.ShouldSetProperty(property, initial, expected);
[Theory]
[InlineAutoNSubstituteData(nameof(IConnectionViewModel.To))]
public void SetsInProperties(string property,
IInConnectorViewModel initial,
IInConnectorViewModel expected)
=> kernel.Get<IConnectionViewModel>()
.ShouldSetProperty(property, initial, expected);
}
} | 33 | 70 | 0.57989 | [
"MIT"
] | dimiboi/ColorMixer | ColorMixer.Tests/ViewModels/Connection.cs | 1,454 | C# |
using System;
namespace Leptonica
{
/// <summary>
/// Data structure to hold accumulating generated code for storing
/// and extracing serializable leptonica objects (e.g., pixa, recog).
/// </summary>
public class L_StrCode : LeptonicaObjectBase
{
public L_StrCode(IntPtr pointer) : base(pointer) { }
}
}
| 24.642857 | 73 | 0.655072 | [
"Apache-2.0"
] | itoledo/Birdie.Tesseract | tvn-cosine.imaging/tvn-cosine.imaging.leptonica/tvn-cosine.imaging.leptonica/Definitions/StringCode/L_StrCode.cs | 347 | C# |
using GraphicsComposerLib.Svg.Attributes;
using GraphicsComposerLib.Svg.Elements.Categories;
using GraphicsComposerLib.Svg.Values;
namespace GraphicsComposerLib.Svg.Elements.Animation
{
/// <summary>
/// The 'animate' SVG element is used to animate an attribute or property of an element over time.
/// It's normally inserted inside the element or referenced by the href attribute of the target element.
/// http://docs.w3cub.com/svg/element/animate/
/// https://www.w3.org/TR/smil-animation/
/// </summary>
public sealed class SvgElementAnimate : SvgElement, ISvgAnimationElement
{
public static SvgElementAnimate Create()
{
return new SvgElementAnimate();
}
public static SvgElementAnimate Create(string id)
{
return new SvgElementAnimate() { Id = id };
}
public override string ElementName => "animate";
//public SvgEavString<SvgElementAnimate> Id
//{
// get
// {
// var attrInfo = SvgAttributes.Id;
// ISvgAttributeValue attrValue;
// if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
// return attrValue as SvgEavString<SvgElementAnimate>;
// var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
// AttributesTable.Add(attrInfo.Id, attrValue1);
// return attrValue1;
// }
//}
public SvgEavString<SvgElementAnimate> XmlBase
{
get
{
var attrInfo = SvgAttributeUtils.XmlBase;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavString<SvgElementAnimate> XmlLanguage
{
get
{
var attrInfo = SvgAttributeUtils.XmlLanguage;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavStruct<bool, SvgElementAnimate> ExternalResourcesRequired
{
get
{
var attrInfo = SvgAttributeUtils.ExternalResourcesRequired;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavStruct<bool, SvgElementAnimate>;
var attrValue1 = new SvgEavStruct<bool, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavAttribute<SvgElementAnimate> Attribute
{
get
{
var attrInfo = SvgAttributeUtils.AttributeName;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavAttribute<SvgElementAnimate>;
var attrValue1 = new SvgEavAttribute<SvgElementAnimate>(this);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAttributeType, SvgElementAnimate> AttributeType
{
get
{
var attrInfo = SvgAttributeUtils.AttributeType;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAttributeType, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAttributeType, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavString<SvgElementAnimate> From
{
get
{
var attrInfo = SvgAttributeUtils.From;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavString<SvgElementAnimate> To
{
get
{
var attrInfo = SvgAttributeUtils.To;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavString<SvgElementAnimate> By
{
get
{
var attrInfo = SvgAttributeUtils.By;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavString<SvgElementAnimate> Values
{
get
{
var attrInfo = SvgAttributeUtils.Values;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavString<SvgElementAnimate>;
var attrValue1 = new SvgEavString<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavClock<SvgElementAnimate> Duration
{
get
{
var attrInfo = SvgAttributeUtils.Duration;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavClock<SvgElementAnimate>;
var attrValue1 = new SvgEavClock<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavClock<SvgElementAnimate> RepeatDuration
{
get
{
var attrInfo = SvgAttributeUtils.RepeatDuration;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavClock<SvgElementAnimate>;
var attrValue1 = new SvgEavClock<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavClock<SvgElementAnimate> MinDuration
{
get
{
var attrInfo = SvgAttributeUtils.Min;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavClock<SvgElementAnimate>;
var attrValue1 = new SvgEavClock<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavClock<SvgElementAnimate> MaxDuration
{
get
{
var attrInfo = SvgAttributeUtils.Max;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavClock<SvgElementAnimate>;
var attrValue1 = new SvgEavClock<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEavNumber<SvgElementAnimate> RepeatCount
{
get
{
var attrInfo = SvgAttributeUtils.RepeatCount;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEavNumber<SvgElementAnimate>;
var attrValue1 = new SvgEavNumber<SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAnimationFill, SvgElementAnimate> Fill
{
get
{
var attrInfo = SvgAttributeUtils.Fill;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAnimationFill, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAnimationFill, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAnimationAdditive, SvgElementAnimate> Additive
{
get
{
var attrInfo = SvgAttributeUtils.Additive;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAnimationAdditive, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAnimationAdditive, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAnimationAccumulate, SvgElementAnimate> Accumulate
{
get
{
var attrInfo = SvgAttributeUtils.Accumulate;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAnimationAccumulate, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAnimationAccumulate, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAnimationRestart, SvgElementAnimate> Restart
{
get
{
var attrInfo = SvgAttributeUtils.Restart;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAnimationRestart, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAnimationRestart, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueAnimationCalcMode, SvgElementAnimate> CalcMode
{
get
{
var attrInfo = SvgAttributeUtils.CalcMode;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueAnimationCalcMode, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueAnimationCalcMode, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
public SvgEav<SvgValueLengthsList, SvgElementAnimate> KeyTimes
{
get
{
var attrInfo = SvgAttributeUtils.KeyTimes;
ISvgAttributeValue attrValue;
if (AttributesTable.TryGetValue(attrInfo.Id, out attrValue))
return attrValue as SvgEav<SvgValueLengthsList, SvgElementAnimate>;
var attrValue1 = new SvgEav<SvgValueLengthsList, SvgElementAnimate>(this, attrInfo);
AttributesTable.Add(attrInfo.Id, attrValue1);
return attrValue1;
}
}
//TODO: Implement the begin and end attributes http://docs.w3cub.com/svg/attribute/begin/
//TODO: Implement the keySplines attribute http://docs.w3cub.com/svg/attribute/keysplines/http://docs.w3cub.com/svg/attribute/keysplines/
private SvgElementAnimate()
{
}
}
} | 34.29771 | 145 | 0.581942 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | GraphicsComposerLib/GraphicsComposerLib.Svg/Elements/Animation/SvgElementAnimate.cs | 13,481 | C# |
using System.IO;
using System.Linq;
using NUnit.Framework;
using ObjectApproval;
[TestFixture]
public class NuGetPackageRootTest
{
[Test]
public void WithNuGetPackageRoot()
{
var combine = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "../../FakeNuGetPackageRoot"));
var nuGetPackageRoot = Path.GetFullPath(combine);
var result = AddinFinder.ScanNuGetPackageRoot(nuGetPackageRoot)
.Select(s=>s.Replace(@"\\", @"\").Replace(combine, "")).ToList();
ObjectApprover.VerifyWithJson(result);
}
} | 30.368421 | 125 | 0.696707 | [
"MIT"
] | LaudateCorpus1/Fody | Fody.Tests/NuGetPackageRootTest.cs | 577 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Reflection
{
public class CustomAttributeData
{
#region Public Static Members
public static IList<CustomAttributeData> GetCustomAttributes(MemberInfo target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(Module target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(Assembly target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetCustomAttributesData();
}
public static IList<CustomAttributeData> GetCustomAttributes(ParameterInfo target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
return target.GetCustomAttributesData();
}
#endregion
#region Internal Static Members
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
{
Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder<Attribute> pcas);
return GetCombinedList(cad, ref pcas);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target)
{
Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder<Attribute> pcas);
return GetCombinedList(cad, ref pcas);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target)
{
Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder<Attribute> pcas);
return GetCombinedList(cad, ref pcas);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target)
{
Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target)
{
Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target)
{
Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target)
{
Debug.Assert(target != null);
if (target.IsResource())
return new List<CustomAttributeData>();
return GetCustomAttributes(target, target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target)
{
Debug.Assert(target != null);
// No pseudo attributes for RuntimeAssembly
return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
{
Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule()!, target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder<Attribute> pcas);
return GetCombinedList(cad, ref pcas);
}
private static IList<CustomAttributeData> GetCombinedList(IList<CustomAttributeData> customAttributes, ref RuntimeType.ListBuilder<Attribute> pseudoAttributes)
{
if (pseudoAttributes.Count == 0)
return customAttributes;
CustomAttributeData[] pca = new CustomAttributeData[customAttributes.Count + pseudoAttributes.Count];
customAttributes.CopyTo(pca, pseudoAttributes.Count);
for (int i = 0; i < pseudoAttributes.Count; i++)
{
pca[i] = new CustomAttributeData(pseudoAttributes[i]);
}
return Array.AsReadOnly(pca);
}
#endregion
#region Private Static Methods
private static CustomAttributeEncoding TypeToCustomAttributeEncoding(RuntimeType type)
{
if (type == typeof(int))
return CustomAttributeEncoding.Int32;
if (type.IsEnum)
return CustomAttributeEncoding.Enum;
if (type == typeof(string))
return CustomAttributeEncoding.String;
if (type == typeof(Type))
return CustomAttributeEncoding.Type;
if (type == typeof(object))
return CustomAttributeEncoding.Object;
if (type.IsArray)
return CustomAttributeEncoding.Array;
if (type == typeof(char))
return CustomAttributeEncoding.Char;
if (type == typeof(bool))
return CustomAttributeEncoding.Boolean;
if (type == typeof(byte))
return CustomAttributeEncoding.Byte;
if (type == typeof(sbyte))
return CustomAttributeEncoding.SByte;
if (type == typeof(short))
return CustomAttributeEncoding.Int16;
if (type == typeof(ushort))
return CustomAttributeEncoding.UInt16;
if (type == typeof(uint))
return CustomAttributeEncoding.UInt32;
if (type == typeof(long))
return CustomAttributeEncoding.Int64;
if (type == typeof(ulong))
return CustomAttributeEncoding.UInt64;
if (type == typeof(float))
return CustomAttributeEncoding.Float;
if (type == typeof(double))
return CustomAttributeEncoding.Double;
// System.Enum is neither an Enum nor a Class
if (type == typeof(Enum))
return CustomAttributeEncoding.Object;
if (type.IsClass)
return CustomAttributeEncoding.Object;
if (type.IsInterface)
return CustomAttributeEncoding.Object;
if (type.IsValueType)
return CustomAttributeEncoding.Undefined;
throw new ArgumentException(SR.Argument_InvalidKindOfTypeForCA, nameof(type));
}
private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType)
{
CustomAttributeEncoding encodedType = CustomAttributeData.TypeToCustomAttributeEncoding(parameterType);
CustomAttributeEncoding encodedArrayType = CustomAttributeEncoding.Undefined;
CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined;
string? enumName = null;
if (encodedType == CustomAttributeEncoding.Array)
{
parameterType = (RuntimeType)parameterType.GetElementType();
encodedArrayType = CustomAttributeData.TypeToCustomAttributeEncoding(parameterType);
}
if (encodedType == CustomAttributeEncoding.Enum || encodedArrayType == CustomAttributeEncoding.Enum)
{
encodedEnumType = TypeToCustomAttributeEncoding((RuntimeType)Enum.GetUnderlyingType(parameterType));
enumName = parameterType.AssemblyQualifiedName;
}
return new CustomAttributeType(encodedType, encodedArrayType, encodedEnumType, enumName);
}
private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget)
{
CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget);
CustomAttributeData[] customAttributes = new CustomAttributeData[records.Length];
for (int i = 0; i < records.Length; i++)
customAttributes[i] = new CustomAttributeData(module, records[i].tkCtor, in records[i].blob);
return Array.AsReadOnly(customAttributes);
}
#endregion
#region Internal Static Members
internal static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken)
{
MetadataImport scope = module.MetadataImport;
scope.EnumCustomAttributes(targetToken, out MetadataEnumResult tkCustomAttributeTokens);
if (tkCustomAttributeTokens.Length == 0)
{
return Array.Empty<CustomAttributeRecord>();
}
CustomAttributeRecord[] records = new CustomAttributeRecord[tkCustomAttributeTokens.Length];
for (int i = 0; i < records.Length; i++)
{
scope.GetCustomAttributeProps(tkCustomAttributeTokens[i],
out records[i].tkCtor.Value, out records[i].blob);
}
return records;
}
internal static CustomAttributeTypedArgument Filter(IList<CustomAttributeData> attrs, Type? caType, int parameter)
{
for (int i = 0; i < attrs.Count; i++)
{
if (attrs[i].Constructor.DeclaringType == caType)
{
return attrs[i].ConstructorArguments[parameter];
}
}
return default;
}
#endregion
private ConstructorInfo m_ctor = null!;
private readonly RuntimeModule m_scope = null!;
private readonly MemberInfo[] m_members = null!;
private readonly CustomAttributeCtorParameter[] m_ctorParams = null!;
private readonly CustomAttributeNamedParameter[] m_namedParams = null!;
private IList<CustomAttributeTypedArgument> m_typedCtorArgs = null!;
private IList<CustomAttributeNamedArgument> m_namedArgs = null!;
#region Constructor
protected CustomAttributeData()
{
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern",
Justification = "property setters and fiels which are accessed by any attribute instantiation which is present in the code linker has analyzed." +
"As such enumerating all fields and properties may return different results fater trimming" +
"but all those which are needed to actually have data should be there.")]
private CustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob)
{
m_scope = scope;
m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken)!;
ParameterInfo[] parameters = m_ctor.GetParametersNoCopy();
m_ctorParams = new CustomAttributeCtorParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parameters[i].ParameterType));
FieldInfo[] fields = m_ctor.DeclaringType!.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length];
for (int i = 0; i < fields.Length; i++)
m_namedParams[i] = new CustomAttributeNamedParameter(
fields[i].Name, CustomAttributeEncoding.Field, InitCustomAttributeType((RuntimeType)fields[i].FieldType));
for (int i = 0; i < properties.Length; i++)
m_namedParams[i + fields.Length] = new CustomAttributeNamedParameter(
properties[i].Name, CustomAttributeEncoding.Property, InitCustomAttributeType((RuntimeType)properties[i].PropertyType));
m_members = new MemberInfo[fields.Length + properties.Length];
fields.CopyTo(m_members, 0);
properties.CopyTo(m_members, fields.Length);
CustomAttributeEncodedArgument.ParseAttributeArguments(blob, ref m_ctorParams, ref m_namedParams, m_scope);
}
#endregion
#region Pseudo Custom Attribute Constructor
internal CustomAttributeData(Attribute attribute)
{
if (attribute is DllImportAttribute dllImportAttribute)
Init(dllImportAttribute);
else if (attribute is FieldOffsetAttribute fieldOffsetAttribute)
Init(fieldOffsetAttribute);
else if (attribute is MarshalAsAttribute marshalAsAttribute)
Init(marshalAsAttribute);
else if (attribute is TypeForwardedToAttribute typeForwardedToAttribute)
Init(typeForwardedToAttribute);
else
Init(attribute);
}
private void Init(DllImportAttribute dllImport)
{
Type type = typeof(DllImportAttribute);
m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[]
{
new CustomAttributeTypedArgument(dllImport.Value),
});
m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[]
{
new CustomAttributeNamedArgument(type.GetField("EntryPoint")!, dllImport.EntryPoint),
new CustomAttributeNamedArgument(type.GetField("CharSet")!, dllImport.CharSet),
new CustomAttributeNamedArgument(type.GetField("ExactSpelling")!, dllImport.ExactSpelling),
new CustomAttributeNamedArgument(type.GetField("SetLastError")!, dllImport.SetLastError),
new CustomAttributeNamedArgument(type.GetField("PreserveSig")!, dllImport.PreserveSig),
new CustomAttributeNamedArgument(type.GetField("CallingConvention")!, dllImport.CallingConvention),
new CustomAttributeNamedArgument(type.GetField("BestFitMapping")!, dllImport.BestFitMapping),
new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar")!, dllImport.ThrowOnUnmappableChar)
});
}
private void Init(FieldOffsetAttribute fieldOffset)
{
m_ctor = typeof(FieldOffsetAttribute).GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[] {
new CustomAttributeTypedArgument(fieldOffset.Value)
});
m_namedArgs = Array.AsReadOnly(Array.Empty<CustomAttributeNamedArgument>());
}
private void Init(MarshalAsAttribute marshalAs)
{
Type type = typeof(MarshalAsAttribute);
m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[]
{
new CustomAttributeTypedArgument(marshalAs.Value),
});
int i = 3; // ArraySubType, SizeParamIndex, SizeConst
if (marshalAs.MarshalType != null) i++;
if (marshalAs.MarshalTypeRef != null) i++;
if (marshalAs.MarshalCookie != null) i++;
i++; // IidParameterIndex
i++; // SafeArraySubType
if (marshalAs.SafeArrayUserDefinedSubType != null) i++;
CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[i];
// For compatibility with previous runtimes, we always include the following 5 attributes, regardless
// of if they apply to the UnmanagedType being marshaled or not.
i = 0;
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType")!, marshalAs.ArraySubType);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex")!, marshalAs.SizeParamIndex);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst")!, marshalAs.SizeConst);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex")!, marshalAs.IidParameterIndex);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType")!, marshalAs.SafeArraySubType);
if (marshalAs.MarshalType != null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType")!, marshalAs.MarshalType);
if (marshalAs.MarshalTypeRef != null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef")!, marshalAs.MarshalTypeRef);
if (marshalAs.MarshalCookie != null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie")!, marshalAs.MarshalCookie);
if (marshalAs.SafeArrayUserDefinedSubType != null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType")!, marshalAs.SafeArrayUserDefinedSubType);
m_namedArgs = Array.AsReadOnly(namedArgs);
}
private void Init(TypeForwardedToAttribute forwardedTo)
{
Type type = typeof(TypeForwardedToAttribute);
Type[] sig = new Type[] { typeof(Type) };
m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!;
CustomAttributeTypedArgument[] typedArgs = new CustomAttributeTypedArgument[1];
typedArgs[0] = new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination);
m_typedCtorArgs = Array.AsReadOnly(typedArgs);
CustomAttributeNamedArgument[] namedArgs = Array.Empty<CustomAttributeNamedArgument>();
m_namedArgs = Array.AsReadOnly(namedArgs);
}
private void Init(object pca)
{
m_ctor = pca.GetType().GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(Array.Empty<CustomAttributeTypedArgument>());
m_namedArgs = Array.AsReadOnly(Array.Empty<CustomAttributeNamedArgument>());
}
#endregion
#region Object Override
public override string ToString()
{
string ctorArgs = "";
for (int i = 0; i < ConstructorArguments.Count; i++)
ctorArgs += string.Format(i == 0 ? "{0}" : ", {0}", ConstructorArguments[i]);
string namedArgs = "";
for (int i = 0; i < NamedArguments.Count; i++)
namedArgs += string.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", NamedArguments[i]);
return string.Format("[{0}({1}{2})]", Constructor.DeclaringType!.FullName, ctorArgs, namedArgs);
}
public override int GetHashCode() => base.GetHashCode();
public override bool Equals(object? obj) => obj == (object)this;
#endregion
#region Public Members
public virtual Type AttributeType => Constructor.DeclaringType!;
public virtual ConstructorInfo Constructor => m_ctor;
public virtual IList<CustomAttributeTypedArgument> ConstructorArguments
{
get
{
if (m_typedCtorArgs == null)
{
CustomAttributeTypedArgument[] typedCtorArgs = new CustomAttributeTypedArgument[m_ctorParams.Length];
for (int i = 0; i < typedCtorArgs.Length; i++)
{
CustomAttributeEncodedArgument encodedArg = m_ctorParams[i].CustomAttributeEncodedArgument;
typedCtorArgs[i] = new CustomAttributeTypedArgument(m_scope, encodedArg);
}
m_typedCtorArgs = Array.AsReadOnly(typedCtorArgs);
}
return m_typedCtorArgs;
}
}
public virtual IList<CustomAttributeNamedArgument> NamedArguments
{
get
{
if (m_namedArgs == null)
{
if (m_namedParams == null)
return null!;
int cNamedArgs = 0;
for (int i = 0; i < m_namedParams.Length; i++)
{
if (m_namedParams[i].EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined)
cNamedArgs++;
}
CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[cNamedArgs];
for (int i = 0, j = 0; i < m_namedParams.Length; i++)
{
if (m_namedParams[i].EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined)
namedArgs[j++] = new CustomAttributeNamedArgument(
m_members[i], new CustomAttributeTypedArgument(m_scope, m_namedParams[i].EncodedArgument));
}
m_namedArgs = Array.AsReadOnly(namedArgs);
}
return m_namedArgs;
}
}
#endregion
}
public readonly partial struct CustomAttributeTypedArgument
{
#region Private Static Methods
private static Type CustomAttributeEncodingToType(CustomAttributeEncoding encodedType)
{
return encodedType switch
{
CustomAttributeEncoding.Enum => typeof(Enum),
CustomAttributeEncoding.Int32 => typeof(int),
CustomAttributeEncoding.String => typeof(string),
CustomAttributeEncoding.Type => typeof(Type),
CustomAttributeEncoding.Array => typeof(Array),
CustomAttributeEncoding.Char => typeof(char),
CustomAttributeEncoding.Boolean => typeof(bool),
CustomAttributeEncoding.SByte => typeof(sbyte),
CustomAttributeEncoding.Byte => typeof(byte),
CustomAttributeEncoding.Int16 => typeof(short),
CustomAttributeEncoding.UInt16 => typeof(ushort),
CustomAttributeEncoding.UInt32 => typeof(uint),
CustomAttributeEncoding.Int64 => typeof(long),
CustomAttributeEncoding.UInt64 => typeof(ulong),
CustomAttributeEncoding.Float => typeof(float),
CustomAttributeEncoding.Double => typeof(double),
CustomAttributeEncoding.Object => typeof(object),
_ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType)),
};
}
private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType)
{
switch (encodedType)
{
case CustomAttributeEncoding.Boolean:
return (byte)val != 0;
case CustomAttributeEncoding.Char:
return (char)val;
case CustomAttributeEncoding.Byte:
return (byte)val;
case CustomAttributeEncoding.SByte:
return (sbyte)val;
case CustomAttributeEncoding.Int16:
return (short)val;
case CustomAttributeEncoding.UInt16:
return (ushort)val;
case CustomAttributeEncoding.Int32:
return (int)val;
case CustomAttributeEncoding.UInt32:
return (uint)val;
case CustomAttributeEncoding.Int64:
return (long)val;
case CustomAttributeEncoding.UInt64:
return (ulong)val;
case CustomAttributeEncoding.Float:
unsafe { return *(float*)&val; }
case CustomAttributeEncoding.Double:
unsafe { return *(double*)&val; }
default:
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)val), nameof(val));
}
}
private static RuntimeType ResolveType(RuntimeModule scope, string typeName)
{
RuntimeType type = RuntimeTypeHandle.GetTypeByNameUsingCARules(typeName, scope);
if (type == null)
throw new InvalidOperationException(
SR.Format(SR.Arg_CATypeResolutionFailed, typeName));
return type;
}
#endregion
private static object CanonicalizeValue(object value)
{
Debug.Assert(value != null);
if (value.GetType().IsEnum)
{
return ((Enum)value).GetValue();
}
return value;
}
internal CustomAttributeTypedArgument(RuntimeModule scope, CustomAttributeEncodedArgument encodedArg)
{
CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType;
if (encodedType == CustomAttributeEncoding.Undefined)
throw new ArgumentException(null, nameof(encodedArg));
if (encodedType == CustomAttributeEncoding.Enum)
{
m_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
m_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType);
}
else if (encodedType == CustomAttributeEncoding.String)
{
m_argumentType = typeof(string);
m_value = encodedArg.StringValue;
}
else if (encodedType == CustomAttributeEncoding.Type)
{
m_argumentType = typeof(Type);
m_value = null;
if (encodedArg.StringValue != null)
m_value = ResolveType(scope, encodedArg.StringValue);
}
else if (encodedType == CustomAttributeEncoding.Array)
{
encodedType = encodedArg.CustomAttributeType.EncodedArrayType;
Type elementType;
if (encodedType == CustomAttributeEncoding.Enum)
{
elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
}
else
{
elementType = CustomAttributeEncodingToType(encodedType);
}
m_argumentType = elementType.MakeArrayType();
if (encodedArg.ArrayValue == null)
{
m_value = null;
}
else
{
CustomAttributeTypedArgument[] arrayValue = new CustomAttributeTypedArgument[encodedArg.ArrayValue.Length];
for (int i = 0; i < arrayValue.Length; i++)
arrayValue[i] = new CustomAttributeTypedArgument(scope, encodedArg.ArrayValue[i]);
m_value = Array.AsReadOnly(arrayValue);
}
}
else
{
m_argumentType = CustomAttributeEncodingToType(encodedType);
m_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedType);
}
}
}
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeRecord
{
internal ConstArray blob;
internal MetadataToken tkCtor;
public CustomAttributeRecord(int token, ConstArray blob)
{
tkCtor = new MetadataToken(token);
this.blob = blob;
}
}
internal enum CustomAttributeEncoding : int
{
Undefined = 0,
Boolean = CorElementType.ELEMENT_TYPE_BOOLEAN,
Char = CorElementType.ELEMENT_TYPE_CHAR,
SByte = CorElementType.ELEMENT_TYPE_I1,
Byte = CorElementType.ELEMENT_TYPE_U1,
Int16 = CorElementType.ELEMENT_TYPE_I2,
UInt16 = CorElementType.ELEMENT_TYPE_U2,
Int32 = CorElementType.ELEMENT_TYPE_I4,
UInt32 = CorElementType.ELEMENT_TYPE_U4,
Int64 = CorElementType.ELEMENT_TYPE_I8,
UInt64 = CorElementType.ELEMENT_TYPE_U8,
Float = CorElementType.ELEMENT_TYPE_R4,
Double = CorElementType.ELEMENT_TYPE_R8,
String = CorElementType.ELEMENT_TYPE_STRING,
Array = CorElementType.ELEMENT_TYPE_SZARRAY,
Type = 0x50,
Object = 0x51,
Field = 0x53,
Property = 0x54,
Enum = 0x55
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeEncodedArgument
{
private readonly long m_primitiveValue;
private readonly CustomAttributeEncodedArgument[] m_arrayValue;
private readonly string m_stringValue;
private readonly CustomAttributeType m_type;
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void ParseAttributeArguments(
IntPtr pCa,
int cCa,
ref CustomAttributeCtorParameter[] CustomAttributeCtorParameters,
ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument,
RuntimeAssembly assembly);
internal static void ParseAttributeArguments(ConstArray attributeBlob,
ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
RuntimeModule customAttributeModule)
{
if (customAttributeModule == null)
throw new ArgumentNullException(nameof(customAttributeModule));
Debug.Assert(customAttributeCtorParameters != null);
Debug.Assert(customAttributeNamedParameters != null);
if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0)
{
ParseAttributeArguments(
attributeBlob.Signature,
(int)attributeBlob.Length,
ref customAttributeCtorParameters,
ref customAttributeNamedParameters,
(RuntimeAssembly)customAttributeModule.Assembly);
}
}
public CustomAttributeType CustomAttributeType => m_type;
public long PrimitiveValue => m_primitiveValue;
public CustomAttributeEncodedArgument[] ArrayValue => m_arrayValue;
public string StringValue => m_stringValue;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeNamedParameter
{
private readonly string m_argumentName;
private readonly CustomAttributeEncoding m_fieldOrProperty;
private readonly CustomAttributeEncoding m_padding;
private readonly CustomAttributeType m_type;
private readonly CustomAttributeEncodedArgument m_encodedArgument;
public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type)
{
if (argumentName == null)
throw new ArgumentNullException(nameof(argumentName));
m_argumentName = argumentName;
m_fieldOrProperty = fieldOrProperty;
m_padding = fieldOrProperty;
m_type = type;
m_encodedArgument = default;
}
public CustomAttributeEncodedArgument EncodedArgument => m_encodedArgument;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeCtorParameter
{
private readonly CustomAttributeType m_type;
private readonly CustomAttributeEncodedArgument m_encodedArgument;
public CustomAttributeCtorParameter(CustomAttributeType type)
{
m_type = type;
m_encodedArgument = default;
}
public CustomAttributeEncodedArgument CustomAttributeEncodedArgument => m_encodedArgument;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeType
{
/// The most complicated type is an enum[] in which case...
private readonly string? m_enumName; // ...enum name
private readonly CustomAttributeEncoding m_encodedType; // ...array
private readonly CustomAttributeEncoding m_encodedEnumType; // ...enum
private readonly CustomAttributeEncoding m_encodedArrayType; // ...enum type
private readonly CustomAttributeEncoding m_padding;
public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType,
CustomAttributeEncoding encodedEnumType, string? enumName)
{
m_encodedType = encodedType;
m_encodedArrayType = encodedArrayType;
m_encodedEnumType = encodedEnumType;
m_enumName = enumName;
m_padding = m_encodedType;
}
public CustomAttributeEncoding EncodedType => m_encodedType;
public CustomAttributeEncoding EncodedEnumType => m_encodedEnumType;
public CustomAttributeEncoding EncodedArrayType => m_encodedArrayType;
public string? EnumName => m_enumName;
}
internal static unsafe class CustomAttribute
{
private static readonly RuntimeType Type_RuntimeType = (RuntimeType)typeof(RuntimeType);
private static readonly RuntimeType Type_Type = (RuntimeType)typeof(Type);
#region Internal Static Members
internal static bool IsDefined(RuntimeType type, RuntimeType? caType, bool inherit)
{
Debug.Assert(type != null);
if (type.GetElementType() != null)
return false;
if (PseudoCustomAttribute.IsDefined(type, caType))
return true;
if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType))
return true;
if (!inherit)
return false;
type = (type.BaseType as RuntimeType)!;
while (type != null)
{
if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit))
return true;
type = (type.BaseType as RuntimeType)!;
}
return false;
}
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Debug.Assert(method != null);
Debug.Assert(caType != null);
if (PseudoCustomAttribute.IsDefined(method, caType))
return true;
if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType))
return true;
if (!inherit)
return false;
method = method.GetParentDefinition()!;
while (method != null)
{
if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit))
return true;
method = method.GetParentDefinition()!;
}
return false;
}
internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Debug.Assert(ctor != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeConstructorInfo
return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType);
}
internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType)
{
Debug.Assert(property != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimePropertyInfo
return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType)
{
Debug.Assert(e != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeEventInfo
return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
{
Debug.Assert(field != null);
Debug.Assert(caType != null);
if (PseudoCustomAttribute.IsDefined(field, caType))
return true;
return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
{
Debug.Assert(parameter != null);
Debug.Assert(caType != null);
if (PseudoCustomAttribute.IsDefined(parameter, caType))
return true;
return IsCustomAttributeDefined(parameter.GetRuntimeModule()!, parameter.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
Debug.Assert(assembly != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeAssembly
return IsCustomAttributeDefined((assembly.ManifestModule as RuntimeModule)!, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
}
internal static bool IsDefined(RuntimeModule module, RuntimeType caType)
{
Debug.Assert(module != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeModule
return IsCustomAttributeDefined(module, module.MetadataToken, caType);
}
internal static object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit)
{
Debug.Assert(type != null);
Debug.Assert(caType != null);
if (type.GetElementType() != null)
return (caType.IsValueType) ? Array.Empty<object>() : CreateAttributeArrayHelper(caType, 0);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
type = (type.GetGenericTypeDefinition() as RuntimeType)!;
PseudoCustomAttribute.GetCustomAttributes(type, caType, out RuntimeType.ListBuilder<Attribute> pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
object[] attributes = GetCustomAttributes(type.GetRuntimeModule(), type.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
RuntimeType.ListBuilder<object> result = default;
bool mustBeInheritable = false;
bool useObjectArray = (caType.IsValueType || caType.ContainsGenericParameters);
RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : caType;
for (int i = 0; i < pcas.Count; i++)
result.Add(pcas[i]);
while (type != (RuntimeType)typeof(object) && type != null)
{
AddCustomAttributes(ref result, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, result);
mustBeInheritable = true;
type = (type.BaseType as RuntimeType)!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
for (int i = 0; i < result.Count; i++)
{
typedResult[i] = result[i];
}
return typedResult;
}
internal static object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Debug.Assert(method != null);
Debug.Assert(caType != null);
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
method = (method.GetGenericMethodDefinition() as RuntimeMethodInfo)!;
PseudoCustomAttribute.GetCustomAttributes(method, caType, out RuntimeType.ListBuilder<Attribute> pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
object[] attributes = GetCustomAttributes(method.GetRuntimeModule(), method.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
RuntimeType.ListBuilder<object> result = default;
bool mustBeInheritable = false;
bool useObjectArray = (caType.IsValueType || caType.ContainsGenericParameters);
RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : caType;
for (int i = 0; i < pcas.Count; i++)
result.Add(pcas[i]);
while (method != null)
{
AddCustomAttributes(ref result, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, result);
mustBeInheritable = true;
method = method.GetParentDefinition()!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
for (int i = 0; i < result.Count; i++)
{
typedResult[i] = result[i];
}
return typedResult;
}
internal static object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Debug.Assert(ctor != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeConstructorInfo
return GetCustomAttributes(ctor.GetRuntimeModule(), ctor.MetadataToken, 0, caType);
}
internal static object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType)
{
Debug.Assert(property != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimePropertyInfo
return GetCustomAttributes(property.GetRuntimeModule(), property.MetadataToken, 0, caType);
}
internal static object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType)
{
Debug.Assert(e != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeEventInfo
return GetCustomAttributes(e.GetRuntimeModule(), e.MetadataToken, 0, caType);
}
internal static object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType)
{
Debug.Assert(field != null);
Debug.Assert(caType != null);
PseudoCustomAttribute.GetCustomAttributes(field, caType, out RuntimeType.ListBuilder<Attribute> pcas);
object[] attributes = GetCustomAttributes(field.GetRuntimeModule(), field.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
internal static object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType)
{
Debug.Assert(parameter != null);
Debug.Assert(caType != null);
PseudoCustomAttribute.GetCustomAttributes(parameter, caType, out RuntimeType.ListBuilder<Attribute> pcas);
object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule()!, parameter.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
internal static object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
{
Debug.Assert(assembly != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeAssembly
int assemblyToken = RuntimeAssembly.GetToken(assembly.GetNativeHandle());
return GetCustomAttributes((assembly.ManifestModule as RuntimeModule)!, assemblyToken, 0, caType);
}
internal static object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType)
{
Debug.Assert(module != null);
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeModule
return GetCustomAttributes(module, module.MetadataToken, 0, caType);
}
internal static bool IsAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, int attributeCtorToken)
{
return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, null, attributeCtorToken, false);
}
private static bool IsCustomAttributeDefined(
RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType)
{
return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false);
}
private static bool IsCustomAttributeDefined(
RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
{
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
if (attributeFilterType != null)
{
Debug.Assert(attributeCtorToken == 0);
MetadataImport scope = decoratedModule.MetadataImport;
RuntimeType.ListBuilder<object> derivedAttributes = default;
for (int i = 0; i < car.Length; i++)
{
if (FilterCustomAttributeRecord(car[i].tkCtor, in scope,
decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, ref derivedAttributes,
out _, out _, out _))
return true;
}
}
else
{
Debug.Assert(attributeFilterType == null);
Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
for (int i = 0; i < car.Length; i++)
{
if (car[i].tkCtor == attributeCtorToken)
return true;
}
}
return false;
}
private static object[] GetCustomAttributes(
RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType? attributeFilterType)
{
RuntimeType.ListBuilder<object> attributes = default;
AddCustomAttributes(ref attributes, decoratedModule, decoratedMetadataToken, attributeFilterType, false, default);
bool useObjectArray = attributeFilterType == null || attributeFilterType.IsValueType || attributeFilterType.ContainsGenericParameters;
RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : attributeFilterType!;
object[] result = CreateAttributeArrayHelper(arrayType, attributes.Count + pcaCount);
for (int i = 0; i < attributes.Count; i++)
{
result[i] = attributes[i];
}
return result;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2065:UnrecognizedReflectionPattern",
Justification = "Linker guarantees presence of all the constructor parameters, property setters and fiels which are accessed by any " +
"attribute instantiation which is present in the code linker has analyzed." +
"As such the reflection usage in this method should never fail as those methods/fields should always be present.")]
private static void AddCustomAttributes(
ref RuntimeType.ListBuilder<object> attributes,
RuntimeModule decoratedModule, int decoratedMetadataToken,
RuntimeType? attributeFilterType, bool mustBeInheritable,
// The derivedAttributes list must be passed by value so that it is not modified with the discovered attributes
RuntimeType.ListBuilder<object> derivedAttributes)
{
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
if (attributeFilterType is null && car.Length == 0)
{
return;
}
MetadataImport scope = decoratedModule.MetadataImport;
for (int i = 0; i < car.Length; i++)
{
ref CustomAttributeRecord caRecord = ref car[i];
IntPtr blobStart = caRecord.blob.Signature;
IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);
if (!FilterCustomAttributeRecord(caRecord.tkCtor, in scope,
decoratedModule, decoratedMetadataToken, attributeFilterType!, mustBeInheritable,
ref derivedAttributes,
out RuntimeType attributeType, out IRuntimeMethodInfo? ctorWithParameters, out bool isVarArg))
{
continue;
}
// Leverage RuntimeConstructorInfo standard .ctor verification
RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, isVarArg);
// Create custom attribute object
int cNamedArgs;
object attribute;
if (ctorWithParameters != null)
{
attribute = CreateCaObject(decoratedModule, attributeType, ctorWithParameters, ref blobStart, blobEnd, out cNamedArgs);
}
else
{
attribute = attributeType.CreateInstanceDefaultCtor(publicOnly: false, skipCheckThis: true, fillCache: true, wrapExceptions: false)!;
// It is allowed by the ECMA spec to have an empty signature blob
int blobLen = (int)((byte*)blobEnd - (byte*)blobStart);
if (blobLen == 0)
{
cNamedArgs = 0;
}
else
{
// Metadata is always written in little-endian format. Must account for this on
// big-endian platforms.
#if BIGENDIAN
const int CustomAttributeVersion = 0x0100;
#else
const int CustomAttributeVersion = 0x0001;
#endif
if (Marshal.ReadInt16(blobStart) != CustomAttributeVersion)
{
throw new CustomAttributeFormatException();
}
blobStart = (IntPtr)((byte*)blobStart + 2); // skip version prefix
cNamedArgs = Marshal.ReadInt16(blobStart);
blobStart = (IntPtr)((byte*)blobStart + 2); // skip namedArgs count
#if BIGENDIAN
cNamedArgs = ((cNamedArgs & 0xff00) >> 8) | ((cNamedArgs & 0x00ff) << 8);
#endif
}
}
for (int j = 0; j < cNamedArgs; j++)
{
GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value);
try
{
if (isProperty)
{
if (type is null && value != null)
{
type = (RuntimeType)value.GetType();
if (type == Type_RuntimeType)
{
type = Type_Type;
}
}
PropertyInfo? property = type is null ?
attributeType.GetProperty(name) :
attributeType.GetProperty(name, type, Type.EmptyTypes);
// Did we get a valid property reference?
if (property == null)
{
throw new CustomAttributeFormatException(
SR.Format(SR.RFLCT_InvalidPropFail, name));
}
MethodInfo setMethod = property.GetSetMethod(true)!;
// Public properties may have non-public setter methods
if (!setMethod.IsPublic)
{
continue;
}
setMethod.Invoke(attribute, BindingFlags.Default, null, new object?[] { value }, null);
}
else
{
FieldInfo field = attributeType.GetField(name)!;
field.SetValue(attribute, value, BindingFlags.Default, Type.DefaultBinder, null);
}
}
catch (Exception e)
{
throw new CustomAttributeFormatException(
SR.Format(isProperty ? SR.RFLCT_InvalidPropFail : SR.RFLCT_InvalidFieldFail, name), e);
}
}
if (blobStart != blobEnd)
{
throw new CustomAttributeFormatException();
}
attributes.Add(attribute);
}
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Module.ResolveMethod and Module.ResolveType are marked as RequiresUnreferencedCode because they rely on tokens" +
"which are not guaranteed to be stable across trimming. So if somebody harcodes a token it could break." +
"The usage here is not like that as all these tokes come from existing metadata loaded from some IL" +
"and so trimming has no effect (the tokens are read AFTER trimming occured).")]
private static bool FilterCustomAttributeRecord(
MetadataToken caCtorToken,
in MetadataImport scope,
RuntimeModule decoratedModule,
MetadataToken decoratedToken,
RuntimeType attributeFilterType,
bool mustBeInheritable,
ref RuntimeType.ListBuilder<object> derivedAttributes,
out RuntimeType attributeType,
out IRuntimeMethodInfo? ctorWithParameters,
out bool isVarArg)
{
ctorWithParameters = null;
isVarArg = false;
// Resolve attribute type from ctor parent token found in decorated decoratedModule scope
attributeType = (decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null) as RuntimeType)!;
// Test attribute type against user provided attribute type filter
if (!attributeFilterType.IsAssignableFrom(attributeType))
return false;
// Ensure if attribute type must be inheritable that it is inheritable
// Ensure that to consider a duplicate attribute type AllowMultiple is true
if (!AttributeUsageCheck(attributeType, mustBeInheritable, ref derivedAttributes))
return false;
// Windows Runtime attributes aren't real types - they exist to be read as metadata only, and as such
// should be filtered out of the GetCustomAttributes path.
if ((attributeType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
{
return false;
}
// Resolve the attribute ctor
ConstArray ctorSig = scope.GetMethodSignature(caCtorToken);
isVarArg = (ctorSig[0] & 0x05) != 0;
bool ctorHasParameters = ctorSig[1] != 0;
if (ctorHasParameters)
{
// Resolve method ctor token found in decorated decoratedModule scope
// See https://github.com/dotnet/runtime/issues/11637 for why we fast-path non-generics here (fewer allocations)
if (attributeType.IsGenericType)
{
ctorWithParameters = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo();
}
else
{
ctorWithParameters = ModuleHandle.ResolveMethodHandleInternal(decoratedModule.GetNativeHandle(), caCtorToken);
}
}
// Visibility checks
MetadataToken tkParent = default;
if (decoratedToken.IsParamDef)
{
tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
tkParent = new MetadataToken(scope.GetParentToken(tkParent));
}
else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef)
{
tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
}
else if (decoratedToken.IsTypeDef)
{
tkParent = decoratedToken;
}
else if (decoratedToken.IsGenericPar)
{
tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
// decoratedToken is a generic parameter on a method. Get the declaring Type of the method.
if (tkParent.IsMethodDef)
tkParent = new MetadataToken(scope.GetParentToken(tkParent));
}
else
{
// We need to relax this when we add support for other types of decorated tokens.
Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
"The decoratedToken must be either an assembly, a module, a type, or a member.");
}
// If the attribute is on a type, member, or parameter we check access against the (declaring) type,
// otherwise we check access against the module.
RuntimeTypeHandle parentTypeHandle = tkParent.IsTypeDef ?
decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent) :
default;
RuntimeTypeHandle attributeTypeHandle = attributeType.TypeHandle;
bool result = RuntimeMethodHandle.IsCAVisibleFromDecoratedType(new QCallTypeHandle(ref attributeTypeHandle),
ctorWithParameters != null ? ctorWithParameters.Value : RuntimeMethodHandleInternal.EmptyHandle,
new QCallTypeHandle(ref parentTypeHandle),
new QCallModule(ref decoratedModule)) != Interop.BOOL.FALSE;
GC.KeepAlive(ctorWithParameters);
return result;
}
#endregion
#region Private Static Methods
private static bool AttributeUsageCheck(
RuntimeType attributeType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes)
{
AttributeUsageAttribute? attributeUsageAttribute = null;
if (mustBeInheritable)
{
attributeUsageAttribute = GetAttributeUsage(attributeType);
if (!attributeUsageAttribute.Inherited)
return false;
}
// Legacy: AllowMultiple ignored for none inheritable attributes
if (derivedAttributes.Count == 0)
return true;
for (int i = 0; i < derivedAttributes.Count; i++)
{
if (derivedAttributes[i].GetType() == attributeType)
{
attributeUsageAttribute ??= GetAttributeUsage(attributeType);
return attributeUsageAttribute.AllowMultiple;
}
}
return true;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokens" +
"which are not guaranteed to be stable across trimming. So if somebody harcodes a token it could break." +
"The usage here is not like that as all these tokes come from existing metadata loaded from some IL" +
"and so trimming has no effect (the tokens are read AFTER trimming occured).")]
internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute)
{
RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule();
MetadataImport scope = decoratedModule.MetadataImport;
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedAttribute.MetadataToken);
AttributeUsageAttribute? attributeUsageAttribute = null;
for (int i = 0; i < car.Length; i++)
{
ref CustomAttributeRecord caRecord = ref car[i];
RuntimeType? attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;
if (attributeType != (RuntimeType)typeof(AttributeUsageAttribute))
continue;
if (attributeUsageAttribute != null)
throw new FormatException(SR.Format(SR.Format_AttributeUsage, attributeType));
ParseAttributeUsageAttribute(caRecord.blob, out AttributeTargets targets, out bool inherited, out bool allowMultiple);
attributeUsageAttribute = new AttributeUsageAttribute(targets, allowMultiple, inherited);
}
return attributeUsageAttribute ?? AttributeUsageAttribute.Default;
}
#endregion
#region Private Static FCalls
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _ParseAttributeUsageAttribute(
IntPtr pCa, int cCa, out int targets, out bool inherited, out bool allowMultiple);
private static void ParseAttributeUsageAttribute(
ConstArray ca, out AttributeTargets targets, out bool inherited, out bool allowMultiple)
{
_ParseAttributeUsageAttribute(ca.Signature, ca.Length, out int _targets, out inherited, out allowMultiple);
targets = (AttributeTargets)_targets;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern object _CreateCaObject(RuntimeModule pModule, RuntimeType type, IRuntimeMethodInfo pCtor, byte** ppBlob, byte* pEndBlob, int* pcNamedArgs);
private static object CreateCaObject(RuntimeModule module, RuntimeType type, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs)
{
byte* pBlob = (byte*)blob;
byte* pBlobEnd = (byte*)blobEnd;
int cNamedArgs;
object ca = _CreateCaObject(module, type, ctor, &pBlob, pBlobEnd, &cNamedArgs);
blob = (IntPtr)pBlob;
namedArgs = cNamedArgs;
return ca;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _GetPropertyOrFieldData(
RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value);
private static void GetPropertyOrFieldData(
RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value)
{
byte* pBlobStart = (byte*)blobStart;
_GetPropertyOrFieldData(
module.GetNativeHandle(), &pBlobStart, (byte*)blobEnd, out name, out isProperty, out type, out value);
blobStart = (IntPtr)pBlobStart;
}
private static object[] CreateAttributeArrayHelper(RuntimeType elementType, int elementCount)
{
// If we have 0 elements, don't allocate a new array
if (elementCount == 0)
{
return elementType.GetEmptyArray();
}
return (object[])Array.CreateInstance(elementType, elementCount);
}
#endregion
}
internal static class PseudoCustomAttribute
{
#region Private Static Data Members
// Here we can avoid the need to take a lock when using Dictionary by rearranging
// the only method that adds values to the Dictionary. For more details on
// Dictionary versus Hashtable thread safety:
// See code:Dictionary#DictionaryVersusHashtableThreadSafety
private static readonly Dictionary<RuntimeType, RuntimeType> s_pca = CreatePseudoCustomAttributeDictionary();
#endregion
#region Static Constructor
private static Dictionary<RuntimeType, RuntimeType> CreatePseudoCustomAttributeDictionary()
{
Type[] pcas = new Type[]
{
// See https://github.com/dotnet/coreclr/blob/master/src/md/compiler/custattr_emit.cpp
typeof(FieldOffsetAttribute), // field
typeof(SerializableAttribute), // class, struct, enum, delegate
typeof(MarshalAsAttribute), // parameter, field, return-value
typeof(ComImportAttribute), // class, interface
typeof(NonSerializedAttribute), // field, inherited
typeof(InAttribute), // parameter
typeof(OutAttribute), // parameter
typeof(OptionalAttribute), // parameter
typeof(DllImportAttribute), // method
typeof(PreserveSigAttribute), // method
typeof(TypeForwardedToAttribute), // assembly
};
Dictionary<RuntimeType, RuntimeType> dict = new Dictionary<RuntimeType, RuntimeType>(pcas.Length);
foreach (RuntimeType runtimeType in pcas)
{
VerifyPseudoCustomAttribute(runtimeType);
dict[runtimeType] = runtimeType;
}
return dict;
}
[Conditional("DEBUG")]
private static void VerifyPseudoCustomAttribute(RuntimeType pca)
{
// If any of these are invariants are no longer true will have to
// re-architect the PCA product logic and test cases -- you've been warned!
Debug.Assert(pca.BaseType == typeof(Attribute), "Pseudo CA Error");
AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
Debug.Assert(!usage.Inherited, "Pseudo CA Error");
// AllowMultiple is true for TypeForwardedToAttribute
// Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
}
#endregion
#region Internal Static
internal static void GetCustomAttributes(RuntimeType type, RuntimeType caType, out RuntimeType.ListBuilder<Attribute> pcas)
{
Debug.Assert(type != null);
Debug.Assert(caType != null);
pcas = default;
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType))
return;
if (all || caType == typeof(SerializableAttribute))
{
if ((type.Attributes & TypeAttributes.Serializable) != 0)
pcas.Add(new SerializableAttribute());
}
if (all || caType == typeof(ComImportAttribute))
{
if ((type.Attributes & TypeAttributes.Import) != 0)
pcas.Add(new ComImportAttribute());
}
}
internal static bool IsDefined(RuntimeType type, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(SerializableAttribute))
{
if ((type.Attributes & TypeAttributes.Serializable) != 0)
return true;
}
if (all || caType == typeof(ComImportAttribute))
{
if ((type.Attributes & TypeAttributes.Import) != 0)
return true;
}
return false;
}
internal static void GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, out RuntimeType.ListBuilder<Attribute> pcas)
{
Debug.Assert(method != null);
Debug.Assert(caType != null);
pcas = default;
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType))
return;
if (all || caType == typeof(DllImportAttribute))
{
Attribute? pca = GetDllImportCustomAttribute(method);
if (pca != null) pcas.Add(pca);
}
if (all || caType == typeof(PreserveSigAttribute))
{
if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0)
pcas.Add(new PreserveSigAttribute());
}
}
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(DllImportAttribute))
{
if ((method.Attributes & MethodAttributes.PinvokeImpl) != 0)
return true;
}
if (all || caType == typeof(PreserveSigAttribute))
{
if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0)
return true;
}
return false;
}
internal static void GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out RuntimeType.ListBuilder<Attribute> pcas)
{
Debug.Assert(parameter != null);
Debug.Assert(caType != null);
pcas = default;
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType))
return;
if (all || caType == typeof(InAttribute))
{
if (parameter.IsIn)
pcas.Add(new InAttribute());
}
if (all || caType == typeof(OutAttribute))
{
if (parameter.IsOut)
pcas.Add(new OutAttribute());
}
if (all || caType == typeof(OptionalAttribute))
{
if (parameter.IsOptional)
pcas.Add(new OptionalAttribute());
}
if (all || caType == typeof(MarshalAsAttribute))
{
Attribute? pca = GetMarshalAsCustomAttribute(parameter);
if (pca != null) pcas.Add(pca);
}
}
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(InAttribute))
{
if (parameter.IsIn) return true;
}
if (all || caType == typeof(OutAttribute))
{
if (parameter.IsOut) return true;
}
if (all || caType == typeof(OptionalAttribute))
{
if (parameter.IsOptional) return true;
}
if (all || caType == typeof(MarshalAsAttribute))
{
if (GetMarshalAsCustomAttribute(parameter) != null) return true;
}
return false;
}
internal static void GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, out RuntimeType.ListBuilder<Attribute> pcas)
{
Debug.Assert(field != null);
Debug.Assert(caType != null);
pcas = default;
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType))
return;
Attribute? pca;
if (all || caType == typeof(MarshalAsAttribute))
{
pca = GetMarshalAsCustomAttribute(field);
if (pca != null) pcas.Add(pca);
}
if (all || caType == typeof(FieldOffsetAttribute))
{
pca = GetFieldOffsetCustomAttribute(field);
if (pca != null) pcas.Add(pca);
}
if (all || caType == typeof(NonSerializedAttribute))
{
if ((field.Attributes & FieldAttributes.NotSerialized) != 0)
pcas.Add(new NonSerializedAttribute());
}
}
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(MarshalAsAttribute))
{
if (GetMarshalAsCustomAttribute(field) != null) return true;
}
if (all || caType == typeof(FieldOffsetAttribute))
{
if (GetFieldOffsetCustomAttribute(field) != null) return true;
}
if (all || caType == typeof(NonSerializedAttribute))
{
if ((field.Attributes & FieldAttributes.NotSerialized) != 0)
return true;
}
return false;
}
#endregion
private static DllImportAttribute? GetDllImportCustomAttribute(RuntimeMethodInfo method)
{
if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
return null;
MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule());
int token = method.MetadataToken;
scope.GetPInvokeMap(token, out PInvokeAttributes flags, out string entryPoint, out string dllName);
CharSet charSet = CharSet.None;
switch (flags & PInvokeAttributes.CharSetMask)
{
case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break;
case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break;
case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break;
case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break;
// Invalid: default to CharSet.None
default: break;
}
CallingConvention callingConvention = CallingConvention.Cdecl;
switch (flags & PInvokeAttributes.CallConvMask)
{
case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break;
case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break;
case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break;
case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break;
case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break;
// Invalid: default to CallingConvention.Cdecl
default: break;
}
DllImportAttribute attribute = new DllImportAttribute(dllName);
attribute.EntryPoint = entryPoint;
attribute.CharSet = charSet;
attribute.SetLastError = (flags & PInvokeAttributes.SupportsLastError) != 0;
attribute.ExactSpelling = (flags & PInvokeAttributes.NoMangle) != 0;
attribute.PreserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0;
attribute.CallingConvention = callingConvention;
attribute.BestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled;
attribute.ThrowOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled;
return attribute;
}
private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter)
{
return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()!);
}
private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeFieldInfo field)
{
return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule());
}
private static MarshalAsAttribute? GetMarshalAsCustomAttribute(int token, RuntimeModule scope)
{
ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token);
if (nativeType.Length == 0)
return null;
MetadataImport.GetMarshalAs(nativeType,
out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedTypeName, out UnmanagedType arraySubType, out int sizeParamIndex,
out int sizeConst, out string? marshalTypeName, out string? marshalCookie, out int iidParamIndex);
RuntimeType? safeArrayUserDefinedType = string.IsNullOrEmpty(safeArrayUserDefinedTypeName) ? null :
RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope);
RuntimeType? marshalTypeRef = null;
try
{
marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope);
}
catch (TypeLoadException)
{
// The user may have supplied a bad type name string causing this TypeLoadException
// Regardless, we return the bad type name
Debug.Assert(marshalTypeName != null);
}
MarshalAsAttribute attribute = new MarshalAsAttribute(unmanagedType);
attribute.SafeArraySubType = safeArraySubType;
attribute.SafeArrayUserDefinedSubType = safeArrayUserDefinedType;
attribute.IidParameterIndex = iidParamIndex;
attribute.ArraySubType = arraySubType;
attribute.SizeParamIndex = (short)sizeParamIndex;
attribute.SizeConst = sizeConst;
attribute.MarshalType = marshalTypeName;
attribute.MarshalTypeRef = marshalTypeRef;
attribute.MarshalCookie = marshalCookie;
return attribute;
}
private static FieldOffsetAttribute? GetFieldOffsetCustomAttribute(RuntimeFieldInfo field)
{
if (field.DeclaringType != null &&
field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out int fieldOffset))
return new FieldOffsetAttribute(fieldOffset);
return null;
}
internal static StructLayoutAttribute? GetStructLayoutCustomAttribute(RuntimeType type)
{
if (type.IsInterface || type.HasElementType || type.IsGenericParameter)
return null;
LayoutKind layoutKind = LayoutKind.Auto;
switch (type.Attributes & TypeAttributes.LayoutMask)
{
case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break;
case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break;
case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break;
default: Debug.Fail("Unreachable code"); break;
}
CharSet charSet = CharSet.None;
switch (type.Attributes & TypeAttributes.StringFormatMask)
{
case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break;
case TypeAttributes.AutoClass: charSet = CharSet.Auto; break;
case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break;
default: Debug.Fail("Unreachable code"); break;
}
type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out int pack, out int size);
// Metadata parameter checking should not have allowed 0 for packing size.
// The runtime later converts a packing size of 0 to 8 so do the same here
// because it's more useful from a user perspective.
if (pack == 0)
pack = 8; // DEFAULT_PACKING_SIZE
StructLayoutAttribute attribute = new StructLayoutAttribute(layoutKind);
attribute.Pack = pack;
attribute.Size = size;
attribute.CharSet = charSet;
return attribute;
}
}
}
| 43.879625 | 176 | 0.607399 | [
"MIT"
] | BrianH12345/runtime | src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs | 84,205 | C# |
using CmsShoppingCart.Models.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CmsShoppingCart.Models.ViewModels.Pages
{
public class SidebarVM
{
public SidebarVM()
{
}
public SidebarVM(SidebarDTO row)
{
Id = row.Id;
Body = row.Body;
}
public int Id { get; set; }
[AllowHtml]
public string Body { get; set; }
}
} | 19.115385 | 49 | 0.583501 | [
"MIT"
] | ritchie200/cmsmvcwebsite | CmsShoppingCart/Models/ViewModels/Pages/SidebarVM.cs | 499 | 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.Diagnostics;
using System.Threading;
namespace System.Net
{
internal enum SocketPerfCounterName
{
SocketConnectionsEstablished = 0, // these enum values are used as index
SocketBytesReceived,
SocketBytesSent,
SocketDatagramsReceived,
SocketDatagramsSent,
}
internal sealed class SocketPerfCounter
{
private static SocketPerfCounter s_instance;
public static SocketPerfCounter Instance => LazyInitializer.EnsureInitialized(ref s_instance);
public bool Enabled => false; // TODO (#7833): Implement socket perf counters.
[Conditional("TODO7833")]
public void Increment(SocketPerfCounterName perfCounter, long amount = 1)
{
// TODO (#7833): Implement socket perf counters.
}
}
}
| 30.264706 | 102 | 0.693878 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Net.Sockets/src/System/Net/SocketPerfCounters.cs | 1,029 | C# |
namespace DistributedShop.Products.Dto
{
using DistributedShop.Common.Mediator.Contracts;
using System;
public class UpdateProductInputModel : ICommand
{
public UpdateProductInputModel(Guid id, string name, string description, string vendor, decimal price, int quantity)
{
this.Id = id;
this.Name = name;
this.Description = description;
this.Vendor = vendor;
this.Price = price;
this.Quantity = quantity;
}
public Guid Id { get; }
public string Name { get; }
public string Description { get; }
public string Vendor { get; }
public decimal Price { get; }
public int Quantity { get; }
}
}
| 24.483871 | 124 | 0.587615 | [
"MIT"
] | stoyanov7/DistributedShop | src/DistributedShop.Products/Dto/UpdateProductInputModel.cs | 761 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the eventbridge-2015-10-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.EventBridge.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.EventBridge.Model.Internal.MarshallTransformations
{
/// <summary>
/// SqsParameters Marshaller
/// </summary>
public class SqsParametersMarshaller : IRequestMarshaller<SqsParameters, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(SqsParameters requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetMessageGroupId())
{
context.Writer.WritePropertyName("MessageGroupId");
context.Writer.Write(requestObject.MessageGroupId);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static SqsParametersMarshaller Instance = new SqsParametersMarshaller();
}
} | 32.935484 | 109 | 0.69001 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/EventBridge/Generated/Model/Internal/MarshallTransformations/SqsParametersMarshaller.cs | 2,042 | C# |
/*
Copyright (c) 2017, Kevin Pope, John Lewin
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.Diagnostics;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.ActionBar;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.SlicerConfiguration;
namespace MatterHackers.MatterControl.PrinterControls
{
public class TemperatureControls : FlowLayoutWidget
{
private PrinterConfig printer;
private TextButton preHeatButton;
private TextButton offButton;
private TemperatureControls(PrinterConfig printer, ThemeConfig theme)
: base(FlowDirection.TopToBottom)
{
this.HAnchor = HAnchor.Stretch;
this.HAnchor = HAnchor.Stretch;
this.printer = printer;
int hotendCount = printer.Settings.Helpers.NumberOfHotends();
// add in the hotend controls
for (int extruderIndex = 0; extruderIndex < hotendCount; extruderIndex++)
{
var settingsRow = new SettingsRow(
hotendCount == 1 ? "Hotend".Localize() : "Hotend {0}".Localize().FormatWith(extruderIndex + 1),
null,
theme);
settingsRow.AddChild(new TemperatureWidgetHotend(printer, extruderIndex, theme, hotendCount));
this.AddChild(settingsRow);
}
if (printer.Settings.GetValue<bool>(SettingsKey.has_heated_bed))
{
var settingsRow = new SettingsRow(
"Bed".Localize(),
null,
theme);
settingsRow.AddChild(new TemperatureWidgetBed(printer, theme));
this.AddChild(settingsRow);
}
// add in the all heaters section
var heatersRow = new SettingsRow(
"All Heaters".Localize(),
null,
theme);
this.AddChild(heatersRow);
var container = new FlowLayoutWidget();
heatersRow.AddChild(container);
preHeatButton = new TextButton("Preheat".Localize(), theme)
{
BackgroundColor = theme.MinimalShade,
Margin = new BorderDouble(right: 10)
};
container.AddChild(preHeatButton);
preHeatButton.Click += (s, e) =>
{
// turn on the bed
printer.Connection.TargetBedTemperature = printer.Settings.GetValue<double>(SettingsKey.bed_temperature);
for (int extruderIndex = 0; extruderIndex < hotendCount; extruderIndex++)
{
printer.Connection.SetTargetHotendTemperature(extruderIndex, printer.Settings.Helpers.ExtruderTargetTemperature(extruderIndex));
}
printer.Connection.TurnOffBedAndExtruders(PrinterCommunication.TurnOff.AfterDelay);
};
offButton = new TextButton("Off".Localize(), theme)
{
BackgroundColor = theme.MinimalShade,
};
container.AddChild(offButton);
offButton.Click += (s, e) =>
{
printer.Connection.TurnOffBedAndExtruders(PrinterCommunication.TurnOff.Now);
};
// Register listeners
printer.Connection.CommunicationStateChanged += Printer_StatusChanged;
printer.Connection.EnableChanged += Printer_StatusChanged;
SetVisibleControls();
}
public static SectionWidget CreateSection(PrinterConfig printer, ThemeConfig theme)
{
return new SectionWidget("Temperature".Localize(), new TemperatureControls(printer, theme), theme);
}
public override void OnClosed(EventArgs e)
{
// Unregister listeners
printer.Connection.CommunicationStateChanged -= Printer_StatusChanged;
printer.Connection.EnableChanged -= Printer_StatusChanged;
base.OnClosed(e);
}
private void Printer_StatusChanged(object sender, EventArgs e)
{
SetVisibleControls();
UiThread.RunOnIdle(this.Invalidate);
}
private void SetVisibleControls()
{
if (!printer.Settings.PrinterSelected)
{
offButton?.SetEnabled(false);
preHeatButton?.SetEnabled(false);
}
else // we at least have a printer selected
{
switch (printer.Connection.CommunicationState)
{
case CommunicationStates.FinishedPrint:
case CommunicationStates.Connected:
offButton?.SetEnabled(true);
preHeatButton?.SetEnabled(true);
break;
default:
offButton?.SetEnabled(false);
preHeatButton?.SetEnabled(false);
break;
}
}
}
}
} | 32.817647 | 133 | 0.751748 | [
"BSD-2-Clause"
] | mrtwizta/MatterControl | MatterControlLib/PrinterControls/ControlWidgets/TemperatureControls.cs | 5,581 | C# |
namespace FiveOhFirstDataCore.Data.Services
{
public interface IRefreshRequestService
{
/// <summary>
/// An <see cref="Action"/> that is called when a refresh is requested.
/// </summary>
public event Action RefreshRequested;
/// <summary>
/// Trigger the <see cref="IRefreshRequestService.RefreshRequested"/> <see cref="Action"/>.
/// </summary>
public void CallRequestRefresh();
}
}
| 30.866667 | 99 | 0.613391 | [
"MIT"
] | 501stLegionA3/FiveOhFirstDataCore | FiveOhFirstDataCore.Core/Services/IRefreshRequestService.cs | 465 | C# |
using Bonsai;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
// TODO: replace this with the source output type.
using TSource = System.String;
namespace $rootnamespace$
{
public class $safeitemname$ : Source<TSource>
{
public override IObservable<TSource> Generate()
{
// TODO: generate the observable sequence.
throw new NotImplementedException();
}
}
}
| 23 | 56 | 0.648221 | [
"MIT"
] | medengineer/Bonsai_3.0 | Bonsai.Templates/Bonsai.SourceTemplate/SourceTemplate.cs | 508 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace TBACS.BlazorGridCustomStyle.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FilesController : ControllerBase
{
private readonly IWebHostEnvironment WebHostEnvironment;
public FilesController(IWebHostEnvironment webHostEnvironment)
{
WebHostEnvironment = webHostEnvironment;
}
[HttpGet]
[Produces("application/json")]
public IActionResult Get()
{
DirectoryInfo d = new(Path.Combine(WebHostEnvironment.ContentRootPath, "Reports"));
FileInfo[] Files = d.GetFiles("*.trdp");
string[] FileNames = new string[Files.Length + 1];
FileNames[0] = "Please Select a Report.";
for (int i = 0; i < Files.Length; i++)
{
FileNames[i + 1] = Files[i].Name;
}
if (FileNames.Length > 0)
{
return Ok(FileNames);
}
else
{
return BadRequest();
}
}
}
}
| 25.509804 | 95 | 0.581091 | [
"MIT"
] | edrohler/blogging-source | theming-across-products/Post03/src/TBACS.BlazorGridCustomStyle/Server/Controllers/FilesController.cs | 1,303 | C# |
// Project: Aguafrommars/TheIdServer
// Copyright (c) 2022 @Olivier Lefebvre
using Aguacongas.IdentityServer.KeysRotation;
#if DUENDE
using Duende.IdentityServer.Stores;
using static Duende.IdentityServer.IdentityServerConstants;
#else
using IdentityServer4.Stores;
using static IdentityServer4.IdentityServerConstants;
#endif
using Microsoft.AspNetCore.DataProtection.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// <see cref="IServiceCollection"/> extensions
/// </summary>
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddECDsaAddValidationKeysStore(this IServiceCollection services, ECDsaSigningAlgorithm signingAlgorithm)
{
return services.AddValidattionKeysStore<ECDsaEncryptorConfiguration, ECDsaEncryptor>(signingAlgorithm.ToString());
}
public static IServiceCollection AddRsaAddValidationKeysStore(this IServiceCollection services, RsaSigningAlgorithm signingAlgorithm)
{
return services.AddValidattionKeysStore<RsaEncryptorConfiguration, RsaEncryptor>(signingAlgorithm.ToString());
}
/// <summary>
/// Adds the keys rotation.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configureKeysRotation">Action to configure keys rotation.</param>
/// <returns></returns>
public static IKeyRotationBuilder AddKeysRotation(this IServiceCollection services, RsaSigningAlgorithm rsaSigningAlgorithm = RsaSigningAlgorithm.RS256, Action<KeyRotationOptions> configureKeysRotation = null)
{
services.AddDataProtection();
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IConfigureOptions<KeyRotationOptions>, KeyRotationOptionsSetup>());
return new KeyRotationBuilder
{
Services = services
.AddKeysRotation<RsaEncryptorConfiguration, RsaEncryptor>(rsaSigningAlgorithm.ToString(), configureKeysRotation)
}.AddRsaEncryptorConfiguration(rsaSigningAlgorithm, options =>
{
options.SigningAlgorithm = rsaSigningAlgorithm.ToString();
options.IsDefaultSigningAlgorithm = true;
});
}
public static IServiceCollection AddKeysRotation<TC,TE>(this IServiceCollection services, string signingAlgorithm, Action<KeyRotationOptions> configureKeysRotation = null)
where TC : SigningAlgorithmConfiguration, new()
where TE : ISigningAlgortithmEncryptor
{
return services
.Configure<KeyRotationOptions>(signingAlgorithm, options =>
{
var configuration = new TC();
configuration.SigningAlgorithm = signingAlgorithm;
options.AuthenticatedEncryptorConfiguration = configuration;
configureKeysRotation?.Invoke(options);
})
.AddSingleton<ICacheableKeyRingProvider<TC, TE>>(p =>
{
var optionsFactory = p.GetRequiredService<IOptionsFactory<KeyRotationOptions>>();
var configueOptionsList = p.GetRequiredService<IEnumerable<IConfigureOptions<KeyRotationOptions>>>();
var settings = optionsFactory.Create(signingAlgorithm);
foreach(var configure in configueOptionsList)
{
configure.Configure(settings);
}
var options = Options.Options.Create(settings);
var keyManager = new AspNetCore.DataProtection.KeyManagement.XmlKeyManager(options, p.GetRequiredService<IActivator>());
var resolver = new DefaultKeyResolver(options, p.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance);
return new KeyRingProvider<TC, TE>(keyManager, options, resolver);
})
.AddTransient<ICacheableKeyRingProvider>(p =>
{
var providerList = p.GetRequiredService<IEnumerable<ICacheableKeyRingProvider<TC, TE>>>();
return providerList.First(p => p.Algorithm == signingAlgorithm);
})
.AddTransient<IKeyRingStore<TC, TE>>(p =>
{
var providerList = p.GetRequiredService<IEnumerable<ICacheableKeyRingProvider<TC, TE>>>();
return providerList.First(p => p.Algorithm == signingAlgorithm).GetCurrentKeyRing() as KeyRing<TC, TE>;
})
.AddTransient(p =>
{
var list = p.GetRequiredService<IEnumerable<IKeyRingStore<TC, TE>>>();
return list.First(s => s.Algorithm == signingAlgorithm) as IValidationKeysStore;
})
.AddTransient(p => {
var list = p.GetRequiredService<IEnumerable<IKeyRingStore<TC, TE>>>();
return list.First(s => s.Algorithm == signingAlgorithm) as ISigningCredentialStore;
});
}
static IServiceCollection AddValidattionKeysStore<TC, TE>(this IServiceCollection services, string signingAlgorithm)
where TC : SigningAlgorithmConfiguration, new()
where TE : ISigningAlgortithmEncryptor
{
return services.AddTransient<IValidationKeysStore>(p =>
{
var providerList = p.GetRequiredService<IEnumerable<ICacheableKeyRingProvider<TC, TE>>>();
return new ValidattionKeysStore(providerList.First(rp => rp.Algorithm == signingAlgorithm));
});
}
}
}
| 49.859504 | 217 | 0.646445 | [
"Apache-2.0"
] | LibertyEngineeringMovement/TheIdServer | src/IdentityServer/Shared/Aguacongas.IdentityServer.KeysRotation.Shared/Extensions/ServiceCollectionExtensions.cs | 6,035 | C# |
using UnityEngine;
using UnityEngine.Events;
namespace MyFrameworkPure
{
public class UnityEventFloat : UnityEvent<float>
{
}
public class GestureTool : CSingletonMono<GestureTool>
{
public float HThreshold { get; set; }//水平阈值
public float VThreshold { get; set; }//垂直阈值
public UnityEvent<float> onHorizontalMove = new UnityEventFloat();
public UnityEvent<float> onVerticalMove = new UnityEventFloat();
public float mouseSpeed = 20;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!Input.GetMouseButton(0))
return;
float deltaX = Input.GetAxis("Mouse X") * mouseSpeed;
float deltaY = Input.GetAxis("Mouse Y") * mouseSpeed;
if (Input.touchCount > 0)
{
deltaX = Input.touches[0].deltaPosition.x;
deltaY = Input.touches[0].deltaPosition.y;
}
Vector2 mousePos = Input.mousePosition;
if (mousePos.x <= 0)
{
deltaX = -mouseSpeed * 0.5f;
}
else if (mousePos.x >= Screen.width)
{
deltaX = mouseSpeed * 0.5f;
}
if (mousePos.y <= 0)
{
deltaY = -mouseSpeed * 0.5f;
}
else if (mousePos.y >= Screen.height)
{
deltaY = mouseSpeed * 0.5f;
}
if (Mathf.Abs(deltaX) > HThreshold)
{
onHorizontalMove?.Invoke(deltaX);
}
if (Mathf.Abs(deltaY) > VThreshold)
{
onVerticalMove?.Invoke(deltaY);
}
}
}
}
| 25.178082 | 74 | 0.494015 | [
"MIT"
] | lihaiyang-xx/MyFrameworkPure | Tool/GestureTool.cs | 1,856 | C# |
using Alex.Blocks.Materials;
namespace Alex.Blocks.Minecraft.Slabs
{
public class StoneBrickSlab : Slab
{
public StoneBrickSlab() : base()
{
BlockMaterial = Material.Stone.Clone().WithHardness(1.5f);
//Hardness = 1.5f;
}
}
} | 18.461538 | 61 | 0.695833 | [
"MPL-2.0"
] | ConcreteMC/Alex | src/Alex/Blocks/Minecraft/Slabs/StoneBrickSlab.cs | 240 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NuGet.VisualStudio.Internal.Contracts;
using Xunit;
namespace NuGet.PackageManagement.UI.Test
{
public class ProjectUtilityTests
{
[Fact]
public async Task GetSortedProjectIdsAsync_WhenProjectsIsNull_Throws()
{
ArgumentNullException exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => ProjectUtility.GetSortedProjectIdsAsync(projects: null, CancellationToken.None).AsTask());
Assert.Equal("projects", exception.ParamName);
}
[Fact]
public async Task GetSortedProjectIdsAsync_WhenCancellationTokenIsCancelled_Throws()
{
await Assert.ThrowsAsync<OperationCanceledException>(
() => ProjectUtility.GetSortedProjectIdsAsync(
Enumerable.Empty<IProjectContextInfo>(),
new CancellationToken(canceled: true)).AsTask());
}
[Fact]
public async Task GetSortedProjectIdsAsync_WhenProjectsUnsorted_ReturnsSortedProjectIds()
{
var projectA = new Mock<IProjectContextInfo>();
var projectB = new Mock<IProjectContextInfo>();
var projectC = new Mock<IProjectContextInfo>();
var projectAMetadata = new Mock<IProjectMetadataContextInfo>();
var projectBMetadata = new Mock<IProjectMetadataContextInfo>();
var projectCMetadata = new Mock<IProjectMetadataContextInfo>();
projectA.Setup(x => x.GetMetadataAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(projectAMetadata.Object);
projectB.Setup(x => x.GetMetadataAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(projectBMetadata.Object);
projectC.Setup(x => x.GetMetadataAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(projectCMetadata.Object);
projectAMetadata.SetupGet(x => x.UniqueName)
.Returns("a");
projectBMetadata.SetupGet(x => x.UniqueName)
.Returns("b");
projectCMetadata.SetupGet(x => x.UniqueName)
.Returns("c");
// ProjectId values were picked to help detect if the test method incorrectly sorts on project ID.
var expectedResults = new List<string>() { "2", "0", "1" };
projectAMetadata.SetupGet(x => x.ProjectId)
.Returns(expectedResults[0]);
projectBMetadata.SetupGet(x => x.ProjectId)
.Returns(expectedResults[1]);
projectCMetadata.SetupGet(x => x.ProjectId)
.Returns(expectedResults[2]);
IEnumerable<string> actualResults = await ProjectUtility.GetSortedProjectIdsAsync(
new[] { projectB.Object, projectA.Object, projectC.Object },
CancellationToken.None);
Assert.Equal(expectedResults, actualResults.ToArray());
}
}
}
| 41.87013 | 112 | 0.644541 | [
"Apache-2.0"
] | marcin-krystianc/NuGet.Client | test/NuGet.Clients.Tests/NuGet.PackageManagement.UI.Test/Utility/ProjectUtilityTests.cs | 3,224 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Nep;
using Newtonsoft.Json;
public class Example : MonoBehaviour // Change MonoBehaviour name for your class in unity
{
// NEP objects as global
Node node;
Subscriber sub;
// Example of message to send
class Msg
{
public string message { get; set; }
}
// Message as strings to convert to Msg
string msg;
// Start is called before the first frame update
void Start()
{
// Definition of objects
node = new Node("unity_sub");
sub = node.new_sub("test", "json");
}
// Update is called once per frame
void Update()
{
// Non blocking listen
bool isMsg = sub.listenNB(ref msg);
// if isMsg == true, then msg has information, otherwise, there is no message
if (isMsg)
{
// Convert JSON string to Msg
Msg message = JsonConvert.DeserializeObject<Msg>(msg);
Debug.Log(message.message);
}
}
// Called when program is finished
void OnDestroy()
{
// IMPORTANT: Close objects to avoid freezing of Unity
sub.close();
node.close();
Debug.Log("NEP objects closed");
}
} | 23.236364 | 89 | 0.597027 | [
"MIT"
] | enriquecoronadozu/NEP_samples | ZMQ(recommended)/unity/master_local/sub.cs | 1,278 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CExplorationStateSkateSlide : CExplorationStateSkatingDrift
{
[Ordinal(1)] [RED("inputRangeToEnter")] public CFloat InputRangeToEnter { get; set;}
[Ordinal(2)] [RED("height")] public CFloat Height { get; set;}
public CExplorationStateSkateSlide(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CExplorationStateSkateSlide(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 34.814815 | 139 | 0.740426 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CExplorationStateSkateSlide.cs | 940 | C# |
using System.Windows;
using Elmah.Everywhere.Diagnostics;
namespace Wpf_Sample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Make an exception
int i = 0;
int result = 10 / i;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var client = new WcfSample.SampleWcfServiceClient();
client.MakeErrorCompleted += (s, args) =>
{
if(args.Error != null)
{
// Manual error log
ExceptionHandler.Report(args.Error);
MessageBox.Show(args.Error.Message, "Error");
}
};
client.MakeErrorAsync();
}
}
}
| 30.358974 | 98 | 0.388514 | [
"Apache-2.0"
] | vincoss/vinco-logging-toolk | Source/Samples/Wpf_Sample/MainWindow.xaml.cs | 1,186 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.OperationalInsights.Properties;
using System.Globalization;
using System.Management.Automation;
using System.Net;
namespace Microsoft.Azure.Commands.OperationalInsights
{
[Cmdlet(VerbsCommon.Remove, Constants.SavedSearch)]
public class RemoveAzureOperationalInsightsSavedSearchCommand : OperationalInsightsBaseCmdlet
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("Name")]
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The workspace name.")]
[ValidateNotNullOrEmpty]
public string WorkspaceName { get; set; }
[Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The saved search id.")]
[ValidateNotNullOrEmpty]
public string SavedSearchId { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Don't ask for confirmation.")]
public SwitchParameter Force { get; set; }
protected override void ProcessRecord()
{
ConfirmAction(
Force.IsPresent,
string.Format(
CultureInfo.InvariantCulture,
Resources.SavedSearchDeleteConfirmationMessage,
SavedSearchId,
WorkspaceName),
string.Format(
CultureInfo.InvariantCulture,
Resources.SavedSearchRemoving,
SavedSearchId,
WorkspaceName),
SavedSearchId,
ExecuteDelete);
}
public void ExecuteDelete()
{
HttpStatusCode response = OperationalInsightsClient.DeleteSavedSearch(ResourceGroupName, WorkspaceName, SavedSearchId);
if (response == HttpStatusCode.NoContent)
{
WriteWarning(string.Format(CultureInfo.InvariantCulture, Resources.SavedSearchNotFound, SavedSearchId, WorkspaceName));
}
}
}
}
| 42.013699 | 136 | 0.603847 | [
"MIT"
] | hchungmsft/azure-powershell | src/ResourceManager/OperationalInsights/Commands.OperationalInsights/Search/RemoveAzureOperationalInsightsSavedSearchCommand.cs | 2,997 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mahjong.Model
{
[Serializable]
public struct WaitingData
{
public Tile[] HandTiles;
public Tile[] WaitingTiles;
public override string ToString()
{
return $"HandTiles: {string.Join("", HandTiles)}, "
+ $"WaitingTiles: {string.Join("", WaitingTiles)}";
}
}
[Serializable]
public struct PlayerHandData
{
public Tile[] HandTiles;
public OpenMeld[] OpenMelds;
public override string ToString()
{
var hands = HandTiles == null ? "Confidential" : string.Join("", HandTiles);
return $"HandTiles: {hands}, "
+ $"OpenMelds: {string.Join(",", OpenMelds)}";
}
public Meld[] Melds => OpenMelds.Select(openMeld => openMeld.Meld).ToArray();
}
} | 22.028571 | 79 | 0.66537 | [
"MIT"
] | HitomiFlower/NaoMahjong | Assets/Scripts/Mahjong/Model/TransferData.cs | 771 | C# |
namespace mc_pi_csharp_df
{
public class McpiCsharp
{
private struct Fastrand
{
private ulong _rctr;
public void SplitMix64(ulong seed = 0x956126898) => _rctr = seed;
public double Rand()
{
_rctr %= 0xFFFFFFFF;
_rctr ^= _rctr << 13;
_rctr %= 0xFFFFFFFF;
_rctr ^= _rctr >> 7;
_rctr %= 0xFFFFFFFF;
_rctr ^= _rctr << 17;
_rctr %= 0xFFFFFFFF;
return (float)(_rctr % 0xFFFFFFFF) / 0xFFFFFFFF;
}
}
public static double Mcpi(int acc)
{
var rng = new Fastrand();
rng.SplitMix64();
var hitCount = 0;
var count = 0;
for (var i = 0; i < acc; i++)
{
var x = rng.Rand();
var y = rng.Rand();
if (x * x + y * y <= 1.0)
{
hitCount += 1;
}
count += 1;
}
return (float)hitCount / count * 4.0;
}
}
}
| 26.604651 | 77 | 0.386364 | [
"MIT"
] | noname0310/PythonBindingSample | mc_pi_csharp_df/Class1.cs | 1,146 | C# |
namespace OrbitalShell.Lib
{
/// <summary>
/// based on System.Runtime.RuntimeEnvironment
/// </summary>
public enum TargetPlatform
{
FreeBSD,
Linux,
OSX,
Windows,
Any,
Unspecified
}
} | 17.066667 | 50 | 0.53125 | [
"MIT"
] | OrbitalShell/Orbital-Shell | OrbitalShell-ConsoleApp/Lib/TargetPlatform.cs | 256 | 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.Immutable;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class GlyphExtensions
{
// hardcode ImageCatalogGuid locally rather than calling KnownImageIds.ImageCatalogGuid
// So it doesnot have dependency for Microsoft.VisualStudio.ImageCatalog.dll
// https://github.com/dotnet/roslyn/issues/26642
private static readonly Guid ImageCatalogGuid = Guid.Parse("ae27a6b0-e345-4288-96df-5eaf394ee369");
public static ImageId GetImageId(this Glyph glyph)
{
// VS for mac cannot refer to ImageMoniker
// so we need to expose ImageId instead of ImageMoniker here
// and expose ImageMoniker in the EditorFeatures.wpf.dll
switch (glyph)
{
case Glyph.None:
return default;
case Glyph.Assembly:
return new ImageId(ImageCatalogGuid, KnownImageIds.Assembly);
case Glyph.BasicFile:
return new ImageId(ImageCatalogGuid, KnownImageIds.VBFileNode);
case Glyph.BasicProject:
return new ImageId(ImageCatalogGuid, KnownImageIds.VBProjectNode);
case Glyph.ClassPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPublic);
case Glyph.ClassProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.ClassProtected);
case Glyph.ClassPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.ClassPrivate);
case Glyph.ClassInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.ClassInternal);
case Glyph.CSharpFile:
return new ImageId(ImageCatalogGuid, KnownImageIds.CSFileNode);
case Glyph.CSharpProject:
return new ImageId(ImageCatalogGuid, KnownImageIds.CSProjectNode);
case Glyph.ConstantPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPublic);
case Glyph.ConstantProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantProtected);
case Glyph.ConstantPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantPrivate);
case Glyph.ConstantInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.ConstantInternal);
case Glyph.DelegatePublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePublic);
case Glyph.DelegateProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateProtected);
case Glyph.DelegatePrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.DelegatePrivate);
case Glyph.DelegateInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.DelegateInternal);
case Glyph.EnumPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPublic);
case Glyph.EnumProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationProtected);
case Glyph.EnumPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationPrivate);
case Glyph.EnumInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationInternal);
case Glyph.EnumMemberPublic:
case Glyph.EnumMemberProtected:
case Glyph.EnumMemberPrivate:
case Glyph.EnumMemberInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.EnumerationItemPublic);
case Glyph.Error:
return new ImageId(ImageCatalogGuid, KnownImageIds.StatusError);
case Glyph.EventPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.EventPublic);
case Glyph.EventProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.EventProtected);
case Glyph.EventPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.EventPrivate);
case Glyph.EventInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.EventInternal);
// Extension methods have the same glyph regardless of accessibility.
case Glyph.ExtensionMethodPublic:
case Glyph.ExtensionMethodProtected:
case Glyph.ExtensionMethodPrivate:
case Glyph.ExtensionMethodInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.ExtensionMethod);
case Glyph.FieldPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic);
case Glyph.FieldProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.FieldProtected);
case Glyph.FieldPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPrivate);
case Glyph.FieldInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.FieldInternal);
case Glyph.InterfacePublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePublic);
case Glyph.InterfaceProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceProtected);
case Glyph.InterfacePrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.InterfacePrivate);
case Glyph.InterfaceInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.InterfaceInternal);
// TODO: Figure out the right thing to return here.
case Glyph.Intrinsic:
return new ImageId(ImageCatalogGuid, KnownImageIds.Type);
case Glyph.Keyword:
return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseKeyword);
case Glyph.Label:
return new ImageId(ImageCatalogGuid, KnownImageIds.Label);
case Glyph.Parameter:
case Glyph.Local:
return new ImageId(ImageCatalogGuid, KnownImageIds.LocalVariable);
case Glyph.Namespace:
return new ImageId(ImageCatalogGuid, KnownImageIds.Namespace);
case Glyph.MethodPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPublic);
case Glyph.MethodProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.MethodProtected);
case Glyph.MethodPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.MethodPrivate);
case Glyph.MethodInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.MethodInternal);
case Glyph.ModulePublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePublic);
case Glyph.ModuleProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleProtected);
case Glyph.ModulePrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.ModulePrivate);
case Glyph.ModuleInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.ModuleInternal);
case Glyph.OpenFolder:
return new ImageId(ImageCatalogGuid, KnownImageIds.OpenFolder);
case Glyph.Operator:
return new ImageId(ImageCatalogGuid, KnownImageIds.Operator);
case Glyph.PropertyPublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPublic);
case Glyph.PropertyProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyProtected);
case Glyph.PropertyPrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyPrivate);
case Glyph.PropertyInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.PropertyInternal);
case Glyph.RangeVariable:
return new ImageId(ImageCatalogGuid, KnownImageIds.FieldPublic);
case Glyph.Reference:
return new ImageId(ImageCatalogGuid, KnownImageIds.Reference);
//// this is not a copy-paste mistake, we were using these before in the previous GetImageMoniker()
//case Glyph.StructurePublic:
// return KnownMonikers.ValueTypePublic;
//case Glyph.StructureProtected:
// return KnownMonikers.ValueTypeProtected;
//case Glyph.StructurePrivate:
// return KnownMonikers.ValueTypePrivate;
//case Glyph.StructureInternal:
// return KnownMonikers.ValueTypeInternal;
case Glyph.StructurePublic:
return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePublic);
case Glyph.StructureProtected:
return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeProtected);
case Glyph.StructurePrivate:
return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypePrivate);
case Glyph.StructureInternal:
return new ImageId(ImageCatalogGuid, KnownImageIds.ValueTypeInternal);
case Glyph.TypeParameter:
return new ImageId(ImageCatalogGuid, KnownImageIds.Type);
case Glyph.Snippet:
return new ImageId(ImageCatalogGuid, KnownImageIds.Snippet);
case Glyph.CompletionWarning:
return new ImageId(ImageCatalogGuid, KnownImageIds.IntellisenseWarning);
case Glyph.StatusInformation:
return new ImageId(ImageCatalogGuid, KnownImageIds.StatusInformation);
case Glyph.NuGet:
return new ImageId(ImageCatalogGuid, KnownImageIds.NuGet);
default:
throw new ArgumentException(nameof(glyph));
}
}
public static Glyph GetGlyph(this ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
switch (tag)
{
case WellKnownTags.Assembly:
return Glyph.Assembly;
case WellKnownTags.File:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicFile : Glyph.CSharpFile;
case WellKnownTags.Project:
return tags.Contains(LanguageNames.VisualBasic) ? Glyph.BasicProject : Glyph.CSharpProject;
case WellKnownTags.Class:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ClassProtected;
case Accessibility.Private:
return Glyph.ClassPrivate;
case Accessibility.Internal:
return Glyph.ClassInternal;
case Accessibility.Public:
default:
return Glyph.ClassPublic;
}
case WellKnownTags.Constant:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ConstantProtected;
case Accessibility.Private:
return Glyph.ConstantPrivate;
case Accessibility.Internal:
return Glyph.ConstantInternal;
case Accessibility.Public:
default:
return Glyph.ConstantPublic;
}
case WellKnownTags.Delegate:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.DelegateProtected;
case Accessibility.Private:
return Glyph.DelegatePrivate;
case Accessibility.Internal:
return Glyph.DelegateInternal;
case Accessibility.Public:
default:
return Glyph.DelegatePublic;
}
case WellKnownTags.Enum:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumProtected;
case Accessibility.Private:
return Glyph.EnumPrivate;
case Accessibility.Internal:
return Glyph.EnumInternal;
case Accessibility.Public:
default:
return Glyph.EnumPublic;
}
case WellKnownTags.EnumMember:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EnumMemberProtected;
case Accessibility.Private:
return Glyph.EnumMemberPrivate;
case Accessibility.Internal:
return Glyph.EnumMemberInternal;
case Accessibility.Public:
default:
return Glyph.EnumMemberPublic;
}
case WellKnownTags.Error:
return Glyph.Error;
case WellKnownTags.Event:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.EventProtected;
case Accessibility.Private:
return Glyph.EventPrivate;
case Accessibility.Internal:
return Glyph.EventInternal;
case Accessibility.Public:
default:
return Glyph.EventPublic;
}
case WellKnownTags.ExtensionMethod:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ExtensionMethodProtected;
case Accessibility.Private:
return Glyph.ExtensionMethodPrivate;
case Accessibility.Internal:
return Glyph.ExtensionMethodInternal;
case Accessibility.Public:
default:
return Glyph.ExtensionMethodPublic;
}
case WellKnownTags.Field:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.FieldProtected;
case Accessibility.Private:
return Glyph.FieldPrivate;
case Accessibility.Internal:
return Glyph.FieldInternal;
case Accessibility.Public:
default:
return Glyph.FieldPublic;
}
case WellKnownTags.Interface:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.InterfaceProtected;
case Accessibility.Private:
return Glyph.InterfacePrivate;
case Accessibility.Internal:
return Glyph.InterfaceInternal;
case Accessibility.Public:
default:
return Glyph.InterfacePublic;
}
case WellKnownTags.Intrinsic:
return Glyph.Intrinsic;
case WellKnownTags.Keyword:
return Glyph.Keyword;
case WellKnownTags.Label:
return Glyph.Label;
case WellKnownTags.Local:
return Glyph.Local;
case WellKnownTags.Namespace:
return Glyph.Namespace;
case WellKnownTags.Method:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.MethodProtected;
case Accessibility.Private:
return Glyph.MethodPrivate;
case Accessibility.Internal:
return Glyph.MethodInternal;
case Accessibility.Public:
default:
return Glyph.MethodPublic;
}
case WellKnownTags.Module:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.ModulePublic;
case Accessibility.Private:
return Glyph.ModulePrivate;
case Accessibility.Internal:
return Glyph.ModuleInternal;
case Accessibility.Public:
default:
return Glyph.ModulePublic;
}
case WellKnownTags.Folder:
return Glyph.OpenFolder;
case WellKnownTags.Operator:
return Glyph.Operator;
case WellKnownTags.Parameter:
return Glyph.Parameter;
case WellKnownTags.Property:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.PropertyProtected;
case Accessibility.Private:
return Glyph.PropertyPrivate;
case Accessibility.Internal:
return Glyph.PropertyInternal;
case Accessibility.Public:
default:
return Glyph.PropertyPublic;
}
case WellKnownTags.RangeVariable:
return Glyph.RangeVariable;
case WellKnownTags.Reference:
return Glyph.Reference;
case WellKnownTags.NuGet:
return Glyph.NuGet;
case WellKnownTags.Structure:
switch (GetAccessibility(tags))
{
case Accessibility.Protected:
return Glyph.StructureProtected;
case Accessibility.Private:
return Glyph.StructurePrivate;
case Accessibility.Internal:
return Glyph.StructureInternal;
case Accessibility.Public:
default:
return Glyph.StructurePublic;
}
case WellKnownTags.TypeParameter:
return Glyph.TypeParameter;
case WellKnownTags.Snippet:
return Glyph.Snippet;
case WellKnownTags.Warning:
return Glyph.CompletionWarning;
case WellKnownTags.StatusInformation:
return Glyph.StatusInformation;
}
}
return Glyph.None;
}
private static Accessibility GetAccessibility(ImmutableArray<string> tags)
{
if (tags.Contains(WellKnownTags.Public))
{
return Accessibility.Public;
}
else if (tags.Contains(WellKnownTags.Protected))
{
return Accessibility.Protected;
}
else if (tags.Contains(WellKnownTags.Internal))
{
return Accessibility.Internal;
}
else if (tags.Contains(WellKnownTags.Private))
{
return Accessibility.Private;
}
else
{
return Accessibility.NotApplicable;
}
}
}
}
| 46.038776 | 161 | 0.512922 | [
"Apache-2.0"
] | ObsidianMinor/roslyn | src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs | 22,561 | C# |
using RWCustom;
using UnityEngine;
namespace CentiShields
{
sealed class CentiShield : Weapon
{
private static float Rand => Random.value;
new public float rotation;
new public float lastRotation;
public float rotVel;
public float lastDarkness = -1f;
public float darkness;
private Color blackColor;
private Color earthColor;
private readonly float rotationOffset;
public CentiShieldAbstract Abstr { get; }
public CentiShield(CentiShieldAbstract abstr, Vector2 pos, Vector2 vel) : base(abstr, abstr.world)
{
Abstr = abstr;
bodyChunks = new[] { new BodyChunk(this, 0, pos + vel, 4 * (Abstr.scaleX + Abstr.scaleY), 0.35f) { goThroughFloors = true } };
bodyChunks[0].lastPos = bodyChunks[0].pos;
bodyChunks[0].vel = vel;
bodyChunkConnections = new BodyChunkConnection[0];
airFriction = 0.999f;
gravity = 0.9f;
bounce = 0.6f;
surfaceFriction = 0.45f;
collisionLayer = 1;
waterFriction = 0.92f;
buoyancy = 0.75f;
rotation = Rand * 360f;
lastRotation = rotation;
rotationOffset = Rand * 30 - 15;
ResetVel(vel.magnitude);
}
public void HitEffect(Vector2 impactVelocity)
{
var num = Random.Range(3, 8);
for (int k = 0; k < num; k++) {
Vector2 pos = firstChunk.pos + Custom.DegToVec(Rand * 360f) * 5f * Rand;
Vector2 vel = -impactVelocity * -0.1f + Custom.DegToVec(Rand * 360f) * Mathf.Lerp(0.2f, 0.4f, Rand) * impactVelocity.magnitude;
room.AddObject(new Spark(pos, vel, new Color(1f, 1f, 1f), null, 10, 170));
}
room.AddObject(new StationaryEffect(firstChunk.pos, new Color(1f, 1f, 1f), null, StationaryEffect.EffectType.FlashingOrb));
}
public void AddDamage(float damage)
{
Abstr.damage += damage * 0.2f;
if (Abstr.damage > 1)
Abstr.damage = 1;
}
private void Shatter()
{
var num = Random.Range(6, 10);
for (int k = 0; k < num; k++) {
Vector2 pos = firstChunk.pos + Custom.RNV() * 5f * Rand;
Vector2 vel = Custom.RNV() * 4f * (1 + Rand);
room.AddObject(new Spark(pos, vel, new Color(1f, 1f, 1f), null, 10, 170));
}
float count = 2 + 4 * (Abstr.scaleX + Abstr.scaleY);
for (int j = 0; j < count; j++) {
Vector2 extraVel = Custom.RNV() * Random.value * (j == 0 ? 3f : 6f);
room.AddObject(new CentipedeShell(firstChunk.pos, Custom.RNV() * Rand * 15 + extraVel, Abstr.hue, Abstr.saturation, 0.25f, 0.25f));
}
room.PlaySound(SoundID.Weapon_Skid, firstChunk.pos, 0.75f, 1.25f);
AllGraspsLetGoOfThisObject(true);
abstractPhysicalObject.LoseAllStuckObjects();
Destroy();
}
public override void Update(bool eu)
{
if (Abstr.damage >= 1 && Random.value < 0.015f) {
Shatter();
return;
}
ChangeCollisionLayer(grabbedBy.Count == 0 ? 2 : 1);
firstChunk.collideWithTerrain = grabbedBy.Count == 0;
firstChunk.collideWithSlopes = grabbedBy.Count == 0;
base.Update(eu);
var chunk = firstChunk;
lastRotation = rotation;
rotation += rotVel * Vector2.Distance(chunk.lastPos, chunk.pos);
rotation %= 360;
if (grabbedBy.Count == 0) {
if (firstChunk.lastPos == firstChunk.pos) {
rotVel *= 0.9f;
} else if (Mathf.Abs(rotVel) <= 0.01f) {
ResetVel((firstChunk.lastPos - firstChunk.pos).magnitude);
}
} else {
var grabberChunk = grabbedBy[0].grabber.mainBodyChunk;
rotVel *= 0.9f;
rotation = Mathf.Lerp(rotation, grabberChunk.Rotation.GetAngle() + rotationOffset, 0.25f);
}
if (!Custom.DistLess(chunk.lastPos, chunk.pos, 3f) && room.GetTile(chunk.pos).Solid && !room.GetTile(chunk.lastPos).Solid) {
var firstSolid = SharedPhysics.RayTraceTilesForTerrainReturnFirstSolid(room, room.GetTilePosition(chunk.lastPos), room.GetTilePosition(chunk.pos));
if (firstSolid != null) {
FloatRect floatRect = Custom.RectCollision(chunk.pos, chunk.lastPos, room.TileRect(firstSolid.Value).Grow(2f));
chunk.pos = floatRect.GetCorner(FloatRect.CornerLabel.D);
bool flag = false;
if (floatRect.GetCorner(FloatRect.CornerLabel.B).x < 0f) {
chunk.vel.x = Mathf.Abs(chunk.vel.x) * 0.15f;
flag = true;
} else if (floatRect.GetCorner(FloatRect.CornerLabel.B).x > 0f) {
chunk.vel.x = -Mathf.Abs(chunk.vel.x) * 0.15f;
flag = true;
} else if (floatRect.GetCorner(FloatRect.CornerLabel.B).y < 0f) {
chunk.vel.y = Mathf.Abs(chunk.vel.y) * 0.15f;
flag = true;
} else if (floatRect.GetCorner(FloatRect.CornerLabel.B).y > 0f) {
chunk.vel.y = -Mathf.Abs(chunk.vel.y) * 0.15f;
flag = true;
}
if (flag) {
rotVel *= 0.8f;
}
}
}
}
public override void HitByWeapon(Weapon weapon)
{
base.HitByWeapon(weapon);
if (grabbedBy.Count > 0) {
Creature grabber = grabbedBy[0].grabber;
Vector2 push = firstChunk.vel * firstChunk.mass / grabber.firstChunk.mass;
grabber.firstChunk.vel += push;
}
firstChunk.vel = Vector2.zero;
HitEffect(weapon.firstChunk.vel);
AddDamage(weapon.HeavyWeapon ? 0.5f : 0.2f);
}
public override void TerrainImpact(int chunk, IntVector2 direction, float speed, bool firstContact)
{
base.TerrainImpact(chunk, direction, speed, firstContact);
if (speed > 10) {
room.PlaySound(SoundID.Spear_Fragment_Bounce, firstChunk.pos, 0.35f, 2f);
ResetVel(speed);
}
}
private void ResetVel(float speed)
{
rotVel = Mathf.Lerp(-1f, 1f, Rand) * Custom.LerpMap(speed, 0f, 18f, 5f, 26f);
}
public override void ChangeMode(Mode newMode)
{ }
public override void InitiateSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam)
{
sLeaser.sprites = new FSprite[2];
sLeaser.sprites[0] = new FSprite("CentipedeBackShell", true);
sLeaser.sprites[1] = new FSprite("CentipedeBackShell", true);
AddToContainer(sLeaser, rCam, null);
}
public override void DrawSprites(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, float timeStacker, Vector2 camPos)
{
Vector2 pos = Vector2.Lerp(firstChunk.lastPos, firstChunk.pos, timeStacker);
float num = Mathf.InverseLerp(305f, 380f, timeStacker);
pos.y -= 20f * Mathf.Pow(num, 3f);
float num2 = Mathf.Pow(1f - num, 0.25f);
lastDarkness = darkness;
darkness = rCam.room.Darkness(pos);
darkness *= 1f - 0.5f * rCam.room.LightSourceExposure(pos);
for (int i = 0; i < 2; i++) {
sLeaser.sprites[i].x = pos.x - camPos.x;
sLeaser.sprites[i].y = pos.y - camPos.y;
sLeaser.sprites[i].rotation = Mathf.Lerp(lastRotation, rotation, timeStacker);
sLeaser.sprites[i].scaleY = num2 * Abstr.scaleY;
sLeaser.sprites[i].scaleX = num2 * Abstr.scaleX;
}
sLeaser.sprites[0].color = blackColor;
sLeaser.sprites[0].scaleY *= 1.175f - Abstr.damage * 0.2f;
sLeaser.sprites[0].scaleX *= 1.175f - Abstr.damage * 0.2f;
sLeaser.sprites[1].color = Color.Lerp(Custom.HSL2RGB(Abstr.hue, Abstr.saturation, 0.55f), blackColor, darkness);
if (blink > 0 && Rand < 0.5f) {
sLeaser.sprites[0].color = blinkColor;
} else if (num > 0.3f) {
for (int j = 0; j < 2; j++) {
sLeaser.sprites[j].color = Color.Lerp(sLeaser.sprites[j].color, earthColor, Mathf.Pow(Mathf.InverseLerp(0.3f, 1f, num), 1.6f));
}
}
if (slatedForDeletetion || room != rCam.room) {
sLeaser.CleanSpritesAndRemove();
}
}
public override void ApplyPalette(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, RoomPalette palette)
{
blackColor = palette.blackColor;
earthColor = Color.Lerp(palette.fogColor, palette.blackColor, 0.5f);
}
public override void AddToContainer(RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, FContainer? newContainer)
{
newContainer ??= rCam.ReturnFContainer("Items");
foreach (FSprite fsprite in sLeaser.sprites) {
fsprite.RemoveFromContainer();
newContainer.AddChild(fsprite);
}
}
}
} | 39.191837 | 163 | 0.5402 | [
"CC0-1.0"
] | Dual-Iron/fisob-api | examples/centipede-shields/CentiShield.cs | 9,604 | C# |
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyWebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders(); // Forwarded Headers Middleware can run after diagnostics and error handling, but it must be be run before calling UseHsts.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/", async context =>
{
context.Response.ContentType = "text/plain";
// Host info
var name = Dns.GetHostName(); // get container id
var ip = Dns.GetHostEntry(name).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine($"Host Name: { Environment.MachineName} \t {name}\t {ip}");
await context.Response.WriteAsync($"Host Name: {Environment.MachineName}{Environment.NewLine}");
await context.Response.WriteAsync(Environment.NewLine);
// Request method, scheme, and path
await context.Response.WriteAsync($"Request Method: {context.Request.Method}{Environment.NewLine}");
await context.Response.WriteAsync($"Request Scheme: {context.Request.Scheme}{Environment.NewLine}");
await context.Response.WriteAsync($"Request URL: {context.Request.GetDisplayUrl()}{Environment.NewLine}");
await context.Response.WriteAsync($"Request Path: {context.Request.Path}{Environment.NewLine}");
// Headers
await context.Response.WriteAsync($"Request Headers:{Environment.NewLine}");
foreach (var (key, value) in context.Request.Headers)
{
await context.Response.WriteAsync($"\t {key}: {value}{Environment.NewLine}");
}
await context.Response.WriteAsync(Environment.NewLine);
// Connection: RemoteIp
await context.Response.WriteAsync($"Request Remote IP: {context.Connection.RemoteIpAddress}");
});
});
}
}
}
| 42.686747 | 162 | 0.613322 | [
"MIT"
] | burhanwani/dotnetlabs | ASPNetCoreLabs/NginxLoadBalancer/src/MyWebApi/Startup.cs | 3,543 | C# |
using BEDF.Domain.Entity;
namespace BEDF.Domain.Interfaces
{
public interface ITransactionRepository : IGenericRepository<Transaction>
{
}
}
| 17.222222 | 77 | 0.748387 | [
"MIT"
] | RMiike/MaratonaDiscovery | Back-End-Dev-Finance/src/domain/BEDF.Domain/Interfaces/ITransactionRepository.cs | 157 | C# |
using System;
using System.Collections.Generic;
using ZKWeb.Localize;
using ZKWeb.Plugins.Common.Base.src.UIComponents.ListItems.Interfaces;
using ZKWebStandard.Extensions;
namespace ZKWeb.Plugins.Common.Base.src.UIComponents.ListItems {
/// <summary>
/// 根据枚举值提供选项列表
/// </summary>
/// <typeparam name="TEnum">枚举类型</typeparam>
public class ListItemFromEnum<TEnum> : IListItemProvider where TEnum : struct {
/// <summary>
/// 获取选项列表
/// </summary>
/// <returns></returns>
public IEnumerable<ListItem> GetItems() {
foreach (Enum value in Enum.GetValues(typeof(TEnum))) {
yield return new ListItem(new T(value.GetDescription()), ((int)(object)value).ToString());
}
}
}
}
| 30.083333 | 95 | 0.691136 | [
"MIT"
] | 303248153/ZKWeb.Plugins | src/ZKWeb.Plugins/Common.Base/src/UIComponents/ListItems/ListItemFromEnum.cs | 766 | C# |
using System.Threading.Tasks;
using AElf.OS.Network.Application;
using AElf.OS.Network.Events;
using AElf.OS.Network.Grpc;
using AElf.OS.Network.Helpers;
using AElf.OS.Network.Infrastructure;
using AElf.OS.Network.Protocol.Types;
using AElf.Types;
using Grpc.Core;
using Shouldly;
using Volo.Abp.EventBus.Local;
using Xunit;
namespace AElf.OS.Network
{
public class GrpcNetworkServerBootNodesTests : GrpcNetworkWithBootNodesTestBase
{
private readonly IAElfNetworkServer _networkServer;
private readonly ILocalEventBus _eventBus;
public GrpcNetworkServerBootNodesTests()
{
_networkServer = GetRequiredService<IAElfNetworkServer>();
_eventBus = GetRequiredService<ILocalEventBus>();
}
[Fact]
public async Task Calling_DisposedPeer_ThrowsUnrecoverableNEtException()
{
await _networkServer.StartAsync();
Channel channel = new Channel("localhost", 2001, ChannelCredentials.Insecure);
PeerService.PeerServiceClient peerClient = new PeerService.PeerServiceClient(channel);
GrpcClient grpcClient = new GrpcClient(channel, peerClient);
AElfPeerEndpointHelper.TryParse("127.0.0.1:2001", out var endpoint);
GrpcPeer peer = new GrpcPeer(grpcClient, endpoint, new PeerConnectionInfo
{
SessionId = new byte[] { 1,2,3 }
});
await peer.DisconnectAsync(false);
var exHealthCheck = await Assert.ThrowsAsync<NetworkException>(async () => await peer.PingAsync());
exHealthCheck.ExceptionType.ShouldBe(NetworkExceptionType.Unrecoverable);
var exGetBlocks = await Assert.ThrowsAsync<NetworkException>(
async () => await peer.GetBlocksAsync(HashHelper.ComputeFromString("blockHash"), 10));
exGetBlocks.ExceptionType.ShouldBe(NetworkExceptionType.Unrecoverable);
var exGetBlock = await Assert.ThrowsAsync<NetworkException>(
async () => await peer.GetBlockByHashAsync(HashHelper.ComputeFromString("blockHash")));
exGetBlock.ExceptionType.ShouldBe(NetworkExceptionType.Unrecoverable);
var exGetNodes = await Assert.ThrowsAsync<NetworkException>(
async () => await peer.GetNodesAsync());
exGetNodes.ExceptionType.ShouldBe(NetworkExceptionType.Unrecoverable);
await _networkServer.StopAsync();
}
[Fact]
public async Task StartServer_Test()
{
NetworkInitializedEvent received = null;
_eventBus.Subscribe<NetworkInitializedEvent>(a =>
{
received = a;
return Task.CompletedTask;
});
await _networkServer.StartAsync();
received.ShouldNotBeNull();
await _networkServer.StopAsync();
}
}
} | 36.939024 | 111 | 0.637174 | [
"MIT"
] | ezaruba/AElf | test/AElf.OS.Network.Grpc.Tests/GrpcNetworkServerBootNodesTests.cs | 3,029 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Famoser.MassPass.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Famoser.MassPass.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c770b6c7-525a-4a85-9806-931604c274c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.277778 | 84 | 0.74238 | [
"MIT"
] | famoser/MassPass | Famoser.MassPass.Tests/Properties/AssemblyInfo.cs | 1,381 | C# |
using System;
namespace DefiningClasses
{
public class Person
{
private string name;
private int age;
public Person()
{
this.name = "No name";
this.age = 1;
}
public Person(int number) : this()
{
this.age = number;
}
public Person (string name, int age)
{
this.name = name;
this.age = age;
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
} | 17.425 | 44 | 0.401722 | [
"MIT"
] | rumenand/HomeWork_Tasks | CSharp Advanced/06. Exercises Defining Classes/Problem 2. Creating Constructors/Person.cs | 699 | C# |
namespace oadr2b_ven.UserControls.OptSchedule
{
partial class ucOptStateButton
{
/// <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.lblState = new System.Windows.Forms.Label();
this.pnlborder = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.lblHour = new System.Windows.Forms.Label();
this.pnlborder.SuspendLayout();
this.SuspendLayout();
//
// lblState
//
this.lblState.BackColor = System.Drawing.Color.Transparent;
this.lblState.Cursor = System.Windows.Forms.Cursors.Hand;
this.lblState.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblState.Location = new System.Drawing.Point(0, 0);
this.lblState.Name = "lblState";
this.lblState.Size = new System.Drawing.Size(72, 23);
this.lblState.TabIndex = 2;
this.lblState.Text = "none";
this.lblState.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// pnlborder
//
this.pnlborder.BackColor = System.Drawing.Color.Transparent;
this.pnlborder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pnlborder.Controls.Add(this.lblState);
this.pnlborder.Dock = System.Windows.Forms.DockStyle.Right;
this.pnlborder.ForeColor = System.Drawing.Color.Black;
this.pnlborder.Location = new System.Drawing.Point(30, 0);
this.pnlborder.Name = "pnlborder";
this.pnlborder.Size = new System.Drawing.Size(74, 25);
this.pnlborder.TabIndex = 3;
//
// label1
//
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.label1.Dock = System.Windows.Forms.DockStyle.Top;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(30, 2);
this.label1.TabIndex = 4;
//
// lblHour
//
this.lblHour.AutoSize = true;
this.lblHour.Dock = System.Windows.Forms.DockStyle.Right;
this.lblHour.Location = new System.Drawing.Point(-3, 2);
this.lblHour.Name = "lblHour";
this.lblHour.Size = new System.Drawing.Size(33, 13);
this.lblHour.TabIndex = 5;
this.lblHour.Text = "12am";
//
// ucOptStateButton
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lblHour);
this.Controls.Add(this.label1);
this.Controls.Add(this.pnlborder);
this.Name = "ucOptStateButton";
this.Size = new System.Drawing.Size(104, 25);
this.pnlborder.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblState;
private System.Windows.Forms.Panel pnlborder;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblHour;
}
}
| 39.847619 | 107 | 0.575526 | [
"BSD-3-Clause"
] | epri-dev/OpenADR-Virtual-End-Node | oadr2b-ven/UserControls/OptSchedule/ucOptStateButton.Designer.cs | 4,186 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Xml.Schema;
using System.Xml.Xsl.Runtime;
namespace System.Xml
{
/// <summary>
/// Caches sequence of XmlEvents so that they can be replayed later.
/// </summary>
internal sealed class XmlEventCache : XmlRawWriter
{
private List<XmlEvent[]>? _pages; // All event pages
private XmlEvent[]? _pageCurr; // Page that is currently being built
private int _pageSize; // Number of events in pageCurr
private readonly bool _hasRootNode; // True if the cached document has a root node, false if it's a fragment
private StringConcat _singleText; // If document consists of a single text node, cache it here rather than creating pages
private readonly string _baseUri; // Base Uri of document
private enum XmlEventType
{
Unknown = 0,
DocType,
StartElem,
StartAttr,
EndAttr,
CData,
Comment,
PI,
Whitespace,
String,
Raw,
EntRef,
CharEnt,
SurrCharEnt,
Base64,
BinHex,
XmlDecl1,
XmlDecl2,
StartContent,
EndElem,
FullEndElem,
Nmsp,
EndBase64,
Close,
Flush,
Dispose,
}
#if DEBUG
private const int InitialPageSize = 4;
#else
private const int InitialPageSize = 32;
#endif
public XmlEventCache(string baseUri, bool hasRootNode)
{
_baseUri = baseUri;
_hasRootNode = hasRootNode;
}
public void EndEvents()
{
if (_singleText.Count == 0)
AddEvent(XmlEventType.Unknown);
}
//-----------------------------------------------
// XmlEventCache methods
//-----------------------------------------------
/// <summary>
/// Return Base Uri of the document.
/// </summary>
public string BaseUri
{
get { return _baseUri; }
}
/// <summary>
/// Return true if the cached document has a root node, false if it's a fragment.
/// </summary>
public bool HasRootNode
{
get { return _hasRootNode; }
}
/// <summary>
/// Replay all cached events to an XmlWriter.
/// </summary>
public void EventsToWriter(XmlWriter writer)
{
XmlEvent[] page;
int idxPage, idxEvent;
byte[] bytes;
char[] chars;
XmlRawWriter? rawWriter;
// Special-case single text node at the top-level
if (_singleText.Count != 0)
{
writer.WriteString(_singleText.GetResult());
return;
}
rawWriter = writer as XmlRawWriter;
// Loop over set of pages
for (idxPage = 0; idxPage < _pages!.Count; idxPage++)
{
page = _pages[idxPage];
// Loop over events in each page
for (idxEvent = 0; idxEvent < page.Length; idxEvent++)
{
switch (page[idxEvent].EventType)
{
case XmlEventType.Unknown:
// No more events
Debug.Assert(idxPage + 1 == _pages.Count);
return;
case XmlEventType.DocType:
writer.WriteDocType(page[idxEvent].String1!, page[idxEvent].String2, page[idxEvent].String3, (string?)page[idxEvent].Object);
break;
case XmlEventType.StartElem:
writer.WriteStartElement(page[idxEvent].String1, page[idxEvent].String2!, page[idxEvent].String3);
break;
case XmlEventType.StartAttr:
writer.WriteStartAttribute(page[idxEvent].String1, page[idxEvent].String2!, page[idxEvent].String3);
break;
case XmlEventType.EndAttr:
writer.WriteEndAttribute();
break;
case XmlEventType.CData:
writer.WriteCData(page[idxEvent].String1);
break;
case XmlEventType.Comment:
writer.WriteComment(page[idxEvent].String1);
break;
case XmlEventType.PI:
writer.WriteProcessingInstruction(page[idxEvent].String1!, page[idxEvent].String2);
break;
case XmlEventType.Whitespace:
writer.WriteWhitespace(page[idxEvent].String1);
break;
case XmlEventType.String:
writer.WriteString(page[idxEvent].String1);
break;
case XmlEventType.Raw:
writer.WriteRaw(page[idxEvent].String1!);
break;
case XmlEventType.EntRef:
writer.WriteEntityRef(page[idxEvent].String1!);
break;
case XmlEventType.CharEnt:
writer.WriteCharEntity((char)page[idxEvent].Object!);
break;
case XmlEventType.SurrCharEnt:
chars = (char[])page[idxEvent].Object!;
writer.WriteSurrogateCharEntity(chars[0], chars[1]);
break;
case XmlEventType.Base64:
bytes = (byte[])page[idxEvent].Object!;
writer.WriteBase64(bytes, 0, bytes.Length);
break;
case XmlEventType.BinHex:
bytes = (byte[])page[idxEvent].Object!;
writer.WriteBinHex(bytes, 0, bytes.Length);
break;
case XmlEventType.XmlDecl1:
if (rawWriter != null)
rawWriter.WriteXmlDeclaration((XmlStandalone)page[idxEvent].Object!);
break;
case XmlEventType.XmlDecl2:
if (rawWriter != null)
rawWriter.WriteXmlDeclaration(page[idxEvent].String1!);
break;
case XmlEventType.StartContent:
if (rawWriter != null)
rawWriter.StartElementContent();
break;
case XmlEventType.EndElem:
if (rawWriter != null)
rawWriter.WriteEndElement(page[idxEvent].String1!, page[idxEvent].String2!, page[idxEvent].String3!);
else
writer.WriteEndElement();
break;
case XmlEventType.FullEndElem:
if (rawWriter != null)
rawWriter.WriteFullEndElement(page[idxEvent].String1!, page[idxEvent].String2!, page[idxEvent].String3!);
else
writer.WriteFullEndElement();
break;
case XmlEventType.Nmsp:
if (rawWriter != null)
rawWriter.WriteNamespaceDeclaration(page[idxEvent].String1!, page[idxEvent].String2!);
else
writer.WriteAttributeString("xmlns", page[idxEvent].String1!, XmlReservedNs.NsXmlNs, page[idxEvent].String2);
break;
case XmlEventType.EndBase64:
if (rawWriter != null)
rawWriter.WriteEndBase64();
break;
case XmlEventType.Close:
writer.Close();
break;
case XmlEventType.Flush:
writer.Flush();
break;
case XmlEventType.Dispose:
((IDisposable)writer).Dispose();
break;
default:
Debug.Fail("Unknown event: " + page[idxEvent].EventType);
break;
}
}
}
Debug.Fail("Unknown event should be added to end of event sequence.");
}
/// <summary>
/// Concatenate all element text and atomic value events and return the resulting string.
/// </summary>
public string EventsToString()
{
StringBuilder bldr;
XmlEvent[] page;
int idxPage, idxEvent;
bool inAttr;
// Special-case single text node at the top-level
if (_singleText.Count != 0)
return _singleText.GetResult();
bldr = new StringBuilder();
// Loop over set of pages
inAttr = false;
for (idxPage = 0; idxPage < _pages!.Count; idxPage++)
{
page = _pages[idxPage];
// Loop over events in each page
for (idxEvent = 0; idxEvent < page.Length; idxEvent++)
{
switch (page[idxEvent].EventType)
{
case XmlEventType.Unknown:
// No more events
Debug.Assert(idxPage + 1 == _pages.Count);
return bldr.ToString();
case XmlEventType.String:
case XmlEventType.Whitespace:
case XmlEventType.Raw:
case XmlEventType.CData:
// Append text
if (!inAttr)
bldr.Append(page[idxEvent].String1);
break;
case XmlEventType.StartAttr:
// Don't append text or atomic values if they appear within attributes
inAttr = true;
break;
case XmlEventType.EndAttr:
// No longer in an attribute
inAttr = false;
break;
}
}
}
Debug.Fail("Unknown event should be added to end of event sequence.");
return string.Empty;
}
//-----------------------------------------------
// XmlWriter interface
//-----------------------------------------------
public override XmlWriterSettings? Settings
{
get { return null; }
}
public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
{
AddEvent(XmlEventType.DocType, name, pubid, sysid, subset);
}
public override void WriteStartElement(string? prefix, string localName, string? ns)
{
AddEvent(XmlEventType.StartElem, prefix, localName, ns);
}
public override void WriteStartAttribute(string? prefix, string localName, string? ns)
{
AddEvent(XmlEventType.StartAttr, prefix, localName, ns);
}
public override void WriteEndAttribute()
{
AddEvent(XmlEventType.EndAttr);
}
public override void WriteCData(string? text)
{
AddEvent(XmlEventType.CData, text);
}
public override void WriteComment(string? text)
{
AddEvent(XmlEventType.Comment, text);
}
public override void WriteProcessingInstruction(string name, string? text)
{
AddEvent(XmlEventType.PI, name, text);
}
public override void WriteWhitespace(string? ws)
{
AddEvent(XmlEventType.Whitespace, ws);
}
public override void WriteString(string? text)
{
// Special-case single text node at the top level
if (_pages == null)
{
_singleText.ConcatNoDelimiter(text);
}
else
{
AddEvent(XmlEventType.String, text);
}
}
public override void WriteChars(char[] buffer, int index, int count)
{
WriteString(new string(buffer, index, count));
}
public override void WriteRaw(char[] buffer, int index, int count)
{
WriteRaw(new string(buffer, index, count));
}
public override void WriteRaw(string data)
{
AddEvent(XmlEventType.Raw, data);
}
public override void WriteEntityRef(string name)
{
AddEvent(XmlEventType.EntRef, name);
}
public override void WriteCharEntity(char ch)
{
AddEvent(XmlEventType.CharEnt, (object)ch);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
// Save high and low characters
char[] chars = { lowChar, highChar };
AddEvent(XmlEventType.SurrCharEnt, (object)chars);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
AddEvent(XmlEventType.Base64, (object)ToBytes(buffer, index, count));
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
AddEvent(XmlEventType.BinHex, (object)ToBytes(buffer, index, count));
}
public override void Close()
{
AddEvent(XmlEventType.Close);
}
public override void Flush()
{
AddEvent(XmlEventType.Flush);
}
/// <summary>
/// All other WriteValue methods are implemented by XmlWriter to delegate to WriteValue(object) or WriteValue(string), so
/// only these two methods need to be implemented.
/// </summary>
public override void WriteValue(object value)
{
WriteString(XmlUntypedConverter.Untyped.ToString(value, this._resolver));
}
public override void WriteValue(string? value)
{
WriteString(value);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
AddEvent(XmlEventType.Dispose);
}
}
finally
{
base.Dispose(disposing);
}
}
//-----------------------------------------------
// XmlRawWriter interface
//-----------------------------------------------
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
AddEvent(XmlEventType.XmlDecl1, (object)standalone);
}
internal override void WriteXmlDeclaration(string xmldecl)
{
AddEvent(XmlEventType.XmlDecl2, xmldecl);
}
internal override void StartElementContent()
{
AddEvent(XmlEventType.StartContent);
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
AddEvent(XmlEventType.EndElem, prefix, localName, ns);
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
AddEvent(XmlEventType.FullEndElem, prefix, localName, ns);
}
internal override void WriteNamespaceDeclaration(string prefix, string ns)
{
AddEvent(XmlEventType.Nmsp, prefix, ns);
}
internal override void WriteEndBase64()
{
AddEvent(XmlEventType.EndBase64);
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
private void AddEvent(XmlEventType eventType)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType);
}
private void AddEvent(XmlEventType eventType, string? s1)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType, s1);
}
private void AddEvent(XmlEventType eventType, string? s1, string? s2)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType, s1, s2);
}
private void AddEvent(XmlEventType eventType, string? s1, string? s2, string? s3)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType, s1, s2, s3);
}
private void AddEvent(XmlEventType eventType, string? s1, string? s2, string? s3, object? o)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType, s1, s2, s3, o);
}
private void AddEvent(XmlEventType eventType, object? o)
{
int idx = NewEvent();
_pageCurr![idx].InitEvent(eventType, o);
}
private int NewEvent()
{
if (_pages == null)
{
_pages = new List<XmlEvent[]>();
_pageCurr = new XmlEvent[InitialPageSize];
_pages.Add(_pageCurr);
if (_singleText.Count != 0)
{
// Review: There is no need to concatenate the strings here
_pageCurr[0].InitEvent(XmlEventType.String, _singleText.GetResult());
_pageSize++;
_singleText.Clear();
}
}
else if (_pageSize >= _pageCurr!.Length)
{
// Create new page
_pageCurr = new XmlEvent[_pageSize * 2];
_pages.Add(_pageCurr);
_pageSize = 0;
}
return _pageSize++;
}
/// <summary>
/// Create a standalone buffer that doesn't need an index or count passed along with it.
/// </summary>
private static byte[] ToBytes(byte[] buffer, int index, int count)
{
if (index != 0 || count != buffer.Length)
{
if (buffer.Length - index > count)
count = buffer.Length - index;
byte[] bufferNew = new byte[count];
Array.Copy(buffer, index, bufferNew, 0, count);
return bufferNew;
}
return buffer;
}
/// <summary>
/// Caches information for XML events like BeginElement, String, and EndAttribute so that they can be replayed later.
/// </summary>
private struct XmlEvent
{
private XmlEventType _eventType;
private string? _s1;
private string? _s2;
private string? _s3;
private object? _o;
public void InitEvent(XmlEventType eventType)
{
_eventType = eventType;
}
public void InitEvent(XmlEventType eventType, string? s1)
{
_eventType = eventType;
_s1 = s1;
}
public void InitEvent(XmlEventType eventType, string? s1, string? s2)
{
_eventType = eventType;
_s1 = s1;
_s2 = s2;
}
public void InitEvent(XmlEventType eventType, string? s1, string? s2, string? s3)
{
_eventType = eventType;
_s1 = s1;
_s2 = s2;
_s3 = s3;
}
public void InitEvent(XmlEventType eventType, string? s1, string? s2, string? s3, object? o)
{
_eventType = eventType;
_s1 = s1;
_s2 = s2;
_s3 = s3;
_o = o;
}
public void InitEvent(XmlEventType eventType, object? o)
{
_eventType = eventType;
_o = o;
}
public XmlEventType EventType
{
get { return _eventType; }
}
public string? String1
{
get { return _s1; }
}
public string? String2
{
get { return _s2; }
}
public string? String3
{
get { return _s3; }
}
public object? Object
{
get { return _o; }
}
}
}
}
| 32.656627 | 153 | 0.468087 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs | 21,684 | C# |
using AerovelenceMod;
using Terraria.ModLoader;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Terraria;
using System.Collections.Generic;
using System.Linq;
using System;
using static Terraria.ModLoader.ModContent;
using System.Reflection;
namespace AerovelenceMod.Core.Prim
{
class LegPrimTrail : PrimTrail
{
public LegPrimTrail(Projectile projectile) : base(projectile)
{
_projectile = projectile;
}
public override void SetDefaults()
{
_points.Add(_projectile.Center);
_cap = 80;
_alphaValue = 0.7f;
_width = 8;
_color = Color.White;
}
public override void PrimStructure(SpriteBatch spriteBatch)
{
/*if (_noOfPoints <= 1) return; //for easier, but less customizable, drawing
float colorSin = (float)Math.Sin(_counter / 3f);
Color c1 = Color.Lerp(Color.White, Color.Cyan, colorSin);
float widthVar = (float)Math.Sqrt(_points.Count) * _width;
DrawBasicTrail(c1, widthVar);*/
if (_noOfPoints <= 6) return;
if (_destroyed) return;
float widthVar;
for (int i = 0; i < _points.Count; i++)
{
if (i == 0)
{
widthVar = _width;
Color c1 = Color.White;
Vector2 normalAhead = CurveNormal(_points, i + 1);
Vector2 secondUp = _points[i + 1] - normalAhead * widthVar;
Vector2 secondDown = _points[i + 1] + normalAhead * widthVar;
AddVertex(_points[i], c1 * _alphaValue, new Vector2(0, 0.5f));
AddVertex(secondUp, c1 * _alphaValue, new Vector2(1 / (float)_points.Count, 0));
AddVertex(secondDown, c1 * _alphaValue, new Vector2(1 / (float)_points.Count, 1));
}
else
{
if (i != _points.Count - 1)
{
widthVar = _width;
Color c = Color.Cyan;
Color CBT = Color.Cyan;
Vector2 normal = CurveNormal(_points, i);
Vector2 normalAhead = CurveNormal(_points, i + 1);
float j = (((float)_points.Count) + ((float)(Math.Sin(_counter / 10f)) * 1) - i * 0.1f) / ((float)_points.Count);
widthVar *= j;
Vector2 firstUp = _points[i] - normal * widthVar;
Vector2 firstDown = _points[i] + normal * widthVar;
Vector2 secondUp = _points[i + 1] - normalAhead * widthVar;
Vector2 secondDown = _points[i + 1] + normalAhead * widthVar;
AddVertex(firstDown, c * _alphaValue, new Vector2((i / ((float)_points.Count)), 1));
AddVertex(firstUp, c * _alphaValue, new Vector2((i / ((float)_points.Count)), 0));
AddVertex(secondDown, CBT * _alphaValue, new Vector2((i + 1) / ((float)_points.Count), 1));
AddVertex(secondUp, CBT * _alphaValue, new Vector2((i + 1) / ((float)_points.Count), 0));
AddVertex(secondDown, CBT * _alphaValue, new Vector2((i + 1) / ((float)_points.Count), 1));
AddVertex(firstUp, c * _alphaValue, new Vector2((i / ((float)_points.Count)), 0));
}
else
{
}
}
}
}
public override void SetShaders()
{
PrepareShader(AerovelenceMod.LegElectricity, "MainPS", _noOfPoints, Color.Red);
}
public override void OnUpdate()
{
_counter++;
_noOfPoints = _points.Count() * 6;
if (_cap < _noOfPoints / 6)
{
_points.RemoveAt(0);
}
if ((!_projectile.active && _projectile != null) || _destroyed)
{
OnDestroy();
}
else
{
_points.Add(_projectile.Center);
}
}
public override void OnDestroy()
{
_destroyed = true;
_width *= 0.95f;
if (_width < 0.05f)
{
Dispose();
}
}
}
} | 39.263158 | 137 | 0.488829 | [
"MIT"
] | Arcri/AerovelenceMod | Core/Prim/LegPrimTrail.cs | 4,478 | C# |
/*
* Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using UniJSON;
// Image 37: UniGLTF.dll - Assembly: UniGLTF, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 5565-5923
namespace UniGLTF
{
[Serializable]
public class glTF_KHR_materials_unlit // TypeDefIndex: 5711
{
// Fields
public const string ExtensionName = "KHR_materials_unlit"; // Metadata: 0x003A19C8
public static readonly Utf8String ExtensionNameUtf8; // 0x00
public static readonly byte[] Raw; // 0x10
// Constructors
public glTF_KHR_materials_unlit(); // 0x00000001802650F0-0x0000000180265100
static glTF_KHR_materials_unlit(); // 0x0000000180D61250-0x0000000180D61350
// Methods
public static glTFMaterial CreateDefault(); // 0x0000000180D60B70-0x0000000180D60DE0
public static bool IsEnable(glTFMaterial m); // 0x0000000180D60DE0-0x0000000180D61120
public static glTFExtension Serialize(); // 0x0000000180D61120-0x0000000180D61250
}
}
| 33.65625 | 117 | 0.778087 | [
"MIT"
] | TotalJTM/PrimitierModdingFramework | Dumps/PrimitierDumpV1.0.1/UniGLTF/glTF_KHR_materials_unlit.cs | 1,079 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 組件的一般資訊是由下列的屬性集
// 控制。變更這些屬性值可修改與組件關聯的
// 資訊。
[assembly: AssemblyTitle("webAp2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("webAp2")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 將 ComVisible 設定為 false 會使得這個組件中的型別
// 對 COM 元件而言為不可見。如果您需要從 COM 存取此組件中
// 的型別,請在該型別上將 ComVisible 屬性設定為 true。
[assembly: ComVisible(false)]
// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID
[assembly: Guid("f03af1c1-ab4c-4152-bbd9-b595e1786719")]
// 組件的版本資訊是由下列四項值構成:
//
// 主要版本
// 次要版本
// 組建編號
// 修訂編號
//
// 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將修訂和組建編號
// 指定為預設值:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.527778 | 56 | 0.715996 | [
"Apache-2.0"
] | rainmakerho/cross-machines-formsbase-auth-sso | webAp2/Properties/AssemblyInfo.cs | 1,270 | 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/d3d12video.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="D3D12_RESOURCE_COORDINATE" /> struct.</summary>
public static unsafe class D3D12_RESOURCE_COORDINATETests
{
/// <summary>Validates that the <see cref="D3D12_RESOURCE_COORDINATE" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<D3D12_RESOURCE_COORDINATE>(), Is.EqualTo(sizeof(D3D12_RESOURCE_COORDINATE)));
}
/// <summary>Validates that the <see cref="D3D12_RESOURCE_COORDINATE" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(D3D12_RESOURCE_COORDINATE).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="D3D12_RESOURCE_COORDINATE" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(D3D12_RESOURCE_COORDINATE), Is.EqualTo(24));
}
}
}
| 40.666667 | 145 | 0.687842 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/d3d12video/D3D12_RESOURCE_COORDINATETests.cs | 1,466 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("searchAndExportDocument")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("searchAndExportDocument")]
[assembly: System.Reflection.AssemblyTitleAttribute("searchAndExportDocument")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.458333 | 81 | 0.660451 | [
"MIT"
] | hetal-ahir/REV-SDK | examples/searchAndExportDocument/obj/Debug/netcoreapp2.1/searchAndExportDocument.AssemblyInfo.cs | 1,019 | C# |
using BookLovers.Base.Infrastructure.Queries;
using BookLovers.Publication.Infrastructure.Dtos.Publications;
namespace BookLovers.Publication.Infrastructure.Queries.Quotes
{
public class PaginatedUserQuotesQuery : IQuery<PaginatedResult<QuoteDto>>
{
public int ReaderId { get; set; }
public int Page { get; set; }
public int Count { get; set; }
public int Order { get; set; }
public bool Descending { get; set; }
public PaginatedUserQuotesQuery()
{
var page = this.Page == 0 ? PaginatedResult.DefaultPage : this.Page;
var count = this.Count == 0 ? PaginatedResult.DefaultItemsPerPage : this.Count;
var order = this.Order == 0 ? QuotesOrder.ByLikes.Value : this.Order;
this.Page = page;
this.Count = count;
this.Order = order;
}
public PaginatedUserQuotesQuery(
int readerId,
int? page,
int? count,
int? order,
bool? descending)
{
this.ReaderId = readerId;
this.Page = page ?? PaginatedResult.DefaultPage;
this.Count = count ?? PaginatedResult.DefaultItemsPerPage;
this.Order = order ?? QuotesOrder.ByLikes.Value;
this.Descending = descending.GetValueOrDefault();
}
}
} | 31.837209 | 91 | 0.597516 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Publication.Infrastructure/Queries/Quotes/PaginatedUserQuotesQuery.cs | 1,371 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using POC.Repository.Interface;
using POC.Models;
namespace POC.Repository.Implementation
{
public class RoleRepository : IRoleRepository
{
/// <summary>
/// Get RoleID Name by RoleName
/// </summary>
/// <param name="Rolename"></param>
/// <returns></returns>
public int getRolesofUserbyRolename(string Rolename)
{
using (var _context = new DatabaseContext())
{
var roleID = (from role in _context.Role
where role.Rolename == Rolename
select role.RoleID).SingleOrDefault();
return roleID;
}
}
public List<Roles> getRoles()
{
using (var _context = new DatabaseContext())
{
var roles = (from role in _context.Role
select role).ToList();
return roles;
}
}
public int AddRole(Roles role)
{
try
{
using (var _context = new DatabaseContext())
{
role.IsActive = true;
_context.Role.Add(role);
return _context.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
public int UpdateRole(Roles role)
{
try
{
using (var _context = new DatabaseContext())
{
role.IsActive = true;
_context.Entry(role).State = EntityState.Modified;
return _context.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
public int DeleteRole(int ID)
{
try
{
using (var _context = new DatabaseContext())
{
var role = (from r in _context.Role
where r.RoleID == ID
select r).FirstOrDefault();
if (role != null)
{
_context.Role.Remove(role);
return _context.SaveChanges();
}
return -1;
}
}
catch (Exception ex)
{
if (ex.InnerException.InnerException.ToString().Contains("The DELETE statement conflicted with the REFERENCE constraint"))
{
throw new Exception("This Role is associated with Employee.Please Unlink the Employee(s) with this Role.");
}
throw new Exception(ex.Message);
}
}
public bool IsRoleExist(string RoleName)
{
try
{
using (var _context = new DatabaseContext())
{
var result = (from role in _context.Role
where role.Rolename == RoleName
select role).Count();
if (result > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
throw;
}
}
public string GetRoleName(int? RoleId)
{
using (var _context = new DatabaseContext())
{
var objrole = (from role in _context.Role
where role.RoleID == RoleId
select role).FirstOrDefault();
if (objrole != null)
return objrole.Rolename;
else
return "";
}
}
public string GetRoleCode(int? RoleId)
{
using (var _context = new DatabaseContext())
{
var objrole = (from role in _context.Role
where role.RoleID == RoleId
select role).FirstOrDefault();
if (objrole != null)
return objrole.RoleCode;
else
return "";
}
}
public Roles GetById(int ID)
{
using (var _context = new DatabaseContext())
{
var objrole = (from role in _context.Role
where role.RoleID == ID
select role).FirstOrDefault();
return objrole;
}
}
public bool CheckRoleCodeExists(string RoleCode)
{
try
{
using (var _context = new DatabaseContext())
{
var result = (from role in _context.Role
where role.RoleCode == RoleCode
select role).Count();
if (result > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
throw;
}
}
public bool CheckRoleNameExists(string RoleName)
{
try
{
using (var _context = new DatabaseContext())
{
var result = (from role in _context.Role
where role.Rolename == RoleName
select role).Count();
if (result > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
throw;
}
}
}
}
| 30.009434 | 138 | 0.377711 | [
"MIT"
] | sunil233/AngularPOC | POC.Repository/Repository/Implementation/RolesRepository.cs | 6,364 | C# |
// Copyright(c) 2021 Digital Asset(Switzerland) GmbH and/or its affiliates.All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace Daml.Ledger.Api.Data.Test.Factories
{
public static class TransactionTreeFactory
{
private static readonly DateTimeOffset _now = DateTimeOffset.UtcNow;
public static TransactionTree TransactionTree1 { get; } = new TransactionTree("transaction1", "command1", "workflow1", _now, CreatedEventFactory.EventsById1, CreatedEventFactory.EventsById1.Keys, "offset1");
public static TransactionTree TransactionTree2 = new TransactionTree("transaction2", "command2", "workflow2", _now.AddDays(2), CreatedEventFactory.EventsById2, CreatedEventFactory.EventsById2.Keys, "offset2");
public static TransactionTree TransactionTree3 = new TransactionTree("transaction1", "command1", "workflow1", _now, CreatedEventFactory.EventsById1, CreatedEventFactory.EventsById1.Keys, "offset1");
}
}
| 58.352941 | 218 | 0.765121 | [
"Apache-2.0"
] | AndrewDCDrummond/daml-net | src/Daml.Ledger.Api.Data.Test/factories/TransactionTreeFactory.cs | 994 | C# |
using BenchmarkDotNet.Attributes;
using CryptoBase.Abstractions.SymmetricCryptos;
using CryptoBase.BouncyCastle.SymmetricCryptos.StreamCryptos;
using CryptoBase.SymmetricCryptos.StreamCryptos;
using System;
using System.Security.Cryptography;
namespace CryptoBase.Benchmark;
[MemoryDiagnoser]
public class RC4Benchmark
{
[Params(1000000)]
public int ByteLength { get; set; }
private Memory<byte> _randombytes;
private byte[] _randomKey = null!;
[GlobalSetup]
public void Setup()
{
_randombytes = RandomNumberGenerator.GetBytes(ByteLength);
_randomKey = RandomNumberGenerator.GetBytes(16);
}
private static void Test(IStreamCrypto crypto, Span<byte> origin)
{
Span<byte> o = stackalloc byte[origin.Length];
crypto.Update(origin, o);
crypto.Dispose();
}
[Benchmark]
public void BouncyCastle()
{
Test(new BcRC4Crypto(_randomKey), _randombytes.Span);
}
[Benchmark(Baseline = true)]
public void RC4()
{
Test(StreamCryptoCreate.Rc4(_randomKey), _randombytes.Span);
}
}
| 21.826087 | 66 | 0.768924 | [
"MIT"
] | HMBSbige/CryptoBase | CryptoBase.Benchmark/RC4Benchmark.cs | 1,004 | C# |
#pragma checksum "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "20ae260217ec86e891965ad991f995d07c2706da"
// <auto-generated/>
#pragma warning disable 1591
namespace OWFBlazorDemo.Pages
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using System.Net.Http.Json;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.AspNetCore.Components.Web.Virtualization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using OWFBlazorDemo;
#line default
#line hidden
#nullable disable
#nullable restore
#line 11 "E:\home\development\blazer\OWFBlazorDemo\_Imports.razor"
using OWFBlazorDemo.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
using OWFBlazorDemo.Services;
#line default
#line hidden
#nullable disable
[Microsoft.AspNetCore.Components.RouteAttribute("/counter")]
public partial class Counter : Microsoft.AspNetCore.Components.ComponentBase, IDisposable
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.AddMarkupContent(0, "<h1>App State Storage: Counter</h1>\r\n\r\n");
__builder.OpenElement(1, "p");
__builder.AddContent(2, "Current count: ");
__builder.AddContent(3,
#nullable restore
#line 10 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
currentCount
#line default
#line hidden
#nullable disable
);
__builder.CloseElement();
__builder.AddMarkupContent(4, "\r\n\r\n");
__builder.OpenElement(5, "button");
__builder.AddAttribute(6, "class", "btn btn-primary");
__builder.AddAttribute(7, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 12 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
IncrementCount
#line default
#line hidden
#nullable disable
));
__builder.AddContent(8, "+ Increment");
__builder.CloseElement();
__builder.AddMarkupContent(9, " \r\n");
__builder.OpenElement(10, "button");
__builder.AddAttribute(11, "class", "btn btn-primary");
__builder.AddAttribute(12, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 13 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
DecrementCount
#line default
#line hidden
#nullable disable
));
__builder.AddContent(13, "- Decrement");
__builder.CloseElement();
__builder.AddMarkupContent(14, " \r\n");
__builder.OpenElement(15, "button");
__builder.AddAttribute(16, "class", "btn btn-primary");
__builder.AddAttribute(17, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 14 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
ResetCount
#line default
#line hidden
#nullable disable
));
__builder.AddContent(18, "0 Reset");
__builder.CloseElement();
__builder.AddMarkupContent(19, "\r\n\r\n<br>\r\n<br>");
}
#pragma warning restore 1998
#nullable restore
#line 19 "E:\home\development\blazer\OWFBlazorDemo\Pages\Counter.razor"
private int currentCount = 0;
[Parameter]
public int IncrementAmount { get; set; } = 1;
protected override async Task OnInitializedAsync()
{
if (AppState == null)
{
System.Console.WriteLine("App State is NULL");
}
currentCount = (int)AppState.get("counter", 0);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
string initialization = (string)AppState.get("initialization", "false");
if (initialization == "false") {
NavigationManager.NavigateTo("/");
}
AppState.set("counter", 0);
}
}
public Counter()
{
}
private async Task IncrementCount()
{
currentCount += IncrementAmount;
AppState.set("counter", currentCount);
await JS.InvokeVoidAsync("interopInterface.INTEROPMessageHandler.broadcast", "blazor.counter", "{'counter': " +
currentCount + ",'status': 'increment'}");
}
private async Task DecrementCount()
{
currentCount -= IncrementAmount;
AppState.set("counter", currentCount);
await JS.InvokeVoidAsync("interopInterface.INTEROPMessageHandler.broadcast", "blazor.counter", "{'counter': " +
currentCount + ",'status': 'decrement'}");
}
private async Task ResetCount()
{
currentCount = 0;
AppState.set("counter", currentCount);
await JS.InvokeVoidAsync("interopInterface.INTEROPMessageHandler.broadcast", "blazor.counter", "{'counter': " +
currentCount + ",'status': 'reset'}");
}
async void IDisposable.Dispose()
{
}
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Components.InjectAttribute] private OWFBlazorDemo.Services.AppState AppState { get; set; }
[global::Microsoft.AspNetCore.Components.InjectAttribute] private NavigationManager NavigationManager { get; set; }
[global::Microsoft.AspNetCore.Components.InjectAttribute] private IJSRuntime JS { get; set; }
}
}
#pragma warning restore 1591
| 31.834043 | 169 | 0.692554 | [
"MIT"
] | ssdhaliwal/OWFBlazor | obj/Debug/net5.0/Razor/Pages/Counter.razor.g.cs | 7,481 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ServiceStack.Common;
using ServiceStack.IO;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
namespace ServiceStack.VirtualPath
{
public interface IWriteableVirtualPathProvider
{
void AddFile(string filePath, string contents);
}
/// <summary>
/// In Memory repository for files. Useful for testing.
/// </summary>
public class InMemoryVirtualPathProvider : AbstractVirtualPathProviderBase, IWriteableVirtualPathProvider
{
public InMemoryVirtualPathProvider(IAppHost appHost)
: base(appHost)
{
this.rootDirectory = new InMemoryVirtualDirectory(this);
}
public InMemoryVirtualDirectory rootDirectory;
public override IVirtualDirectory RootDirectory
{
get { return rootDirectory; }
}
public override string VirtualPathSeparator
{
get { return "/"; }
}
public override string RealPathSeparator
{
get { return "/"; }
}
protected override void Initialize()
{
}
public void AddFile(string filePath, string contents)
{
rootDirectory.AddFile(filePath, contents);
}
public override IVirtualFile GetFile(string virtualPath)
{
return rootDirectory.GetFile(virtualPath)
?? base.GetFile(virtualPath);
}
}
public class InMemoryVirtualDirectory : AbstractVirtualDirectoryBase
{
public InMemoryVirtualDirectory(IVirtualPathProvider owningProvider)
: base(owningProvider)
{
this.files = new List<InMemoryVirtualFile>();
this.dirs = new List<InMemoryVirtualDirectory>();
this.DirLastModified = DateTime.MinValue;
}
public InMemoryVirtualDirectory(IVirtualPathProvider owningProvider, IVirtualDirectory parentDirectory)
: base(owningProvider, parentDirectory) {}
public DateTime DirLastModified { get; set; }
public override DateTime LastModified
{
get { return DirLastModified; }
}
public List<InMemoryVirtualFile> files;
public override IEnumerable<IVirtualFile> Files
{
get { return files.Cast<IVirtualFile>(); }
}
public List<InMemoryVirtualDirectory> dirs;
public override IEnumerable<IVirtualDirectory> Directories
{
get { return dirs.Cast<IVirtualDirectory>(); }
}
public string DirName { get; set; }
public override string Name
{
get { return DirName; }
}
public override IVirtualFile GetFile(string virtualPath)
{
return files.FirstOrDefault(x => x.FilePath == virtualPath);
}
public override IEnumerator<IVirtualNode> GetEnumerator()
{
throw new NotImplementedException();
}
protected override IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName)
{
return files.FirstOrDefault(x => x.FilePath == fileName);
}
protected override IEnumerable<IVirtualFile> GetMatchingFilesInDir(string globPattern)
{
var matchingFilesInBackingDir = EnumerateFiles(globPattern).Cast<IVirtualFile>();
return matchingFilesInBackingDir;
}
public IEnumerable<InMemoryVirtualFile> EnumerateFiles(string pattern)
{
return from dir in dirs
from file in files
where file.Name.Glob(pattern)
select file;
}
protected override IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName)
{
return null;
}
static readonly char[] DirSeps = new[] { '\\', '/' };
public void AddFile(string filePath, string contents)
{
this.files.Add(new InMemoryVirtualFile(VirtualPathProvider, this) {
FilePath = filePath,
FileName = filePath.Split(DirSeps).Last(),
TextContents = contents,
});
}
}
public class InMemoryVirtualFile : AbstractVirtualFileBase
{
public InMemoryVirtualFile(IVirtualPathProvider owningProvider, IVirtualDirectory directory)
: base(owningProvider, directory)
{
this.FileLastModified = DateTime.MinValue;
}
public string FilePath { get; set; }
public string FileName { get; set; }
public override string Name
{
get { return FileName; }
}
public DateTime FileLastModified { get; set; }
public override DateTime LastModified
{
get { return FileLastModified; }
}
public string TextContents { get; set; }
public byte[] ByteContents { get; set; }
public override Stream OpenRead()
{
return new MemoryStream(ByteContents ?? (TextContents ?? "").ToUtf8Bytes());
}
}
} | 30.359551 | 113 | 0.588083 | [
"BSD-3-Clause"
] | GSerjo/ServiceStack | src/ServiceStack/VirtualPath/InMemoryVirtualPathProvider.cs | 5,229 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Tests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Fluent;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class CosmosClientTests
{
public const string AccountEndpoint = "https://localhost:8081/";
public const string ConnectionString = "AccountEndpoint=https://localtestcosmos.documents.azure.com:443/;AccountKey=425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==;";
[TestMethod]
public async Task TestDispose()
{
CosmosClient cosmosClient = new CosmosClient(ConnectionString);
Database database = cosmosClient.GetDatabase("asdf");
Container container = cosmosClient.GetContainer("asdf", "asdf");
TransactionalBatch batch = container.CreateTransactionalBatch(new PartitionKey("asdf"));
batch.ReadItem("Test");
FeedIterator<dynamic> feedIterator1 = container.GetItemQueryIterator<dynamic>();
FeedIterator<dynamic> feedIterator2 = container.GetItemQueryIterator<dynamic>(queryText: "select * from T");
FeedIterator<dynamic> feedIterator3 = database.GetContainerQueryIterator<dynamic>(queryText: "select * from T");
string userAgent = cosmosClient.ClientContext.UserAgent;
// Dispose should be idempotent
cosmosClient.Dispose();
cosmosClient.Dispose();
List<Func<Task>> validateAsync = new List<Func<Task>>()
{
() => cosmosClient.ReadAccountAsync(),
() => cosmosClient.CreateDatabaseAsync("asdf"),
() => database.CreateContainerAsync("asdf", "/pkpathasdf", 200),
() => container.ReadItemAsync<dynamic>("asdf", new PartitionKey("test")),
() => container.Scripts.ReadStoredProcedureAsync("asdf"),
() => container.Scripts.ReadTriggerAsync("asdf"),
() => container.Scripts.ReadUserDefinedFunctionAsync("asdf"),
() => batch.ExecuteAsync(),
() => feedIterator1.ReadNextAsync(),
() => feedIterator2.ReadNextAsync(),
() => feedIterator3.ReadNextAsync(),
};
foreach (Func<Task> asyncFunc in validateAsync)
{
try
{
await asyncFunc();
Assert.Fail("Should throw ObjectDisposedException");
}
catch (CosmosObjectDisposedException e)
{
string expectedMessage = $"Cannot access a disposed 'CosmosClient'. Follow best practices and use the CosmosClient as a singleton." +
$" CosmosClient was disposed at: {cosmosClient.DisposedDateTimeUtc.Value.ToString("o", CultureInfo.InvariantCulture)}; CosmosClient Endpoint: https://localtestcosmos.documents.azure.com/; Created at: {cosmosClient.ClientConfigurationTraceDatum.ClientCreatedDateTimeUtc.ToString("o", CultureInfo.InvariantCulture)}; UserAgent: {userAgent};";
Assert.IsTrue(e.Message.Contains(expectedMessage));
string diagnostics = e.Diagnostics.ToString();
Assert.IsNotNull(diagnostics);
Assert.IsFalse(diagnostics.Contains("NoOp"));
Assert.IsTrue(diagnostics.Contains("Client Configuration"));
string exceptionString = e.ToString();
Assert.IsTrue(exceptionString.Contains(diagnostics));
Assert.IsTrue(exceptionString.Contains(e.Message));
Assert.IsTrue(exceptionString.Contains(e.StackTrace));
}
}
}
[DataTestMethod]
[DataRow(null, "425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==")]
[DataRow(AccountEndpoint, null)]
[DataRow("", "425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==")]
[DataRow(AccountEndpoint, "")]
[ExpectedException(typeof(ArgumentNullException))]
public void InvalidEndpointAndKey(string endpoint, string key)
{
new CosmosClient(endpoint, key);
}
[DataTestMethod]
[DataRow(null, "425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==")]
[DataRow(AccountEndpoint, null)]
[DataRow("", "425Mcv8CXQqzRNCgFNjIhT424GK99CKJvASowTnq15Vt8LeahXTcN5wt3342vQ==")]
[DataRow(AccountEndpoint, "")]
[ExpectedException(typeof(ArgumentNullException))]
public void Builder_InvalidEndpointAndKey(string endpoint, string key)
{
new CosmosClientBuilder(endpoint, key);
}
[DataTestMethod]
[DataRow(AccountEndpoint, "425Mcv8CXQqzRNCgFNjIhT424GK88ckJvASowTnq15Vt8LeahXTcN5wt3342vQ==")]
public async Task InvalidKey_ExceptionFullStacktrace(string endpoint, string key)
{
CosmosClient client = new CosmosClient(endpoint, key);
string sqlQueryText = "SELECT * FROM c";
try
{
QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
FeedIterator<object> queryResultSetIterator = client.GetContainer(new Guid().ToString(), new Guid().ToString()).GetItemQueryIterator<object>(queryDefinition);
while (queryResultSetIterator.HasMoreResults)
{
await queryResultSetIterator.ReadNextAsync();
}
}
catch (Exception ex)
{
Assert.IsTrue(ex.StackTrace.Contains("GatewayAccountReader.GetDatabaseAccountAsync"), ex.StackTrace);
}
}
[TestMethod]
public void InvalidConnectionString()
{
Assert.ThrowsException<ArgumentException>(() => new CosmosClient(""));
Assert.ThrowsException<ArgumentNullException>(() => new CosmosClient(null));
}
[TestMethod]
public async Task ValidateAuthorizationTokenProviderTestAsync()
{
string authKeyValue = "MockAuthKey";
Mock<AuthorizationTokenProvider> mockAuth = new Mock<AuthorizationTokenProvider>(MockBehavior.Strict);
mockAuth.Setup(x => x.Dispose());
mockAuth.Setup(x => x.AddAuthorizationHeaderAsync(
It.IsAny<Documents.Collections.INameValueCollection>(),
It.IsAny<Uri>(),
It.IsAny<string>(),
It.IsAny<Documents.AuthorizationTokenType>()))
.Callback<Documents.Collections.INameValueCollection, Uri, string, Documents.AuthorizationTokenType>(
(headers, uri, verb, tokenType) => headers.Add(Documents.HttpConstants.HttpHeaders.Authorization, authKeyValue))
.Returns(() => new ValueTask());
bool validAuth = false;
Exception exceptionToThrow = new Exception("TestException");
Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>();
mockHttpHandler.Setup(x => x.SendAsync(
It.IsAny<HttpRequestMessage>(),
It.IsAny<CancellationToken>()))
.Callback<HttpRequestMessage, CancellationToken>(
(request, cancellationToken) =>
{
Assert.IsTrue(request.Headers.TryGetValues(Documents.HttpConstants.HttpHeaders.Authorization, out IEnumerable<string> authValues));
Assert.AreEqual(authKeyValue, authValues.First());
validAuth = true;
}).Throws(exceptionToThrow);
using CosmosClient client = new CosmosClient(
"https://localhost:8081",
authorizationTokenProvider: mockAuth.Object,
new CosmosClientOptions()
{
HttpClientFactory = () => new HttpClient(new HttpHandlerHelper(mockHttpHandler.Object)),
});
Container container = client.GetContainer("Test", "MockTest");
try
{
await container.ReadItemAsync<ToDoActivity>(Guid.NewGuid().ToString(), new PartitionKey(Guid.NewGuid().ToString()));
}
catch (Exception e) when (object.ReferenceEquals(e, exceptionToThrow))
{
}
Assert.IsTrue(validAuth);
}
[TestMethod]
public void Builder_InvalidConnectionString()
{
Assert.ThrowsException<ArgumentException>(() => new CosmosClientBuilder(""));
Assert.ThrowsException<ArgumentNullException>(() => new CosmosClientBuilder(null));
}
[TestMethod]
public void Builder_ValidateHttpFactory()
{
_ = new CosmosClientBuilder("<<endpoint-here>>", "<<key-here>>")
.WithHttpClientFactory(() => new HttpClient())
.WithConnectionModeGateway();
// Validate that setting it to null does not throw an argument exception
_ = new CosmosClientOptions()
{
HttpClientFactory = null,
WebProxy = new Mock<IWebProxy>().Object,
};
_ = new CosmosClientOptions()
{
WebProxy = new Mock<IWebProxy>().Object,
HttpClientFactory = null,
};
_ = new CosmosClientOptions()
{
WebProxy = null,
HttpClientFactory = () => new HttpClient(),
};
_ = new CosmosClientOptions()
{
HttpClientFactory = () => new HttpClient(),
WebProxy = null,
};
}
}
}
| 45.111111 | 364 | 0.594975 | [
"MIT"
] | askazakov/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/CosmosClientTests.cs | 10,152 | 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 Xunit;
using static Interop;
namespace System.Windows.Forms.Tests
{
public class SplitContainer_SplitContainerAccessibilityObjectTests : IClassFixture<ThreadExceptionFixture>
{
[WinFormsFact]
public void SplitContainerAccessibilityObject_Ctor_Default()
{
using SplitContainer splitContainer = new SplitContainer();
splitContainer.CreateControl();
Assert.NotNull(splitContainer.AccessibilityObject);
Assert.True(splitContainer.IsHandleCreated);
}
[WinFormsFact]
public void SplitContainerAccessibilityObject_ControlType_IsPane_IfAccessibleRoleIsDefault()
{
using SplitContainer splitContainer = new SplitContainer();
splitContainer.CreateControl();
// AccessibleRole is not set = Default
object actual = splitContainer.AccessibilityObject.GetPropertyValue(UiaCore.UIA.ControlTypePropertyId);
Assert.Equal(UiaCore.UIA.PaneControlTypeId, actual);
Assert.True(splitContainer.IsHandleCreated);
}
[WinFormsFact]
public void SplitContainerAccessibilityObject_Role_IsClient_ByDefault()
{
using SplitContainer splitContainer = new SplitContainer();
splitContainer.CreateControl();
// AccessibleRole is not set = Default
AccessibleRole actual = splitContainer.AccessibilityObject.Role;
Assert.Equal(AccessibleRole.Client, actual);
Assert.True(splitContainer.IsHandleCreated);
}
public static IEnumerable<object[]> SplitContainerAccessibleObject_GetPropertyValue_ControlType_IsExpected_ForCustomRole_TestData()
{
Array roles = Enum.GetValues(typeof(AccessibleRole));
foreach (AccessibleRole role in roles)
{
if (role == AccessibleRole.Default)
{
continue; // The test checks custom roles
}
yield return new object[] { role };
}
}
[WinFormsTheory]
[MemberData(nameof(SplitContainerAccessibleObject_GetPropertyValue_ControlType_IsExpected_ForCustomRole_TestData))]
public void SplitContainerAccessibleObject_GetPropertyValue_ControlType_IsExpected_ForCustomRole(AccessibleRole role)
{
using SplitContainer splitContainer = new SplitContainer();
splitContainer.AccessibleRole = role;
object actual = splitContainer.AccessibilityObject.GetPropertyValue(UiaCore.UIA.ControlTypePropertyId);
UiaCore.UIA expected = AccessibleRoleControlTypeMap.GetControlType(role);
Assert.Equal(expected, actual);
Assert.False(splitContainer.IsHandleCreated);
}
}
}
| 38.721519 | 139 | 0.683557 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/SplitContainer.SplitContainerAccessibleObjectTests.cs | 3,061 | C# |
using System.Reflection;
// 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: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("15.0.1.0")]
[assembly: AssemblyFileVersion("15.0.1.0")]
[assembly: AssemblyTitleAttribute("MS-VIEWSS_Adapter")]
[assembly: AssemblyProductAttribute("Microsoft SharePoint Protocol Test Suite")] | 49.6 | 80 | 0.784274 | [
"MIT"
] | ChangDu2021/Interop-TestSuites | SharePoint/Source/MS-VIEWSS/Adapter/Properties/AssemblyInfo.cs | 496 | C# |
namespace Cedar.Handlers
{
using System.Collections.Generic;
public abstract class DomainEventMessage
{
public readonly dynamic DomainEvent;
public readonly IDictionary<string, object> Headers;
public readonly int Version;
public readonly string CheckpointToken;
public readonly string StreamId;
protected DomainEventMessage(
string streamId,
object domainEvent,
int version,
IDictionary<string, object> headers,
string checkpointToken)
{
DomainEvent = domainEvent;
Headers = headers;
Version = version;
CheckpointToken = checkpointToken;
StreamId = streamId;
}
public override string ToString()
{
return DomainEvent.ToString();
}
}
public class DomainEventMessage<T> : DomainEventMessage
where T : class
{
public new readonly T DomainEvent;
public DomainEventMessage(
string streamId,
T domainEvent,
int version,
IDictionary<string, object> headers,
string checkpointToken) : base(streamId, domainEvent, version, headers, checkpointToken)
{
DomainEvent = domainEvent;
}
}
} | 27.916667 | 100 | 0.591045 | [
"MIT"
] | AGiorgetti/Cedar | src/Cedar/Handlers/DomainEventMessage.cs | 1,342 | C# |
using Abp.Domain.Entities.Auditing;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
namespace HS.Farm.Core
{
[Table("AbpThuHoach")]
public class ThuHoach : FullAuditedEntity, IMayHaveTenant
{
[MaxLength(50)]
[Required]
public virtual string TenSanPham { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy/dd/MM}")]
[Required]
public virtual DateTime NgayThuHoach { get; set; }
public virtual int? TenantId { get; set; }
}
}
| 28.190476 | 61 | 0.680743 | [
"MIT"
] | tranthebao/HS.Farm | aspnet-core/src/HS.Farm.Core/Farm/ThuHoach.cs | 594 | C# |
using pdxpartyparrot.Core;
using pdxpartyparrot.Core.Time;
using pdxpartyparrot.Core.Util;
using pdxpartyparrot.Game.Data.Characters.BehaviorComponents;
using UnityEngine;
namespace pdxpartyparrot.Game.Characters.BehaviorComponents
{
[RequireComponent(typeof(JumpBehaviorComponent))]
public class HoverBehaviorComponent : CharacterBehaviorComponent
{
#region Actions
public class HoverAction : CharacterBehaviorAction
{
public static HoverAction Default = new HoverAction();
}
#endregion
[SerializeField]
private HoverBehaviorComponentData _data;
[SerializeField]
[ReadOnly]
private bool _isHeld;
[SerializeField]
[ReadOnly]
private float _heldSeconds;
private bool CanHover => _heldSeconds >= _data.HoverHoldSeconds;
[SerializeField]
[ReadOnly]
private float _hoverTimeSeconds;
public float RemainingPercent => 1.0f - (_hoverTimeSeconds / _data.HoverTimeSeconds);
private ITimer _cooldownTimer;
private bool IsHoverCooldown => _cooldownTimer.SecondsRemaining > 0.0f;
[SerializeField]
[ReadOnly]
private bool _isHovering;
public bool IsHovering => _isHovering;
#region Unity Lifecycle
protected override void Awake()
{
base.Awake();
_cooldownTimer = TimeManager.Instance.AddTimer();
}
protected override void OnDestroy()
{
if(TimeManager.HasInstance) {
TimeManager.Instance.RemoveTimer(_cooldownTimer);
}
_cooldownTimer = null;
base.OnDestroy();
}
private void Update()
{
if(PartyParrotManager.Instance.IsPaused) {
return;
}
float dt = Time.deltaTime;
if(_isHeld && !IsHoverCooldown) {
_heldSeconds += dt;
}
if(IsHovering) {
_hoverTimeSeconds += dt;
if(_hoverTimeSeconds >= _data.HoverTimeSeconds) {
_hoverTimeSeconds = _data.HoverTimeSeconds;
StopHovering();
}
} else if(CanHover) {
StartHovering();
} else if(_hoverTimeSeconds > 0.0f) {
_hoverTimeSeconds -= dt * _data.HoverRechargeRate;
if(_hoverTimeSeconds < 0.0f) {
_hoverTimeSeconds = 0.0f;
}
}
}
private void LateUpdate()
{
if(Behavior.IsGrounded) {
_isHeld = false;
_heldSeconds = 0;
StopHovering();
}
}
#endregion
public override bool OnPhysicsUpdate(float dt)
{
if(!IsHovering) {
return false;
}
Vector3 acceleration = (_data.HoverAcceleration + Behavior.CharacterBehaviorData.FallSpeedAdjustment) * Vector3.up;
// TODO: this probably needs to be * or / mass since it's ForceMode.Force instead of ForceMode.Acceleration
Behavior.Movement.AddForce(acceleration);
return false;
}
public override bool OnStarted(CharacterBehaviorAction action)
{
if(!(action is HoverAction)) {
return false;
}
if(Behavior.IsGrounded && !_data.HoverWhenGrounded) {
return false;
}
_isHeld = true;
_heldSeconds = 0;
return true;
}
// NOTE: we want to consume jump actions if we're hovering
public override bool OnPerformed(CharacterBehaviorAction action)
{
if(!(action is JumpBehaviorComponent.JumpAction)) {
return false;
}
return _isHovering;
}
public override bool OnCancelled(CharacterBehaviorAction action)
{
if(!(action is HoverAction)) {
return false;
}
if(!IsHovering) {
return false;
}
_isHeld = false;
_heldSeconds = 0;
bool wasHover = _isHovering;
StopHovering();
return wasHover;
}
private void StartHovering()
{
_isHovering = true;
if(null != Behavior.Animator) {
Behavior.Animator.SetBool(_data.HoverParam, true);
}
// stop all vertical movement immediately
Behavior.Movement.Velocity = new Vector3(Behavior.Movement.Velocity.x, 0.0f, Behavior.Movement.Velocity.z);
}
public void StopHovering()
{
bool wasHovering = IsHovering;
_isHovering = false;
if(null != Behavior.Animator) {
Behavior.Animator.SetBool(_data.HoverParam, false);
}
if(wasHovering) {
_cooldownTimer.Start(_data.HoverCooldownSeconds);
}
}
}
}
| 26.732984 | 127 | 0.549354 | [
"Apache-2.0"
] | pdxparrot/ssj2019 | Assets/Scripts/Game/Characters/BehaviorComponents/HoverBehaviorComponent.cs | 5,108 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pose;
namespace Pose.Tests.Mocks
{
[TestClass]
public class MockConstructorTests
{
public class MyClass
{
public MyClass()
{
MyProperty = 5;
}
public MyClass(int property)
{
MyProperty = property;
}
public int MyProperty { get; set; }
}
public class ShimMyClass
{
public static MyClass MyClass()
{
return new MyClass()
{
MyProperty = 10
};
}
public static MyClass MyClass(int property)
{
return new MyClass()
{
MyProperty = 30
};
}
}
[TestMethod]
public void MockMethod()
{
Mock mock = Mock.It<MyClass, ShimMyClass>();
MyClass myClass1 = new MyClass();
Assert.AreEqual(5, myClass1.MyProperty);
MyClass myClass2 = new MyClass(20);
Assert.AreEqual(20, myClass2.MyProperty);
PoseContext.Isolate(() =>
{
MyClass myClassA = new MyClass();
Assert.AreEqual("10", myClassA.MyProperty.ToString());
MyClass myClassB = new MyClass(20);
Assert.AreEqual("30", myClassB.MyProperty.ToString());
}, mock);
Assert.AreEqual(5, myClass1.MyProperty);
}
}
}
| 23.768116 | 74 | 0.457927 | [
"MIT"
] | jonkeda/pose | test/Pose.Tests/Mocks/MockConstructorTests.cs | 1,642 | C# |
#if !NETSTANDARD2_0
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.Core.Framework.Graph;
using OfficeDevPnP.Core.Framework.Provisioning.Connectors;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers;
using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
namespace OfficeDevPnP.Core.Tests.Framework.Providers
{
[TestClass]
public class BaseTemplateTests
{
protected class BaseTemplate
{
public BaseTemplate(string template, string subSiteTemplate = "", string saveAsTemplate = "", bool skipDeleteCreateCycle = false)
{
Template = template;
SubSiteTemplate = subSiteTemplate;
SaveAsTemplate = saveAsTemplate;
SkipDeleteCreateCycle = skipDeleteCreateCycle;
}
public string Template { get; set; }
public string SubSiteTemplate { get; set; }
public string SaveAsTemplate { get; set; }
public bool SkipDeleteCreateCycle { get; set; }
}
[TestMethod]
[Ignore]
public void ExtractMinimalTemplateSetForRelease()
{
bool deleteSites = true;
bool createSites = true;
List<BaseTemplate> templates = new List<BaseTemplate>(1);
templates.Add(new BaseTemplate("STS#0"));
#if !ONPREMISES || SP2019
templates.Add(new BaseTemplate("STS#3"));
#endif
#if !ONPREMISES
templates.Add(new BaseTemplate("SITEPAGEPUBLISHING#0"));
templates.Add(new BaseTemplate("GROUP#0", skipDeleteCreateCycle: true));
#endif
ProcessBaseTemplates(templates, deleteSites, createSites);
}
[TestMethod]
[Ignore]
public void ExtractOtherTemplatesForRelease()
{
// IMPORTANT: extraction needs to be done with user credentials, not app-only. With app-only certain templates (like BDR) will fail
// use these flags to save time if the process failed after delete or create sites was done
bool deleteSites = false;
bool createSites = false;
List<BaseTemplate> templates = new List<BaseTemplate>(15);
templates.Add(new BaseTemplate("BLOG#0"));
templates.Add(new BaseTemplate("BDR#0"));
templates.Add(new BaseTemplate("DEV#0"));
templates.Add(new BaseTemplate("OFFILE#1"));
#if !ONPREMISES
templates.Add(new BaseTemplate("EHS#1"));
templates.Add(new BaseTemplate("BLANKINTERNETCONTAINER#0", "", "BLANKINTERNET#0"));
#else
templates.Add(new BaseTemplate("STS#1"));
templates.Add(new BaseTemplate("BLANKINTERNET#0"));
#endif
templates.Add(new BaseTemplate("BICENTERSITE#0"));
templates.Add(new BaseTemplate("SRCHCEN#0"));
templates.Add(new BaseTemplate("BLANKINTERNETCONTAINER#0", "CMSPUBLISHING#0", "CMSPUBLISHING#0"));
templates.Add(new BaseTemplate("ENTERWIKI#0"));
templates.Add(new BaseTemplate("PROJECTSITE#0"));
templates.Add(new BaseTemplate("COMMUNITY#0"));
templates.Add(new BaseTemplate("COMMUNITYPORTAL#0"));
templates.Add(new BaseTemplate("SRCHCENTERLITE#0"));
templates.Add(new BaseTemplate("VISPRUS#0"));
ProcessBaseTemplates(templates, deleteSites, createSites);
}
[TestMethod]
[Ignore]
public void ExtractSingleTemplate2()
{
bool deleteSites = true;
bool createSites = true;
List<BaseTemplate> templates = new List<BaseTemplate>(1);
templates.Add(new BaseTemplate("SITEPAGEPUBLISHING#0", skipDeleteCreateCycle: false));
ProcessBaseTemplates(templates, deleteSites, createSites);
}
[TestMethod]
[Ignore]
public void ExtractBaseTemplates2()
{
// IMPORTANT: extraction needs to be done with user credentials, not app-only. With app-only certain templates (like BDR) will fail
// use these flags to save time if the process failed after delete or create sites was done
bool deleteSites = true;
bool createSites = true;
List<BaseTemplate> templates = new List<BaseTemplate>(15);
templates.Add(new BaseTemplate("STS#0"));
templates.Add(new BaseTemplate("BLOG#0"));
templates.Add(new BaseTemplate("BDR#0"));
templates.Add(new BaseTemplate("DEV#0"));
templates.Add(new BaseTemplate("OFFILE#1"));
#if !ONPREMISES
templates.Add(new BaseTemplate("GROUP#0", skipDeleteCreateCycle: true));
templates.Add(new BaseTemplate("SITEPAGEPUBLISHING#0"));
templates.Add(new BaseTemplate("EHS#1"));
templates.Add(new BaseTemplate("BLANKINTERNETCONTAINER#0", "", "BLANKINTERNET#0"));
#else
templates.Add(new BaseTemplate("STS#1"));
templates.Add(new BaseTemplate("BLANKINTERNET#0"));
#endif
#if !ONPREMISES || SP2019
templates.Add(new BaseTemplate("STS#3"));
#endif
templates.Add(new BaseTemplate("BICENTERSITE#0"));
templates.Add(new BaseTemplate("SRCHCEN#0"));
templates.Add(new BaseTemplate("BLANKINTERNETCONTAINER#0", "CMSPUBLISHING#0", "CMSPUBLISHING#0"));
templates.Add(new BaseTemplate("ENTERWIKI#0"));
templates.Add(new BaseTemplate("PROJECTSITE#0"));
templates.Add(new BaseTemplate("COMMUNITY#0"));
templates.Add(new BaseTemplate("COMMUNITYPORTAL#0"));
templates.Add(new BaseTemplate("SRCHCENTERLITE#0"));
templates.Add(new BaseTemplate("VISPRUS#0"));
ProcessBaseTemplates(templates, deleteSites, createSites);
}
[TestMethod]
[Ignore]
public void ExtractSingleBaseTemplate2()
{
// use these flags to save time if the process failed after delete or create sites was done
bool deleteSites = true;
bool createSites = true;
List<BaseTemplate> templates = new List<BaseTemplate>(1);
templates.Add(new BaseTemplate("GROUP#0", skipDeleteCreateCycle: true));
ProcessBaseTemplates(templates, deleteSites, createSites);
}
private void ProcessBaseTemplates(List<BaseTemplate> templates, bool deleteSites, bool createSites)
{
using (var tenantCtx = TestCommon.CreateTenantClientContext())
{
tenantCtx.RequestTimeout = 1000 * 60 * 15;
Tenant tenant = new Tenant(tenantCtx);
#if !ONPREMISES
if (deleteSites)
{
// First delete all template site collections when in SPO
foreach (var template in templates)
{
string siteUrl = GetSiteUrl(template);
try
{
Console.WriteLine("Deleting existing site {0}", siteUrl);
if (template.SkipDeleteCreateCycle)
{
// Do nothing for the time being since we don't allow group deletion using app-only context
}
else
{
tenant.DeleteSiteCollection(siteUrl, false);
}
}
catch{ }
}
}
if (createSites)
{
// Create site collections
foreach (var template in templates)
{
string siteUrl = GetSiteUrl(template);
Console.WriteLine("Creating site {0}", siteUrl);
if (template.SkipDeleteCreateCycle)
{
// Do nothing for the time being since we don't allow group creation using app-only context
}
else
{
bool siteExists = false;
if (template.SubSiteTemplate.Length > 0)
{
siteExists = tenant.SiteExists(siteUrl);
}
if (!siteExists)
{
if (template.Template.StartsWith("SITEPAGEPUBLISHING"))
{
using (var clientContext = TestCommon.CreateClientContext())
{
clientContext.CreateSiteAsync(new Core.Sites.CommunicationSiteCollectionCreationInformation()
{
Url = siteUrl,
SiteDesign = Core.Sites.CommunicationSiteDesign.Blank,
Title = "Template Site",
Lcid = 1033
}).Wait();
}
}
else
{
tenant.CreateSiteCollection(new Entities.SiteEntity()
{
Lcid = 1033,
TimeZoneId = 4,
SiteOwnerLogin = (TestCommon.Credentials as SharePointOnlineCredentials).UserName,
Title = "Template Site",
Template = template.Template,
Url = siteUrl,
}, true, true);
}
}
if (template.SubSiteTemplate.Length > 0)
{
using (ClientContext ctx = TestCommon.CreateClientContext())
{
using (var sitecolCtx = ctx.Clone(siteUrl))
{
sitecolCtx.Web.Webs.Add(new WebCreationInformation()
{
Title = string.Format("template{0}", template.SubSiteTemplate),
Language = 1033,
Url = string.Format("template{0}", template.SubSiteTemplate.Replace("#", "")),
UseSamePermissionsAsParentSite = true
});
sitecolCtx.ExecuteQueryRetry();
}
}
}
}
}
}
#endif
}
// Export the base templates
using (ClientContext ctx = TestCommon.CreateClientContext())
{
foreach (var template in templates)
{
string siteUrl = GetSiteUrl(template, false);
// Export the base templates
using (ClientContext cc = ctx.Clone(siteUrl))
{
cc.RequestTimeout = 1000 * 60 * 15;
// Specify null as base template since we do want "everything" in this case
ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
creationInfo.BaseTemplate = null;
// Do not extract the home page for the base templates
creationInfo.HandlersToProcess ^= Handlers.PageContents;
// Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
// blankinternet#0 as web template using CSOM/SSOM API
string templateName = template.Template;
if (template.SaveAsTemplate.Length > 0)
{
templateName = template.SaveAsTemplate;
}
ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
if (template.SubSiteTemplate.Length > 0)
{
p.Id = String.Format("{0}template", template.SubSiteTemplate.Replace("#", ""));
}
else
{
p.Id = String.Format("{0}template", templateName.Replace("#", ""));
}
// Cleanup before saving
p.Security.AdditionalAdministrators.Clear();
// persist the template using the XML provider
XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
if (template.SubSiteTemplate.Length > 0)
{
provider.SaveAs(p, String.Format("{0}Template.xml", template.SubSiteTemplate.Replace("#", "")));
}
else
{
provider.SaveAs(p, String.Format("{0}Template.xml", templateName.Replace("#", "")));
}
}
}
}
}
private static string GetSiteUrl(BaseTemplate template, bool siteCollectionUrl = true)
{
Uri devSiteUrl = new Uri(TestCommon.AppSetting("SPODevSiteUrl"));
string baseUrl = String.Format("{0}://{1}", devSiteUrl.Scheme, devSiteUrl.DnsSafeHost);
string siteUrl = "";
if (template.SubSiteTemplate.Length > 0)
{
if (siteCollectionUrl)
{
siteUrl = string.Format("{1}/sites/template{2}", template.Template.Replace("#", ""), baseUrl, template.SubSiteTemplate.Replace("#", ""));
}
else
{
siteUrl = string.Format("{1}/sites/template{2}/template{2}", template.Template.Replace("#", ""), baseUrl, template.SubSiteTemplate.Replace("#", ""));
}
}
else
{
siteUrl = string.Format("{1}/sites/template{0}", template.Template.Replace("#", ""), baseUrl);
}
return siteUrl;
}
/// <summary>
/// This is not a test, merely used to dump the needed template files
/// </summary>
[TestMethod]
[Ignore]
public void DumpBaseTemplates()
{
using (ClientContext ctx = TestCommon.CreateClientContext())
{
DumpTemplate(ctx, "STS#0");
DumpTemplate(ctx, "BLOG#0");
DumpTemplate(ctx, "BDR#0");
DumpTemplate(ctx, "DEV#0");
DumpTemplate(ctx, "OFFILE#1");
#if !ONPREMISES
DumpTemplate(ctx, "EHS#1");
DumpTemplate(ctx, "BLANKINTERNETCONTAINER#0", "", "BLANKINTERNET#0");
#else
DumpTemplate(ctx, "STS#1");
DumpTemplate(ctx, "BLANKINTERNET#0");
#endif
DumpTemplate(ctx, "BICENTERSITE#0");
DumpTemplate(ctx, "SRCHCEN#0");
DumpTemplate(ctx, "BLANKINTERNETCONTAINER#0", "CMSPUBLISHING#0");
DumpTemplate(ctx, "ENTERWIKI#0");
DumpTemplate(ctx, "PROJECTSITE#0");
DumpTemplate(ctx, "COMMUNITY#0");
DumpTemplate(ctx, "COMMUNITYPORTAL#0");
DumpTemplate(ctx, "SRCHCENTERLITE#0");
DumpTemplate(ctx, "VISPRUS#0");
}
}
[TestMethod]
[Ignore]
public void DumpSingleTemplate()
{
using (ClientContext ctx = TestCommon.CreateClientContext())
{
DumpTemplate(ctx, "STS#0");
}
}
private void DumpTemplate(ClientContext ctx, string template, string subSiteTemplate = "", string saveAsTemplate = "")
{
Uri devSiteUrl = new Uri(TestCommon.AppSetting("SPODevSiteUrl"));
string baseUrl = String.Format("{0}://{1}", devSiteUrl.Scheme, devSiteUrl.DnsSafeHost);
string siteUrl = "";
if (subSiteTemplate.Length > 0)
{
siteUrl = string.Format("{1}/sites/template{0}/template{2}", template.Replace("#", ""), baseUrl, subSiteTemplate.Replace("#", ""));
#if !ONPREMISES
var siteCollectionUrl = string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl);
CreateSiteCollection(template, siteCollectionUrl);
using (var sitecolCtx = ctx.Clone(siteCollectionUrl))
{
sitecolCtx.Web.Webs.Add(new WebCreationInformation()
{
Title = string.Format("template{0}", subSiteTemplate),
Language = 1033,
Url = string.Format("template{0}", subSiteTemplate.Replace("#", "")),
UseSamePermissionsAsParentSite = true
});
sitecolCtx.ExecuteQueryRetry();
}
#endif
}
else
{
siteUrl = string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl);
#if !ONPREMISES
CreateSiteCollection(template, siteUrl);
#endif
}
using (ClientContext cc = ctx.Clone(siteUrl))
{
// Specify null as base template since we do want "everything" in this case
ProvisioningTemplateCreationInformation creationInfo = new ProvisioningTemplateCreationInformation(cc.Web);
creationInfo.BaseTemplate = null;
// Do not extract the home page for the base templates
creationInfo.HandlersToProcess ^= Handlers.PageContents;
// Override the save name. Case is online site collection provisioned using blankinternetcontainer#0 which returns
// blankinternet#0 as web template using CSOM/SSOM API
if (saveAsTemplate.Length > 0)
{
template = saveAsTemplate;
}
ProvisioningTemplate p = cc.Web.GetProvisioningTemplate(creationInfo);
if (subSiteTemplate.Length > 0)
{
p.Id = String.Format("{0}template", subSiteTemplate.Replace("#", ""));
}
else
{
p.Id = String.Format("{0}template", template.Replace("#", ""));
}
// Cleanup before saving
p.Security.AdditionalAdministrators.Clear();
XMLFileSystemTemplateProvider provider = new XMLFileSystemTemplateProvider(".", "");
if (subSiteTemplate.Length > 0)
{
provider.SaveAs(p, String.Format("{0}Template.xml", subSiteTemplate.Replace("#", "")));
}
else
{
provider.SaveAs(p, String.Format("{0}Template.xml", template.Replace("#", "")));
}
#if !ONPREMISES
using (var tenantCtx = TestCommon.CreateTenantClientContext())
{
Tenant tenant = new Tenant(tenantCtx);
Console.WriteLine("Deleting new site {0}", string.Format("{1}/sites/template{0}", template.Replace("#", ""), baseUrl));
tenant.DeleteSiteCollection(siteUrl, false);
}
#endif
}
}
#if !ONPREMISES
private static void CreateSiteCollection(string template, string siteUrl)
{
// check if site exists
using (var tenantCtx = TestCommon.CreateTenantClientContext())
{
Tenant tenant = new Tenant(tenantCtx);
if (tenant.SiteExists(siteUrl))
{
Console.WriteLine("Deleting existing site {0}", siteUrl);
tenant.DeleteSiteCollection(siteUrl, false);
}
Console.WriteLine("Creating new site {0}", siteUrl);
tenant.CreateSiteCollection(new Entities.SiteEntity()
{
Lcid = 1033,
TimeZoneId = 4,
SiteOwnerLogin = (TestCommon.Credentials as SharePointOnlineCredentials).UserName,
Title = "Template Site",
Template = template,
Url = siteUrl,
}, true, true);
}
}
#endif
/// <summary>
/// Get the base template for the current site
/// </summary>
[TestMethod]
public void GetBaseTemplateForCurrentSiteTest()
{
using (ClientContext ctx = TestCommon.CreateClientContext())
{
ProvisioningTemplate t = ctx.Web.GetBaseTemplate();
Assert.IsNotNull(t);
}
}
}
}
#endif | 42.508637 | 169 | 0.509189 | [
"MIT"
] | bricenocar/PnP-Sites-Core | Core/OfficeDevPnP.Core.Tests/Framework/Providers/BaseTemplateTests.cs | 22,149 | C# |
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Ateliex.Modules.Decisoes.Vendas
{
public class AoCalcularTaxaDeMarcacao : Test
{
protected CalculadoraDeTaxaDeMarcacao calculadoraDeTaxaDeMarcacao;
protected decimal custoFixo;
protected decimal custoVariavel;
protected decimal margemDeLucro;
protected decimal taxaDeMarcacao;
public AoCalcularTaxaDeMarcacao()
{
calculadoraDeTaxaDeMarcacao = new CalculadoraDeTaxaDeMarcacao();
}
public override void Act()
{
taxaDeMarcacao = calculadoraDeTaxaDeMarcacao.CalculaTaxaDeMarcacao(custoFixo, custoVariavel, margemDeLucro);
}
public class ComSucesso : AoCalcularTaxaDeMarcacao
{
[Fact]
public void O_Resuldado_Deve_Ser_Correto()
{
taxaDeMarcacao.Should().BeGreaterThan(0);
}
}
}
}
| 24.634146 | 120 | 0.657426 | [
"MIT"
] | ateliex/UseCaseDrivenDesign | tests/Ateliex.Domain.Tests/Modules/Decisoes/Vendas/CalculadoraDeTaxaDeMarcacaoTests.cs | 1,012 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Diagnostics;
using System.Runtime.CompilerServices; // Do not remove. This is necessary for netstandard, since this file is mirrored into corefx
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
namespace System
{
internal static partial class SpanHelpers // .T
{
public static int IndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
T valueHead = value;
ref T valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
// Adapted from IndexOf(...)
public unsafe static bool Contains<T>(ref T searchSpace, T value, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while (length >= 8)
{
length -= 8;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 1)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 2)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 3)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 4)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 5)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 6)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 7)))
{
goto Found;
}
index += 8;
}
if (length >= 4)
{
length -= 4;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 1)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 2)) ||
value.Equals(Unsafe.Add(ref searchSpace, index + 3)))
{
goto Found;
}
index += 4;
}
while (length > 0)
{
length -= 1;
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
index += 1;
}
}
else
{
byte* len = (byte*)length;
for (index = (IntPtr)0; index.ToPointer() < len; index += 1)
{
if ((object)Unsafe.Add(ref searchSpace, index) is null)
{
goto Found;
}
}
}
return false;
Found:
return true;
}
public static unsafe int IndexOf<T>(ref T searchSpace, T value, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while (length >= 8)
{
length -= 8;
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 4)))
goto Found4;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 5)))
goto Found5;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 6)))
goto Found6;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 7)))
goto Found7;
index += 8;
}
if (length >= 4)
{
length -= 4;
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, index + 3)))
goto Found3;
index += 4;
}
while (length > 0)
{
if (value.Equals(Unsafe.Add(ref searchSpace, index)))
goto Found;
index += 1;
length--;
}
}
else
{
byte* len = (byte*)length;
for (index = (IntPtr)0; index.ToPointer() < len; index += 1)
{
if ((object)Unsafe.Add(ref searchSpace, index) is null)
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
int index = 0;
if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while ((length - index) >= 8)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found7;
index += 8;
}
if ((length - index) >= 4)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
index += 4;
}
while (index < length)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
index++;
}
}
else
{
for (index = 0; index < length; index++)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if ((object?)lookUp is null)
{
if ((object?)value0 is null || (object?)value1 is null)
{
goto Found;
}
}
else if (lookUp.Equals(value0) || lookUp.Equals(value1))
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return index;
Found1:
return index + 1;
Found2:
return index + 2;
Found3:
return index + 3;
Found4:
return index + 4;
Found5:
return index + 5;
Found6:
return index + 6;
Found7:
return index + 7;
}
public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
int index = 0;
if (default(T)! != null || ((object)value0 != null && (object)value1 != null && (object)value2 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while ((length - index) >= 8)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found7;
index += 8;
}
if ((length - index) >= 4)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
index += 4;
}
while (index < length)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
index++;
}
}
else
{
for (index = 0; index < length; index++)
{
lookUp = Unsafe.Add(ref searchSpace, index);
if ((object?)lookUp is null)
{
if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null)
{
goto Found;
}
}
else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2))
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return index;
Found1:
return index + 1;
Found2:
return index + 2;
Found3:
return index + 3;
Found4:
return index + 4;
Found5:
return index + 5;
Found6:
return index + 6;
Found7:
return index + 7;
}
public static int IndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if ((uint)tempIndex < (uint)index)
{
index = tempIndex;
// Reduce space for search, cause we don't care if we find the search value after the index of a previously found value
searchSpaceLength = tempIndex;
if (index == 0)
break;
}
}
return index;
}
public static int LastIndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
T valueHead = value;
ref T valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength))
return relativeIndex; // The tail matched. Return a successful find.
index += remainingSearchSpaceLength - relativeIndex;
}
return -1;
}
public static int LastIndexOf<T>(ref T searchSpace, T value, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while (length >= 8)
{
length -= 8;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 7)))
goto Found7;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 6)))
goto Found6;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 5)))
goto Found5;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 4)))
goto Found4;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
if (length >= 4)
{
length -= 4;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 3)))
goto Found3;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 2)))
goto Found2;
if (value.Equals(Unsafe.Add(ref searchSpace, length + 1)))
goto Found1;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
while (length > 0)
{
length--;
if (value.Equals(Unsafe.Add(ref searchSpace, length)))
goto Found;
}
}
else
{
for (length--; length >= 0; length--)
{
if ((object)Unsafe.Add(ref searchSpace, length) is null)
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while (length >= 8)
{
length -= 8;
lookUp = Unsafe.Add(ref searchSpace, length + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, length + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, length + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, length + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
if (length >= 4)
{
length -= 4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
while (length > 0)
{
length--;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp))
goto Found;
}
}
else
{
for (length--; length >= 0; length--)
{
lookUp = Unsafe.Add(ref searchSpace, length);
if ((object?)lookUp is null)
{
if ((object?)value0 is null || (object?)value1 is null)
{
goto Found;
}
}
else if (lookUp.Equals(value0) || lookUp.Equals(value1))
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
T lookUp;
if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757
{
while (length >= 8)
{
length -= 8;
lookUp = Unsafe.Add(ref searchSpace, length + 7);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, length + 6);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, length + 5);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, length + 4);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
if (length >= 4)
{
length -= 4;
lookUp = Unsafe.Add(ref searchSpace, length + 3);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, length + 2);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, length + 1);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
while (length > 0)
{
length--;
lookUp = Unsafe.Add(ref searchSpace, length);
if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp))
goto Found;
}
}
else
{
for (length--; length >= 0; length--)
{
lookUp = Unsafe.Add(ref searchSpace, length);
if ((object?)lookUp is null)
{
if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null)
{
goto Found;
}
}
else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2))
{
goto Found;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return length;
Found1:
return length + 1;
Found2:
return length + 2;
Found3:
return length + 3;
Found4:
return length + 4;
Found5:
return length + 5;
Found6:
return length + 6;
Found7:
return length + 7;
}
public static int LastIndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength)
where T : IEquatable<T>
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex > index)
index = tempIndex;
}
return index;
}
public static bool SequenceEqual<T>(ref T first, ref T second, int length)
where T : IEquatable<T>
{
Debug.Assert(length >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
T lookUp0;
T lookUp1;
while (length >= 8)
{
length -= 8;
lookUp0 = Unsafe.Add(ref first, index);
lookUp1 = Unsafe.Add(ref second, index);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 1);
lookUp1 = Unsafe.Add(ref second, index + 1);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 2);
lookUp1 = Unsafe.Add(ref second, index + 2);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 3);
lookUp1 = Unsafe.Add(ref second, index + 3);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 4);
lookUp1 = Unsafe.Add(ref second, index + 4);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 5);
lookUp1 = Unsafe.Add(ref second, index + 5);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 6);
lookUp1 = Unsafe.Add(ref second, index + 6);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 7);
lookUp1 = Unsafe.Add(ref second, index + 7);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
index += 8;
}
if (length >= 4)
{
length -= 4;
lookUp0 = Unsafe.Add(ref first, index);
lookUp1 = Unsafe.Add(ref second, index);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 1);
lookUp1 = Unsafe.Add(ref second, index + 1);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 2);
lookUp1 = Unsafe.Add(ref second, index + 2);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
lookUp0 = Unsafe.Add(ref first, index + 3);
lookUp1 = Unsafe.Add(ref second, index + 3);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
index += 4;
}
while (length > 0)
{
lookUp0 = Unsafe.Add(ref first, index);
lookUp1 = Unsafe.Add(ref second, index);
if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null))
goto NotEqual;
index += 1;
length--;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
public static int SequenceCompareTo<T>(ref T first, int firstLength, ref T second, int secondLength)
where T : IComparable<T>
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
var minLength = firstLength;
if (minLength > secondLength)
minLength = secondLength;
for (int i = 0; i < minLength; i++)
{
T lookUp = Unsafe.Add(ref second, i);
int result = (Unsafe.Add(ref first, i)?.CompareTo(lookUp) ?? (((object?)lookUp is null) ? 0 : -1));
if (result != 0)
return result;
}
return firstLength.CompareTo(secondLength);
}
}
}
| 40.212389 | 180 | 0.455573 | [
"MIT"
] | AfsanehR-zz/corefx | src/Common/src/CoreLib/System/SpanHelpers.T.cs | 36,352 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.KeyManagementService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KeyManagementService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InvalidArnException Object
/// </summary>
public class InvalidArnExceptionUnmarshaller : IErrorResponseUnmarshaller<InvalidArnException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public InvalidArnException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public InvalidArnException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
InvalidArnException unmarshalledObject = new InvalidArnException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static InvalidArnExceptionUnmarshaller _instance = new InvalidArnExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InvalidArnExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.435294 | 130 | 0.648406 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/KeyManagementService/Generated/Model/Internal/MarshallTransformations/InvalidArnExceptionUnmarshaller.cs | 3,012 | C# |
using System;
using State.Fody;
public class Default
{
bool _isSyncing;
public bool IsLoading { get; set; }
[AddState("_isSyncing")]
public void TestField()
{
Console.WriteLine("TestField");
}
[AddState("IsLoading")]
public void TestProperty()
{
Console.WriteLine("TestProperty");
}
[AddState("IsTesting")]
public void TestNewProperty()
{
Console.WriteLine("TestNewProperty");
}
[AddState("IsTesting")]
public void TestMultiple()
{
TestField();
TestProperty();
TestNewProperty();
}
} | 17.428571 | 45 | 0.588525 | [
"MIT"
] | msioen/State.Fody | State.Fody.Tests/ValidAssemblyFiles/Default.cs | 612 | C# |
namespace ClassLib054
{
public class Class026
{
public static string Property => "ClassLib054";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib054/Class026.cs | 120 | C# |
using Ordering.Domain.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Ordering.Application.Contracts.Persistence
{
public interface IAsyncRepository<T> where T : EntityBase
{
Task<IReadOnlyList<T>> GetAllAsync();
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate);
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeString = null,
bool disableTracking = true);
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
List<Expression<Func<T, object>>> includes = null,
bool disableTracking = true);
Task<T> GetByIdAsync(int id);
Task<T> AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(T entity);
}
} | 32.676471 | 83 | 0.635464 | [
"MIT"
] | CodeWithKashif/AspNetMicroservices | src/Services/Ordering/Ordering.Application/Contracts/Persistence/IAsyncRepository.cs | 1,113 | C# |
using Microsoft.AspNetCore.Identity;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Zero.Configuration;
using MRPanel.Authorization.Roles;
using MRPanel.Authorization.Users;
using MRPanel.MultiTenancy;
namespace MRPanel.Authorization
{
public class LogInManager : AbpLogInManager<Tenant, Role, User>
{
public LogInManager(
UserManager userManager,
IMultiTenancyConfig multiTenancyConfig,
IRepository<Tenant> tenantRepository,
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager,
IRepository<UserLoginAttempt, long> userLoginAttemptRepository,
IUserManagementConfig userManagementConfig,
IIocResolver iocResolver,
IPasswordHasher<User> passwordHasher,
RoleManager roleManager,
UserClaimsPrincipalFactory claimsPrincipalFactory)
: base(
userManager,
multiTenancyConfig,
tenantRepository,
unitOfWorkManager,
settingManager,
userLoginAttemptRepository,
userManagementConfig,
iocResolver,
passwordHasher,
roleManager,
claimsPrincipalFactory)
{
}
}
}
| 32.782609 | 76 | 0.637268 | [
"MIT"
] | iPazooki/MRPanel | aspnet-core/src/MRPanel.Core/Authorization/LoginManager.cs | 1,510 | C# |
using BotSharp.Algorithm.HiddenMarkovModel.Helpers;
using BotSharp.Algorithm.HiddenMarkovModel.MathHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BotSharp.Algorithm.HiddenMarkovModel.Learning.Unsupervised
{
public partial class BaumWelchLearning : IUnsupervisedLearning
{
protected double[] mLogWeights;
protected double[][,] mLogGamma;
protected double[][][,] mLogKsi;
protected HiddenMarkovModel mModel;
protected double mTolerance = 0.0001;
protected int mIterations = 0;
public HiddenMarkovModel Model
{
get { return mModel; }
set { mModel = value; }
}
public double Tolerance
{
get { return mTolerance; }
set { mTolerance = value; }
}
public int Iterations
{
get { return mIterations; }
set { mIterations = value; }
}
public BaumWelchLearning(HiddenMarkovModel hmm)
{
mModel = hmm;
}
public double Run(int[][] observations_db)
{
return Run(observations_db, null);
}
public double Run(int[][] observations_db, double[] weights)
{
ValidationHelper.ValidateObservationDb(observations_db, 0, mModel.SymbolCount);
int K = observations_db.Length;
mLogWeights = new double[K];
if (weights != null)
{
for (int k = 0; k < K; ++k)
{
mLogWeights[k] = System.Math.Log(weights[k]);
}
}
int N = mModel.StateCount;
double lnK = System.Math.Log(K);
double[,] logA = mModel.LogTransitionMatrix;
double[,] logB = mModel.LogEmissionMatrix;
double[] logPi = mModel.LogProbabilityVector;
int M = mModel.SymbolCount;
mLogGamma = new double[K][,];
mLogKsi = new double[K][][,];
for (int k = 0; k < K; ++k)
{
int T = observations_db[k].Length;
mLogGamma[k] = new double[T, N];
mLogKsi[k] = new double[T][,];
for (int t = 0; t < T; ++t)
{
mLogKsi[k][t] = new double[N, N];
}
}
int maxT = observations_db.Max(x => x.Length);
double[,] lnfwd = new double[maxT, N];
double[,] lnbwd = new double[maxT, N];
// Initialize the model log-likelihoods
double newLogLikelihood = Double.NegativeInfinity;
double oldLogLikelihood = Double.NegativeInfinity;
int iteration = 0;
double deltaLogLikelihood = 0;
bool should_continue = true;
do // Until convergence or max iterations is reached
{
oldLogLikelihood = newLogLikelihood;
for (int k = 0; k < K; ++k)
{
int[] observations = observations_db[k];
double[,] logGamma = mLogGamma[k];
double[][,] logKsi = mLogKsi[k];
double w = mLogWeights[k];
int T = observations.Length;
ForwardBackwardAlgorithm.LogForward(logA, logB, logPi, observations, lnfwd);
ForwardBackwardAlgorithm.LogBackward(logA, logB, logPi, observations, lnbwd);
// Compute Gamma values
for (int t = 0; t < T; ++t)
{
double lnsum = double.NegativeInfinity;
for (int i = 0; i < N; ++i)
{
logGamma[t, i] = lnfwd[t, i] + lnbwd[t, i] + w;
lnsum = LogHelper.LogSum(lnsum, logGamma[t, i]);
}
if (lnsum != Double.NegativeInfinity)
{
for (int i = 0; i < N; ++i)
{
logGamma[t, i] = logGamma[t, i] - lnsum;
}
}
}
// Compute Ksi values
for (int t = 0; t < T-1; ++t)
{
double lnsum = double.NegativeInfinity;
int x = observations[t + 1];
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
logKsi[t][i, j] = lnfwd[t, i] + logA[i, j] + lnbwd[t + 1, j] + logB[j, x] + w;
lnsum = LogHelper.LogSum(lnsum, logKsi[t][i, j]);
}
}
for(int i=0; i < N; ++i)
{
for(int j=0; j < N; ++j)
{
logKsi[t][i, j]=logKsi[t][i, j]-lnsum;
}
}
}
newLogLikelihood = Double.NegativeInfinity;
for (int i = 0; i < N; ++i)
{
newLogLikelihood = LogHelper.LogSum(newLogLikelihood, lnfwd[T - 1, i]);
}
}
newLogLikelihood /= K;
deltaLogLikelihood = newLogLikelihood - oldLogLikelihood;
iteration++;
//Console.WriteLine("Iteration: {0}", iteration);
if (ShouldTerminate(deltaLogLikelihood, iteration))
{
should_continue = false;
}
else
{
// update pi
for (int i = 0; i < N; ++i)
{
double lnsum = double.NegativeInfinity;
for (int k = 0; k < K; ++k)
{
lnsum = LogHelper.LogSum(lnsum, mLogGamma[k][0, i]);
}
logPi[i] = lnsum - lnK;
}
// update A
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
double lndenom = double.NegativeInfinity;
double lnnum = double.NegativeInfinity;
for (int k = 0; k < K; ++k)
{
int T = observations_db[k].Length;
for (int t = 0; t < T - 1; ++t)
{
lnnum = LogHelper.LogSum(lnnum, mLogKsi[k][t][i, j]);
lndenom = LogHelper.LogSum(lndenom, mLogGamma[k][t, i]);
}
}
logA[i, j] = (lnnum == lndenom) ? 0 : lnnum - lndenom;
}
}
// update B
for (int i = 0; i < N; ++i)
{
for (int m = 0; m < M; ++m)
{
double lndenom = double.NegativeInfinity;
double lnnum = double.NegativeInfinity;
for (int k = 0; k < K; ++k)
{
int[] observations=observations_db[k];
int T=observations.Length;
for (int t = 0; t < T; ++t)
{
lndenom = LogHelper.LogSum(lndenom, mLogGamma[k][t, i]);
if (observations[t] == m)
{
lnnum = LogHelper.LogSum(lnnum, mLogGamma[k][t, i]);
}
}
}
logB[i, m] = lnnum-lndenom;
}
}
}
} while (should_continue);
return newLogLikelihood;
}
protected bool ShouldTerminate(double change, int iteration)
{
if (change <= mTolerance)
{
return true;
}
if (mIterations > 0 && mIterations <= iteration)
{
return true;
}
return false;
}
}
}
| 34.098859 | 110 | 0.377007 | [
"Apache-2.0"
] | david0718/BotSharp | BotSharp.Algorithm/HiddenMarkovModel/Learning/Unsupervised/BaumWelchLearning.cs | 8,970 | C# |
#if !UNITY_ZEROPLAYER
using NUnit.Framework;
using Unity.Jobs;
namespace Unity.Entities.Tests
{
class IJobProcessComponentInjection : ECSTestsFixture
{
[DisableAutoCreation]
class TestSystem : JobComponentSystem
{
private struct Process1 : IJobForEach<EcsTestData>
{
public void Execute(ref EcsTestData value)
{
value.value = 7;
}
}
public struct Process2 : IJobForEach<EcsTestData, EcsTestData2>
{
public void Execute(ref EcsTestData src, ref EcsTestData2 dst)
{
dst.value1 = src.value;
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
inputDeps = new Process1().Schedule(this, inputDeps);
inputDeps = new Process2().Schedule(this, inputDeps);
return inputDeps;
}
}
[Test]
public void NestedIJobForEachAreInjectedDuringOnCreate()
{
m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2));
var system = World.GetOrCreateSystem<TestSystem>();
Assert.AreEqual(2, system.EntityQueries.Length);
}
}
}
#endif
| 29.282609 | 78 | 0.548627 | [
"MIT"
] | ToadsworthLP/Millenium | Library/PackageCache/[email protected]/Unity.Entities.Tests/IJobProcessComponentInjection.cs | 1,349 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.RepresentationModel;
namespace VSKubernetes
{
class Kubernetes
{
public static Process RunPowerShellProcess(string path, string workingDirectory, bool wait = false, DataReceivedEventHandler onOutput = null, DataReceivedEventHandler onError = null, EventHandler onExit = null)
{
return Utils.RunProcess("powershell.exe", string.Format("-NonInteractive -NoLogo -ExecutionPolicy RemoteSigned -File \"{0}\"", path),
workingDirectory, wait, onOutput, onError, onExit);
}
public static void DeployMinikube(DataReceivedEventHandler onOutput = null, DataReceivedEventHandler onError = null, EventHandler onExit = null)
{
var baseDir = Utils.GetBinariesDir();
var ps1Path = System.IO.Path.Combine(baseDir, "DeployMinikube.ps1");
RunPowerShellProcess(ps1Path, baseDir, false, onOutput, onError, onExit);
}
public static Process DraftConnect(string projectDir, IList<KeyValuePair<int, int>> portMappings = null, DataReceivedEventHandler onOutput = null, DataReceivedEventHandler onError = null, EventHandler onExit = null)
{
var overridePort = "";
if (portMappings != null && portMappings.Count > 0)
{
foreach (var portMapping in portMappings)
{
if (overridePort.Length > 0)
overridePort += ",";
overridePort += portMapping.Key + ":" + portMapping.Value;
}
overridePort = " --override-port " + overridePort;
}
var draftPath = System.IO.Path.Combine(Utils.GetBinariesDir(), "draft.exe");
return Utils.RunProcess(draftPath, "connect" + overridePort, projectDir, false, onOutput, onError, onExit);
}
public static void DraftUp(string projectDir, bool minikubeDockerEnv=false, DataReceivedEventHandler onOutput = null, DataReceivedEventHandler onError = null, EventHandler onExit = null)
{
if (minikubeDockerEnv)
{
var draftPs1Path = System.IO.Path.Combine(Utils.GetBinariesDir(), "draftUp.ps1");
RunPowerShellProcess(draftPs1Path, projectDir, false, onOutput, onError, onExit);
}
else
{
var draftPath = System.IO.Path.Combine(Utils.GetBinariesDir(), "draft.exe");
Utils.RunProcess(draftPath, "up .", projectDir, false, onOutput, onError, onExit);
}
}
public static void DraftCreate(string projectDir, string packName, string appName, DataReceivedEventHandler onOutput = null, DataReceivedEventHandler onError = null, EventHandler onExit = null)
{
var draftPath = System.IO.Path.Combine(Utils.GetBinariesDir(), "draft.exe");
Utils.RunProcess(draftPath, String.Format("create . --pack {0} --app {1}", packName, appName), projectDir, false, onOutput, onError, onExit);
}
public static void DisableDraftWatch(string projectDir)
{
var draftTomlFileName = "draft.toml";
var path = System.IO.Path.Combine(projectDir, draftTomlFileName);
string text = System.IO.File.ReadAllText(path, System.Text.Encoding.ASCII);
text = text.Replace("watch = true", "watch = false");
System.IO.File.WriteAllText(path, text, System.Text.Encoding.ASCII);
}
static string GetK8sConfigPath()
{
var home = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile);
return System.IO.Path.Combine(home, @".kube\config");
}
static YamlStream LoadKubeConfig()
{
var k8sConfigPath = GetK8sConfigPath();
if (!System.IO.File.Exists(k8sConfigPath))
return null;
using (var r = System.IO.File.OpenText(k8sConfigPath))
{
var yaml = new YamlStream();
yaml.Load(r);
return yaml;
}
}
public static string GetCurrentContext()
{
var yaml = LoadKubeConfig();
if (yaml == null)
return null;
var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
return ((YamlScalarNode)mapping["current-context"]).Value;
}
public static void SetCurrentContext(string context)
{
var kubectlPath = System.IO.Path.Combine(Utils.GetBinariesDir(), "kubectl.exe");
var p = Utils.RunProcess(kubectlPath, "config use-context \"" + context + "\"", "", true);
if (p.ExitCode != 0)
{
throw new Exception("kubectl set-context failed");
}
}
public static string[] GetContextNames()
{
IList<string> l = new List<string>();
var yaml = LoadKubeConfig();
if (yaml != null)
{
var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
var contexts = (YamlSequenceNode)mapping.Children[new YamlScalarNode("contexts")];
foreach (YamlMappingNode context in contexts)
{
l.Add(context["name"].ToString());
}
}
return l.ToArray();
}
}
}
| 41.954887 | 223 | 0.595341 | [
"Apache-2.0"
] | cloudbase/VSKubernetes | VSKubernetes/Kubernetes.cs | 5,582 | C# |
// FILE AUTOGENERATED. DO NOT MODIFY
namespace Starfield.Core.Item.Items {
[Item("minecraft:dark_oak_trapdoor", 231, 64, 227)]
public class ItemDarkOakTrapdoor : BlockItem { }
} | 31.833333 | 56 | 0.712042 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Item/Items/ItemDarkOakTrapdoor.cs | 191 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("EntityFramework.Functions.Tests.Library")]
[assembly: Guid("27afffb0-bc81-40ea-9d93-55523e1aff06")]
| 31.833333 | 68 | 0.811518 | [
"MIT"
] | ChristosMylonas/EntityFramework.Functions | EntityFramework.Functions.Tests.Library/Properties/AssemblyInfo.cs | 193 | C# |
using System;
namespace Sexy
{
public abstract class SoundManager
{
public abstract void Release();
public abstract void Enable(bool enable);
public abstract bool Initialized();
public abstract bool LoadSound(uint theSfxID, string theFilename);
public abstract int LoadSound(string theFilename);
public abstract void ReleaseSound(uint theSfxID);
public abstract void SetVolume(double theVolume);
public abstract bool SetBaseVolume(uint theSfxID, double theBaseVolume);
public abstract bool SetBasePan(uint theSfxID, int theBasePan);
public abstract SoundInstance GetSoundInstance(uint theSfxID);
public abstract void ReleaseSounds();
public abstract void ReleaseChannels();
public abstract double GetMasterVolume();
public abstract void SetMasterVolume(double theVolume);
public abstract void Flush();
public abstract void StopAllSounds();
public abstract int GetFreeSoundId();
public abstract int GetNumSounds();
public abstract void Update();
}
}
| 16.19697 | 74 | 0.730589 | [
"MIT"
] | OptiJuegos/Plants-VS-Zombies-NET | DotNETPvZ_Shared/Sexy/SoundManager.cs | 1,071 | C# |
namespace Sports.Models
{
public class Sport
{
public string Name { get; set; }
public uint FieldPlayers { get; set; }
public bool Goalie { get; set; }
public string Origin { get; set; }
public string Description { get; set; }
}
}
| 21.5 | 43 | 0.627907 | [
"MIT"
] | atkins126/I18N | Samples/ASP.NET/Framework/MVC/SportsOld/Models/Sport.cs | 260 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Web.Data.Entities
{
public class Product : IEntity
{
[Key]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Price { get; set; }
[Display(Name = "Image")]
public string ImgeUrl { get; set; }
[Display(Name = "Last Purchase")]
public DateTime? LastPurchase { get; set; }
[Display(Name = "Last Sale")]
public DateTime? LastSale { get; set; }
[Display(Name = "Is Avalible")]
public bool IsAvalible { get; set; }
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = false)]
public double Stock { get; set; }
public User User { get; set; }
}
}
| 24 | 83 | 0.602183 | [
"MIT"
] | EsauMtzxD/Shop | Shop/Shop.Web/Data/Entities/Product.cs | 1,010 | C# |
/* http://www.zkea.net/ Copyright 2016 ZKEASOFT http://www.zkea.net/licenses */
using System;
using System.Collections.Generic;
using Easy.IOC;
using Easy.Modules.Role;
namespace Easy.Models
{
public interface IUser : IEntity
{
string UserID { get; set; }
string NickName { get; set; }
string PassWord { get; set; }
long Timestamp { get; set; }
string LoginIP { get; set; }
string PhotoUrl { get; set; }
int? UserTypeCD { get; set; }
DateTime LastLoginDate { get; set; }
string UserName { get; set; }
string ApiLoginToken { get; set; }
string LastName { get; set; }
string FirstName { get; set; }
string EnglishName { get; set; }
int? Age { get; }
DateTime? Birthday { get; set; }
int? Sex { get; set; }
string Birthplace { get; set; }
string Address { get; set; }
string ZipCode { get; set; }
string School { get; set; }
string Telephone { get; set; }
string MobilePhone { get; set; }
string Profession { get; set; }
int? MaritalStatus { get; set; }
string Hobby { get; set; }
string QQ { get; set; }
string Email { get; set; }
IEnumerable<UserRoleRelation> Roles { get; set; }
}
}
| 32.195122 | 79 | 0.561364 | [
"Apache-2.0"
] | xcz1997/EasyFrameWork | EasyFrameWork/Models/IUser.cs | 1,320 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace AMSApp.Storage {
public partial class wfmPrintReceiveSend {
/// <summary>
/// Form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm Form1;
/// <summary>
/// Label1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label1;
/// <summary>
/// txtSendSerial 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSendSerial;
/// <summary>
/// btnQuery 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnQuery;
/// <summary>
/// btnPrint 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnPrint;
/// <summary>
/// btnCancel 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancel;
/// <summary>
/// DataGrid1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.DataGrid DataGrid1;
}
}
| 27.177215 | 81 | 0.453656 | [
"Apache-2.0"
] | zhenghua75/AMSCenter | AMSApp/Storage/wfmPrintReceiveSend.aspx.designer.cs | 2,807 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RevloLib.Models.Rewards
{
public class Reward
{
[JsonProperty(PropertyName = "reward_id")]
public int RewardId { get; protected set; }
[JsonProperty(PropertyName = "created_at")]
public DateTime CreatedAt { get; protected set; }
[JsonProperty(PropertyName = "title")]
public string Title { get; protected set; }
[JsonProperty(PropertyName = "bot_command")]
public string BotCommand { get; protected set; }
[JsonProperty(PropertyName = "enabled")]
public bool Enabled { get; protected set; }
[JsonProperty(PropertyName = "points")]
public int Points { get; protected set; }
[JsonProperty(PropertyName = "sub_only")]
public bool SubOnly { get; protected set; }
//TODO: account for input_fields
}
}
| 33.758621 | 57 | 0.657814 | [
"MIT"
] | swiftyspiffy/RevloLib | RevloLib/Models/Rewards/Reward.cs | 981 | C# |
#region Copyright Simple Injector Contributors
/* The Simple Injector is an easy-to-use Inversion of Control library for .NET
*
* Copyright (c) 2013 Simple Injector Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
namespace SimpleInjector.Diagnostics.Debugger
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using SimpleInjector.Diagnostics.Analyzers;
internal sealed class ContainerDebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Container container;
public ContainerDebugView(Container container)
{
this.container = container;
this.Initialize();
}
public ContainerOptions Options => this.container.Options;
[DebuggerDisplay("")]
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public DebuggerViewItem[] Items { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = @"
We must catch all exceptions here, because this constructor is called by the Visual Studio
debugger and it won't hide any failure in case of an exception. We catch and show the
exception in the debug view instead.")]
private void Initialize()
{
if (!this.container.SuccesfullyVerified)
{
this.Items = new[]
{
new DebuggerViewItem(
name: "How To View Diagnostic Info",
description: "Analysis info is available in this debug view after Verify() is " +
"called on this container instance.")
};
return;
}
try
{
this.Items = this.GetAnalysisResults().ToArray();
}
catch (Exception ex)
{
this.Items = GetDebuggerTypeProxyFailureResults(ex);
}
}
private DebuggerViewItem[] GetAnalysisResults()
{
var registrations = this.container.GetCurrentRegistrations();
var rootRegistrations = this.container.GetRootRegistrations();
return new DebuggerViewItem[]
{
DebuggerGeneralWarningsContainerAnalyzer.Analyze(this.container),
new DebuggerViewItem(
name: "Registrations",
description: "Count = " + registrations.Length,
value: registrations),
new DebuggerViewItem(
name: "Root Registrations",
description: "Count = " + rootRegistrations.Length,
value: this.GroupProducers(rootRegistrations))
};
}
private static DebuggerViewItem[] GetDebuggerTypeProxyFailureResults(Exception exception)
{
return new[]
{
new DebuggerViewItem(
"Failure",
"We're so so sorry. The Debugger Type Proxy failed to initialize.",
exception)
};
}
private object[] GroupProducers(IEnumerable<InstanceProducer> producers) =>
this.GroupProducers(producers, level: 0);
private object[] GroupProducers(IEnumerable<InstanceProducer> producers, int level) => (
from producer in producers
group producer by TypeGeneralizer.MakeTypePartiallyGenericUpToLevel(producer.ServiceType, level)
into resultGroup
select this.BuildProducerGroup(resultGroup.Key, resultGroup.ToArray(), level + 1))
.ToArray();
private object BuildProducerGroup(Type groupType,
InstanceProducer[] producersForGroup, int level)
{
if (producersForGroup.Length == 1)
{
var producer = producersForGroup[0];
// This flattens the hierarchy when there is just one item in the group.
return new DebuggerViewItem(
name: producer.ServiceType.ToFriendlyName(),
description: producer.DebuggerDisplay,
value: producersForGroup[0]);
}
if (groupType.ContainsGenericParameters())
{
return this.BuildGenericGroup(groupType, producersForGroup, level);
}
else
{
return BuildNonGenericGroup(groupType, producersForGroup);
}
}
private object BuildGenericGroup(Type groupType,
InstanceProducer[] producersForGroup, int level)
{
object[] childGroups = this.GroupProducers(producersForGroup, level);
if (childGroups.Length == 1)
{
// This flattens the hierarchy when there is just one item in the group.
return childGroups[0];
}
return new DebuggerViewItem(
name: groupType.ToFriendlyName(),
description: "Count = " + producersForGroup.Length,
value: childGroups);
}
private static DebuggerViewItem BuildNonGenericGroup(Type closedType, InstanceProducer[] producersForGroup) =>
new DebuggerViewItem(
name: closedType.ToFriendlyName(),
description: "Count = " + producersForGroup.Length,
value: producersForGroup.ToArray());
}
} | 40.899408 | 120 | 0.592737 | [
"MIT"
] | theunrepentantgeek/SimpleInjector | src/SimpleInjector/Diagnostics/Debugger/ContainerDebugView.cs | 6,746 | 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 UI.Info
{
public partial class Form_Results : Form
{
public Form_Results()
{
InitializeComponent();
}
private void BtnOk_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void Form_Results_Load(object sender, EventArgs e)
{
TbxResultMessage.Clear();
// populate textbox with results
foreach (string st in UI.Form_Main.createdWorksets)
{
TbxResultMessage.AppendText(st + Environment.NewLine);
}
}
}
}
| 23.578947 | 70 | 0.583705 | [
"MIT"
] | angelrps/ARP_Toolkit | 2020/TransferWorksets/VS_TransferWorksets/UI/Form_Results.cs | 898 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using Microsoft.MixedReality.WebRTC;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace TestAppUwp
{
/// <summary>
/// Page for general application settings.
/// </summary>
public sealed partial class SettingsPage : Page
{
public SessionModel SessionModel
{
get { return SessionModel.Current; }
}
/// <summary>
/// Get the string representing the preferred audio codec the user selected.
/// </summary>
// TODO - Use per-transceiver properties instead of per-connection ones
public string PreferredAudioCodec
{
get
{
if (PreferredAudioCodec_Custom.IsChecked.GetValueOrDefault(false))
{
return CustomPreferredAudioCodec.Text;
}
else if (PreferredAudioCodec_OPUS.IsChecked.GetValueOrDefault(false))
{
return "opus";
}
return string.Empty;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
PreferredAudioCodec_Default.IsChecked = true;
}
else if (value == "opus")
{
PreferredAudioCodec_OPUS.IsChecked = true;
}
else
{
PreferredAudioCodec_Custom.IsChecked = true;
CustomPreferredAudioCodec.Text = value;
}
}
}
/// <summary>
/// Get the string representing the preferred video codec the user selected.
/// </summary>
// TODO - Use per-transceiver properties instead of per-connection ones
public string PreferredVideoCodec
{
get
{
if (PreferredVideoCodec_Custom.IsChecked.GetValueOrDefault(false))
{
return CustomPreferredVideoCodec.Text;
}
else if (PreferredVideoCodec_H264.IsChecked.GetValueOrDefault(false))
{
return "H264";
}
else if (PreferredVideoCodec_VP8.IsChecked.GetValueOrDefault(false))
{
return "VP8";
}
return string.Empty;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
PreferredVideoCodec_Default.IsChecked = true;
}
else if (value == "H264")
{
PreferredVideoCodec_H264.IsChecked = true;
}
else if (value == "VP8")
{
PreferredVideoCodec_VP8.IsChecked = true;
}
else
{
PreferredVideoCodec_Custom.IsChecked = true;
CustomPreferredVideoCodec.Text = value;
}
}
}
public SettingsPage()
{
this.InitializeComponent();
// Restore
var sessionModel = SessionModel.Current;
PreferredAudioCodec = sessionModel.PreferredAudioCodec;
PreferredVideoCodec = sessionModel.PreferredVideoCodec;
}
private void SdpSemanticChanged(object sender, RoutedEventArgs e)
{
if (sender == sdpSemanticUnifiedPlan)
{
SessionModel.Current.SdpSemantic = SdpSemantic.UnifiedPlan;
}
else if (sender == sdpSemanticPlanB)
{
SessionModel.Current.SdpSemantic = SdpSemantic.PlanB;
}
}
private void StunServerTextChanged(object sender, TextChangedEventArgs e)
{
SessionModel.Current.IceServer = new IceServer
{
Urls = new List<string> { "stun:" + stunServer.Text }
};
}
// TODO - Use MVVM
// TODO - Use per-transceiver properties instead of per-connection ones
private void PreferredAudioCodecChecked(object sender, RoutedEventArgs args)
{
// Ignore calls during startup, before components are initialized
if (PreferredAudioCodec_Custom == null)
{
return;
}
if (PreferredAudioCodec_Custom.IsChecked.GetValueOrDefault(false))
{
CustomPreferredAudioCodecHelpText.Visibility = Visibility.Visible;
CustomPreferredAudioCodec.Visibility = Visibility.Visible;
}
else
{
CustomPreferredAudioCodecHelpText.Visibility = Visibility.Collapsed;
CustomPreferredAudioCodec.Visibility = Visibility.Collapsed;
}
SessionModel.Current.PreferredAudioCodec = PreferredAudioCodec;
}
// TODO - Use MVVM
// TODO - Use per-transceiver properties instead of per-connection ones
private void PreferredVideoCodecChecked(object sender, RoutedEventArgs args)
{
// Ignore calls during startup, before components are initialized
if (PreferredVideoCodec_Custom == null)
{
return;
}
if (PreferredVideoCodec_Custom.IsChecked.GetValueOrDefault(false))
{
CustomPreferredVideoCodecHelpText.Visibility = Visibility.Visible;
CustomPreferredVideoCodec.Visibility = Visibility.Visible;
}
else
{
CustomPreferredVideoCodecHelpText.Visibility = Visibility.Collapsed;
CustomPreferredVideoCodec.Visibility = Visibility.Collapsed;
}
SessionModel.Current.PreferredVideoCodec = PreferredVideoCodec;
}
}
}
| 33.638889 | 85 | 0.533939 | [
"MIT"
] | AltspaceVR/MixedReality-WebRTC | examples/TestAppUwp/SettingsPage.xaml.cs | 6,055 | C# |
using System.Collections.Generic;
using System;
using FFImageLoading.Config;
using FFImageLoading.Work;
using System.Net.Http;
using FFImageLoading.Helpers;
using FFImageLoading.Cache;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
#if SILVERLIGHT
using FFImageLoading.Concurrency;
#else
using System.Collections.Concurrent;
#endif
namespace FFImageLoading
{
public class ImageService: IImageService
{
private volatile bool _initialized;
private object _initializeLock = new object();
private readonly MD5Helper _md5Helper = new MD5Helper();
private Configuration _config;
private static Lazy<ImageService> LazyInstance = new Lazy<ImageService>(() => new ImageService());
public static IImageService Instance { get { return LazyInstance.Value; } }
private ImageService() { }
/// <summary>
/// Gets FFImageLoading configuration
/// </summary>
/// <value>The configuration used by FFImageLoading.</value>
public Configuration Config
{
get
{
InitializeIfNeeded();
return _config;
}
set
{
_config = value;
}
}
/// <summary>
/// Initializes FFImageLoading with a default Configuration.
/// Also forces to run disk cache cleaning routines (avoiding delay for first image loading tasks)
/// </summary>
/// <param name="configuration">Configuration.</param>
public void Initialize()
{
lock (_initializeLock)
{
_initialized = false;
InitializeIfNeeded();
}
}
/// <summary>
/// Initializes FFImageLoading with a given Configuration. It allows to configure and override most of it.
/// Also forces to run disk cache cleaning routines (avoiding delay for first image loading tasks)
/// </summary>
/// <param name="configuration">Configuration.</param>
public void Initialize(Configuration configuration)
{
lock (_initializeLock)
{
_initialized = false;
if (_config != null)
{
// If DownloadCache is not updated but HttpClient is then we inform DownloadCache
if (configuration.HttpClient != null && configuration.DownloadCache == null)
{
configuration.DownloadCache = _config.DownloadCache;
configuration.DownloadCache.DownloadHttpClient = configuration.HttpClient;
}
// Redefine these if they were provided only
configuration.HttpClient = configuration.HttpClient ?? _config.HttpClient;
configuration.Scheduler = configuration.Scheduler ?? _config.Scheduler;
configuration.Logger = configuration.Logger ?? _config.Logger;
configuration.DownloadCache = configuration.DownloadCache ?? _config.DownloadCache;
// Skip configuration for maxMemoryCacheSize and diskCache. They cannot be redefined.
if (configuration.Logger != null)
configuration.Logger.Debug("Skip configuration for maxMemoryCacheSize and diskCache. They cannot be redefined.");
configuration.MaxMemoryCacheSize = _config.MaxMemoryCacheSize;
configuration.DiskCache = _config.DiskCache;
}
InitializeIfNeeded(configuration);
}
}
private void InitializeIfNeeded(Configuration userDefinedConfig = null)
{
if (_initialized)
return;
lock (_initializeLock)
{
if (_initialized)
return;
if (userDefinedConfig == null)
userDefinedConfig = new Configuration();
var httpClient = userDefinedConfig.HttpClient ?? new HttpClient();
if (userDefinedConfig.HttpReadTimeout > 0)
{
httpClient.Timeout = TimeSpan.FromSeconds(userDefinedConfig.HttpReadTimeout);
}
var logger = new MiniLoggerWrapper(userDefinedConfig.Logger ?? new MiniLogger(), userDefinedConfig.VerboseLogging);
var scheduler = userDefinedConfig.Scheduler ?? new WorkScheduler(logger, userDefinedConfig.VerbosePerformanceLogging, new PlatformPerformance(), userDefinedConfig.SchedulerMaxParallelTasks);
var diskCache = userDefinedConfig.DiskCache ?? SimpleDiskCache.CreateCache("FFSimpleDiskCache");
var downloadCache = userDefinedConfig.DownloadCache ?? new DownloadCache(httpClient, diskCache);
userDefinedConfig.HttpClient = httpClient;
userDefinedConfig.Scheduler = scheduler;
userDefinedConfig.Logger = logger;
userDefinedConfig.DiskCache = diskCache;
userDefinedConfig.DownloadCache = downloadCache;
Config = userDefinedConfig;
_initialized = true;
}
}
private IWorkScheduler Scheduler
{
get {
InitializeIfNeeded();
return Config.Scheduler;
}
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a file.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="filepath">Path to the file.</param>
public TaskParameter LoadFile(string filepath)
{
InitializeIfNeeded();
return TaskParameter.FromFile(filepath);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a URL.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="url">URL to the file</param>
/// <param name="cacheDuration">How long the file will be cached on disk</param>
public TaskParameter LoadUrl(string url, TimeSpan? cacheDuration = null)
{
InitializeIfNeeded();
return TaskParameter.FromUrl(url, cacheDuration);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a file from application bundle.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="filepath">Path to the file.</param>
public TaskParameter LoadFileFromApplicationBundle(string filepath)
{
InitializeIfNeeded();
return TaskParameter.FromApplicationBundle(filepath);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a compiled drawable resource.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="resourceName">Name of the resource in drawable folder without extension</param>
public TaskParameter LoadCompiledResource(string resourceName)
{
InitializeIfNeeded();
return TaskParameter.FromCompiledResource(resourceName);
}
/// <summary>
/// Constructs a new TaskParameter to load an image from a Stream.
/// </summary>
/// <returns>The new TaskParameter.</returns>
/// <param name="resourceName">A function that allows a CancellationToken and returns the Stream to use. This function will be invoked by LoadStream().</param>
public TaskParameter LoadStream(Func<CancellationToken, Task<Stream>> stream)
{
InitializeIfNeeded();
return TaskParameter.FromStream(stream);
}
/// <summary>
/// Gets a value indicating whether ImageService will exit tasks earlier
/// </summary>
/// <value><c>true</c> if it should exit tasks early; otherwise, <c>false</c>.</value>
public bool ExitTasksEarly
{
get
{
return Scheduler.ExitTasksEarly;
}
}
/// <summary>
/// Sets a value indicating whether ImageService will exit tasks earlier
/// </summary>
/// <param name="exitTasksEarly">If set to <c>true</c> exit tasks early.</param>
public void SetExitTasksEarly(bool exitTasksEarly)
{
Scheduler.SetExitTasksEarly(exitTasksEarly);
}
/// <summary>
/// Sets a value indicating if all loading work should be paused (silently canceled).
/// </summary>
/// <param name="pauseWork">If set to <c>true</c> pause/cancel work.</param>
public void SetPauseWork(bool pauseWork)
{
Scheduler.SetPauseWork(pauseWork);
}
/// <summary>
/// Cancel any loading work for the given ImageView
/// </summary>
/// <param name="task">Image loading task to cancel.</param>
public void CancelWorkFor(IImageLoaderTask task)
{
Scheduler.Cancel(task);
}
/// <summary>
/// Removes a pending image loading task from the work queue.
/// </summary>
/// <param name="task">Image loading task to remove.</param>
public void RemovePendingTask(IImageLoaderTask task)
{
Scheduler.RemovePendingTask(task);
}
/// <summary>
/// Queue an image loading task.
/// </summary>
/// <param name="task">Image loading task.</param>
public void LoadImage(IImageLoaderTask task)
{
if (task == null)
return;
if (task.Parameters.DelayInMs == null && Config.DelayInMs > 0)
task.Parameters.Delay(Config.DelayInMs);
Scheduler.LoadImage(task);
}
/// <summary>
/// Invalidates selected caches.
/// </summary>
/// <returns>An awaitable task.</returns>
/// <param name="cacheType">Memory cache, Disk cache or both</param>
public async Task InvalidateCacheAsync(CacheType cacheType)
{
InitializeIfNeeded();
if (cacheType == CacheType.All || cacheType == CacheType.Memory)
{
InvalidateMemoryCache();
}
if (cacheType == CacheType.All || cacheType == CacheType.Disk)
{
await InvalidateDiskCacheAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Invalidates the memory cache.
/// </summary>
public void InvalidateMemoryCache()
{
InitializeIfNeeded();
ImageCache.Instance.Clear();
}
/// <summary>
/// Invalidates the disk cache.
/// </summary>
public Task InvalidateDiskCacheAsync()
{
InitializeIfNeeded();
return Config.DiskCache.ClearAsync();
}
/// <summary>
/// Invalidates the cache for given key.
/// </summary>
/// <returns>The async.</returns>
/// <param name="key">Concerns images with this key.</param>
/// <param name="cacheType">Memory cache, Disk cache or both</param>
/// <param name="removeSimilar">If similar keys should be removed, ie: typically keys with extra transformations</param>
public async Task InvalidateCacheEntryAsync(string key, CacheType cacheType, bool removeSimilar=false)
{
InitializeIfNeeded();
if (cacheType == CacheType.All || cacheType == CacheType.Memory)
{
ImageCache.Instance.Remove(key);
if (removeSimilar)
{
ImageCache.Instance.RemoveSimilar(key);
}
}
if (cacheType == CacheType.All || cacheType == CacheType.Disk)
{
string hash = _md5Helper.MD5(key);
await Config.DiskCache.RemoveAsync(hash).ConfigureAwait(false);
}
}
/// <summary>
/// Cancels tasks that match predicate.
/// </summary>
/// <param name="predicate">Predicate for finding relevant tasks to cancel.</param>
public void Cancel(Func<IImageLoaderTask, bool> predicate)
{
Scheduler.Cancel(predicate);
}
/// <summary>
/// Cancels tasks that match predicate.
/// </summary>
/// <param name="predicate">Predicate for finding relevant tasks to cancel.</param>
public void Cancel(Func<TaskParameter, bool> predicate)
{
Scheduler.Cancel(task => task.Parameters != null && predicate(task.Parameters));
}
}
}
| 33.868946 | 207 | 0.629879 | [
"MIT"
] | klaaspolinder/FFImageLoading | source/FFImageLoading.Shared/ImageService.cs | 11,888 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.