content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime
{
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.Http;
using System.Linq;
using System.Net;
using Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.Json;
public enum MockMode
{
Live,
Record,
Playback,
}
public class PipelineMock
{
private System.Collections.Generic.Stack<string> scenario = new System.Collections.Generic.Stack<string>();
private System.Collections.Generic.Stack<string> context = new System.Collections.Generic.Stack<string>();
private System.Collections.Generic.Stack<string> description = new System.Collections.Generic.Stack<string>();
private readonly string recordingPath;
private int counter = 0;
public static implicit operator Microsoft.Azure.PowerShell.Cmdlets.CloudService.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync;
public MockMode Mode { get; set; } = MockMode.Live;
public PipelineMock(string recordingPath)
{
this.recordingPath = recordingPath;
}
public void PushContext(string text) => context.Push(text);
public void PushDescription(string text) => description.Push(text);
public void PushScenario(string it)
{
// reset counter too
counter = 0;
scenario.Push(it);
}
public void PopContext() => context.Pop();
public void PopDescription() => description.Pop();
public void PopScenario() => scenario.Pop();
public void SetRecord() => Mode = MockMode.Record;
public void SetPlayback() => Mode = MockMode.Playback;
public void SetLive() => Mode = MockMode.Live;
public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]");
public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]");
public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]");
/// <summary>
/// Headers that we substitute out blank values for in the recordings
/// Add additional headers as necessary
/// </summary>
public static HashSet<string> Blacklist = new HashSet<string>(System.StringComparer.CurrentCultureIgnoreCase) {
"Authorization",
};
public Dictionary<string, string> ForceResponseHeaders = new Dictionary<string, string>();
internal static XImmutableArray<string> Removed = new XImmutableArray<string>(new string[] { "[Filtered]" });
internal static IEnumerable<KeyValuePair<string, JsonNode>> FilterHeaders(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers) => headers.Select(header => new KeyValuePair<string, JsonNode>(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray<string>(header.Value.ToArray())));
internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result);
internal static JsonNode SerializeContent(byte[] content)
{
if (null == content || content.Length == 0)
{
return XNull.Instance;
}
var first = content[0];
var last = content[content.Length - 1];
// plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS
if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"'))
{
return new JsonString(System.Text.Encoding.UTF8.GetString(content));
}
// base64 for everyone else
return new JsonString(System.Convert.ToBase64String(content));
}
internal static byte[] DeserializeContent(string content)
{
if (string.IsNullOrWhiteSpace(content))
{
return new byte[0];
}
if (content.EndsWith("=="))
{
try
{
return System.Convert.FromBase64String(content);
}
catch
{
// hmm. didn't work, return it as a string I guess.
}
}
return System.Text.Encoding.UTF8.GetBytes(content);
}
public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response)
{
var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject();
messages[rqKey] = new JsonObject {
{ "Request",new JsonObject {
{ "Method", request.Method.Method },
{ "RequestUri", request.RequestUri },
{ "Content", SerializeContent( request.Content) },
{ "Headers", new JsonObject(FilterHeaders(request.Headers)) },
{ "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))}
} },
{"Response", new JsonObject {
{ "StatusCode", (int)response.StatusCode},
{ "Headers", new JsonObject(FilterHeaders(response.Headers))},
{ "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))},
{ "Content", SerializeContent(response.Content) },
}}
};
System.IO.File.WriteAllText(this.recordingPath, messages.ToString());
}
private JsonObject Load()
{
if (System.IO.File.Exists(this.recordingPath))
{
try
{
return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath));
}
catch
{
throw new System.Exception($"Invalid recording file: '{recordingPath}'");
}
}
throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath));
}
public HttpResponseMessage LoadMessage(string rqKey)
{
var responses = Load();
var message = responses.Property(rqKey);
if (null == message)
{
throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey));
}
var sc = 0;
var reqMessage = message.Property("Request");
var respMessage = message.Property("Response");
// --------------------------- deserialize response ----------------------------------------------------------------
var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc),
Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content")))
};
foreach (var each in respMessage.Property("Headers"))
{
response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf<string>());
}
foreach (var frh in ForceResponseHeaders)
{
response.Headers.Remove(frh.Key);
response.Headers.TryAddWithoutValidation(frh.Key, frh.Value);
}
foreach (var each in respMessage.Property("ContentHeaders"))
{
response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf<string>());
}
// --------------------------- deserialize request ----------------------------------------------------------------
response.RequestMessage = new HttpRequestMessage
{
Method = new HttpMethod(reqMessage.StringProperty("Method")),
RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")),
Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content")))
};
foreach (var each in reqMessage.Property("Headers"))
{
response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf<string>());
}
foreach (var each in reqMessage.Property("ContentHeaders"))
{
response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf<string>());
}
return response;
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next)
{
counter++;
var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}";
switch (Mode)
{
case MockMode.Record:
//Add following code since the request.Content will be released after sendAsync
var requestClone = request;
if (requestClone.Content != null)
{
requestClone = await request.CloneWithContent(request.RequestUri, request.Method);
}
// make the call
var response = await next.SendAsync(request, callback);
// save the message to the recording file
SaveMessage(rqkey, requestClone, response);
// return the response.
return response;
case MockMode.Playback:
// load and return the response.
return LoadMessage(rqkey);
default:
// pass-thru, do nothing
return await next.SendAsync(request, callback);
}
}
}
} | 42.059055 | 319 | 0.544978 | [
"MIT"
] | 3quanfeng/azure-powershell | src/CloudService/generated/runtime/PipelineMocking.cs | 10,430 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using MediatR;
using Microsoft.Health.Abstractions.Features.Transactions;
using Microsoft.Health.Core.Internal;
using Microsoft.Health.Fhir.Core;
using Microsoft.Health.Fhir.Core.Exceptions;
using Microsoft.Health.Fhir.Core.Extensions;
using Microsoft.Health.Fhir.Core.Features.Conformance;
using Microsoft.Health.Fhir.Core.Features.Definition;
using Microsoft.Health.Fhir.Core.Features.Persistence;
using Microsoft.Health.Fhir.Core.Features.Search;
using Microsoft.Health.Fhir.Core.Features.Search.Registry;
using Microsoft.Health.Fhir.Core.Features.Search.SearchValues;
using Microsoft.Health.Fhir.Core.Messages.Delete;
using Microsoft.Health.Fhir.Core.Models;
using Microsoft.Health.Fhir.Tests.Common;
using Microsoft.Health.Fhir.Tests.Common.FixtureParameters;
using Microsoft.Health.Test.Utilities;
using NSubstitute;
using Xunit;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Health.Fhir.Tests.Integration.Persistence
{
/// <summary>
/// Tests for storage layer.
/// </summary>
[FhirStorageTestsFixtureArgumentSets(DataStore.All)]
public partial class FhirStorageTests : IClassFixture<FhirStorageTestsFixture>
{
private readonly FhirStorageTestsFixture _fixture;
private readonly CapabilityStatement _capabilityStatement;
private readonly ResourceDeserializer _deserializer;
private readonly FhirJsonParser _fhirJsonParser;
private readonly IFhirDataStore _dataStore;
private readonly SearchParameterDefinitionManager _searchParameterDefinitionManager;
private readonly ConformanceProviderBase _conformanceProvider;
public FhirStorageTests(FhirStorageTestsFixture fixture)
{
_fixture = fixture;
_capabilityStatement = fixture.CapabilityStatement;
_deserializer = fixture.Deserializer;
_dataStore = fixture.DataStore;
_fhirJsonParser = fixture.JsonParser;
_conformanceProvider = fixture.ConformanceProvider;
_searchParameterDefinitionManager = fixture.SearchParameterDefinitionManager;
Mediator = fixture.Mediator;
}
protected Mediator Mediator { get; }
[Fact]
public async Task GivenAResource_WhenSaving_ThenTheMetaIsUpdated()
{
var instant = new DateTimeOffset(DateTimeOffset.Now.Date, TimeSpan.Zero);
using (Mock.Property(() => ClockResolver.UtcNowFunc, () => instant))
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
Assert.NotNull(saveResult);
Assert.Equal(SaveOutcomeType.Created, saveResult.Outcome);
var deserializedResource = saveResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
Assert.NotNull(deserializedResource);
Assert.NotNull(deserializedResource);
Assert.NotNull(deserializedResource);
Assert.Equal(instant, deserializedResource.LastUpdated.GetValueOrDefault());
}
}
[Fact]
public async Task GivenAResourceId_WhenFetching_ThenTheResponseLoadsCorrectly()
{
var saveResult = await Mediator.CreateResourceAsync(Samples.GetJsonSample("Weight"));
var getResult = (await Mediator.GetResourceAsync(new ResourceKey("Observation", saveResult.Id))).ToResourceElement(_deserializer);
Assert.NotNull(getResult);
Assert.Equal(saveResult.Id, getResult.Id);
var observation = getResult.ToPoco<Observation>();
Assert.NotNull(observation);
Assert.NotNull(observation.Value);
Quantity sq = Assert.IsType<Quantity>(observation.Value);
Assert.Equal(67, sq.Value);
}
[Fact]
public async Task GivenASavedResource_WhenUpsertIsAnUpdate_ThenTheExistingResourceIsUpdated()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco();
newResourceValues.Id = saveResult.RawResourceElement.Id;
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues.ToResourceElement(), WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId));
var deserializedResource = updateResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
Assert.NotNull(deserializedResource);
Assert.Equal(SaveOutcomeType.Updated, updateResult.Outcome);
var wrapper = await _fixture.DataStore.GetAsync(new ResourceKey("Observation", deserializedResource.Id), CancellationToken.None);
Assert.NotNull(wrapper);
if (wrapper.RawResource.IsMetaSet)
{
Observation observation = _fhirJsonParser.Parse<Observation>(wrapper.RawResource.Data);
Assert.Equal("2", observation.VersionId);
}
}
[Fact]
public async Task GivenAResource_WhenUpserting_ThenTheNewResourceHasMetaSet()
{
var instant = new DateTimeOffset(DateTimeOffset.Now.Date, TimeSpan.Zero);
using (Mock.Property(() => ClockResolver.UtcNowFunc, () => instant))
{
var versionId = Guid.NewGuid().ToString();
var resource = Samples.GetJsonSample("Weight").UpdateVersion(versionId);
var saveResult = await Mediator.UpsertResourceAsync(resource);
Assert.NotNull(saveResult);
Assert.Equal(SaveOutcomeType.Created, saveResult.Outcome);
var deserializedResource = saveResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
Assert.NotNull(deserializedResource);
var wrapper = await _fixture.DataStore.GetAsync(new ResourceKey("Observation", deserializedResource.Id), CancellationToken.None);
Assert.NotNull(wrapper);
Assert.True(wrapper.RawResource.IsMetaSet);
Assert.NotEqual(wrapper.Version, versionId);
var deserialized = _fhirJsonParser.Parse<Observation>(wrapper.RawResource.Data);
Assert.NotEqual(versionId, deserialized.VersionId);
}
}
[Fact]
public async Task GivenASavedResource_WhenUpserting_ThenRawResourceVersionIsSetOrMetaSetIsSetToFalse()
{
var versionId = Guid.NewGuid().ToString();
var resource = Samples.GetJsonSample("Weight").UpdateVersion(versionId);
var saveResult = await Mediator.UpsertResourceAsync(resource);
var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco();
newResourceValues.Id = saveResult.RawResourceElement.Id;
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues.ToResourceElement(), WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId));
Assert.NotNull(updateResult);
Assert.Equal(SaveOutcomeType.Updated, updateResult.Outcome);
var deserializedResource = updateResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
Assert.NotNull(deserializedResource);
Assert.Equal(saveResult.RawResourceElement.Id, updateResult.RawResourceElement.Id);
var wrapper = await _fixture.DataStore.GetAsync(new ResourceKey("Observation", deserializedResource.Id), CancellationToken.None);
Assert.NotNull(wrapper);
Assert.NotEqual(wrapper.Version, versionId);
var deserialized = _fhirJsonParser.Parse<Observation>(wrapper.RawResource.Data);
Assert.Equal(wrapper.RawResource.IsMetaSet ? "2" : "1", deserialized.VersionId);
}
[Theory]
[InlineData("1")]
[InlineData("-1")]
[InlineData("0")]
[InlineData("InvalidVersion")]
public async Task GivenANonexistentResource_WhenUpsertingWithCreateEnabledAndIntegerETagHeader_TheServerShouldReturnResourceNotFoundResponse(string versionId)
{
await Assert.ThrowsAsync<ResourceNotFoundException>(async () =>
await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId(versionId)));
}
[Theory]
[InlineData("1")]
[InlineData("-1")]
[InlineData("0")]
[InlineData("InvalidVersion")]
public async Task GivenANonexistentResource_WhenUpsertingWithCreateDisabledAndIntegerETagHeader_TheServerShouldReturnResourceNotFoundResponse(string versionId)
{
await SetAllowCreateForOperation(
false,
async () =>
{
await Assert.ThrowsAsync<ResourceNotFoundException>(async () =>
await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId(versionId)));
});
}
[Fact]
public async Task GivenAResource_WhenUpsertingDifferentTypeWithTheSameId_ThenTheExistingResourceIsNotOverridden()
{
var weightSample = Samples.GetJsonSample("Weight").ToPoco();
var patientSample = Samples.GetJsonSample("Patient").ToPoco();
var exampleId = Guid.NewGuid().ToString();
weightSample.Id = exampleId;
patientSample.Id = exampleId;
await Mediator.UpsertResourceAsync(weightSample.ToResourceElement());
await Mediator.UpsertResourceAsync(patientSample.ToResourceElement());
var fetchedResult1 = (await Mediator.GetResourceAsync(new ResourceKey<Observation>(exampleId))).ToResourceElement(_deserializer);
var fetchedResult2 = (await Mediator.GetResourceAsync(new ResourceKey<Patient>(exampleId))).ToResourceElement(_deserializer);
Assert.Equal(weightSample.Id, fetchedResult1.Id);
Assert.Equal(patientSample.Id, fetchedResult2.Id);
Assert.Equal(weightSample.TypeName, fetchedResult1.InstanceType);
Assert.Equal(patientSample.TypeName, fetchedResult2.InstanceType);
}
[Fact]
public async Task GivenANonexistentResource_WhenUpsertingWithCreateDisabled_ThenAMethodNotAllowedExceptionIsThrown()
{
await SetAllowCreateForOperation(
false,
async () =>
{
var ex = await Assert.ThrowsAsync<MethodNotAllowedException>(() => Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight")));
Assert.Equal(Resources.ResourceCreationNotAllowed, ex.Message);
});
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.CosmosDb)]
public async Task GivenANonexistentResourceAndCosmosDb_WhenUpsertingWithCreateDisabledAndInvalidETagHeader_ThenAResourceNotFoundIsThrown()
{
await SetAllowCreateForOperation(
false,
async () => await Assert.ThrowsAsync<ResourceNotFoundException>(() => Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId("invalidVersion"))));
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.CosmosDb)]
public async Task GivenANonexistentResourceAndCosmosDb_WhenUpsertingWithCreateEnabledAndInvalidETagHeader_ThenResourceNotFoundIsThrown()
{
await Assert.ThrowsAsync<ResourceNotFoundException>(() => Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"), WeakETag.FromVersionId("invalidVersion")));
}
[Fact]
public async Task GivenASavedResource_WhenUpsertingWithNoETagHeader_ThenTheExistingResourceIsUpdated()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco();
newResourceValues.Id = saveResult.RawResourceElement.Id;
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues.ToResourceElement());
Assert.NotNull(updateResult);
Assert.Equal(SaveOutcomeType.Updated, updateResult.Outcome);
var deserializedResource = updateResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
Assert.NotNull(deserializedResource);
Assert.Equal(saveResult.RawResourceElement.Id, updateResult.RawResourceElement.Id);
}
[Fact]
public async Task GivenASavedResource_WhenConcurrentlyUpsertingWithNoETagHeader_ThenTheExistingResourceIsUpdated()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco<Resource>();
newResourceValues.Id = saveResult.RawResourceElement.Id;
var list = new List<Task<SaveOutcome>>();
Resource CloneResource(int value)
{
var newResource = (Observation)newResourceValues.DeepCopy();
newResource.Value = new Quantity(value, "kg");
return newResource;
}
var itemsToCreate = 10;
for (int i = 0; i < itemsToCreate; i++)
{
list.Add(Mediator.UpsertResourceAsync(CloneResource(i).ToResourceElement()));
}
await Task.WhenAll(list);
var deserializedList = new List<Observation>();
foreach (var item in list)
{
Assert.Equal(SaveOutcomeType.Updated, item.Result.Outcome);
deserializedList.Add(item.Result.RawResourceElement.ToPoco<Observation>(Deserializers.ResourceDeserializer));
}
var allObservations = deserializedList.Select(x => ((Quantity)x.Value).Value.GetValueOrDefault()).Distinct();
Assert.Equal(itemsToCreate, allObservations.Count());
}
[Fact]
public async Task GivenAResourceWithNoHistory_WhenFetchingByVersionId_ThenReadWorksCorrectly()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var deserialized = saveResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
var result = (await Mediator.GetResourceAsync(new ResourceKey(deserialized.InstanceType, deserialized.Id, deserialized.VersionId))).ToResourceElement(_deserializer);
Assert.NotNull(result);
Assert.Equal(deserialized.Id, result.Id);
}
[Fact]
public async Task UpdatingAResource_ThenWeCanAccessHistoricValues()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var newResourceValues = Samples.GetJsonSample("WeightInGrams")
.UpdateId(saveResult.RawResourceElement.Id);
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues, WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId));
var getV1Result = (await Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id, saveResult.RawResourceElement.VersionId))).ToResourceElement(_deserializer);
Assert.NotNull(getV1Result);
Assert.Equal(saveResult.RawResourceElement.Id, getV1Result.Id);
Assert.Equal(updateResult.RawResourceElement.Id, getV1Result.Id);
var oldObservation = getV1Result.ToPoco<Observation>();
Assert.NotNull(oldObservation);
Assert.NotNull(oldObservation.Value);
Quantity sq = Assert.IsType<Quantity>(oldObservation.Value);
Assert.Equal(67, sq.Value);
}
[Fact]
public async Task UpdatingAResourceWithNoHistory_ThenWeCannotAccessHistoricValues()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetDefaultOrganization());
var newResourceValues = Samples.GetDefaultOrganization()
.UpdateId(saveResult.RawResourceElement.Id);
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues, WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId));
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Organization>(saveResult.RawResourceElement.Id, saveResult.RawResourceElement.VersionId)));
}
[Fact]
public async Task WhenDeletingAResource_ThenWeGetResourceGone()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var deletedResourceKey = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", saveResult.RawResourceElement.Id), DeleteOperation.SoftDelete);
Assert.NotEqual(saveResult.RawResourceElement.VersionId, deletedResourceKey.ResourceKey.VersionId);
await Assert.ThrowsAsync<ResourceGoneException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id)));
}
[Fact]
public async Task WhenDeletingAResourceThatNeverExisted_ThenReadingTheResourceReturnsNotFound()
{
string id = "missingid";
var deletedResourceKey = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", id), DeleteOperation.SoftDelete);
Assert.Null(deletedResourceKey.ResourceKey.VersionId);
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(id)));
}
[Fact]
public async Task WhenDeletingAResourceForASecondTime_ThenWeDoNotGetANewVersion()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var resourceKey = new ResourceKey("Observation", saveResult.RawResourceElement.Id);
await Mediator.DeleteResourceAsync(resourceKey, DeleteOperation.SoftDelete);
var deletedResourceKey2 = await Mediator.DeleteResourceAsync(resourceKey, DeleteOperation.SoftDelete);
Assert.Null(deletedResourceKey2.ResourceKey.VersionId);
await Assert.ThrowsAsync<ResourceGoneException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id)));
}
[Fact]
public async Task WhenHardDeletingAResource_ThenWeGetResourceNotFound()
{
object snapshotToken = await _fixture.TestHelper.GetSnapshotToken();
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var deletedResourceKey = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", saveResult.RawResourceElement.Id), DeleteOperation.HardDelete);
Assert.Null(deletedResourceKey.ResourceKey.VersionId);
// Subsequent get should result in NotFound.
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id)));
// Subsequent version get should result in NotFound.
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id, saveResult.RawResourceElement.VersionId)));
await _fixture.TestHelper.ValidateSnapshotTokenIsCurrent(snapshotToken);
}
[Fact]
public async Task WhenHardDeletingAResource_ThenHistoryShouldBeDeleted()
{
object snapshotToken = await _fixture.TestHelper.GetSnapshotToken();
var createResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var deserializedResult = createResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer);
string resourceId = createResult.RawResourceElement.Id;
var deleteResult = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", resourceId), DeleteOperation.SoftDelete);
var updateResult = await Mediator.UpsertResourceAsync(deserializedResult);
// Hard-delete the resource.
var deletedResourceKey = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", resourceId), DeleteOperation.HardDelete);
Assert.Null(deletedResourceKey.ResourceKey.VersionId);
// Subsequent get should result in NotFound.
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(resourceId)));
// Subsequent version get should result in NotFound.
foreach (string versionId in new[] { createResult.RawResourceElement.VersionId, deleteResult.ResourceKey.VersionId, updateResult.RawResourceElement.VersionId })
{
await Assert.ThrowsAsync<ResourceNotFoundException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(resourceId, versionId)));
}
await _fixture.TestHelper.ValidateSnapshotTokenIsCurrent(snapshotToken);
}
[Fact]
public async Task GivenAResourceSavedInRepository_AccessingANonValidVersion_ThenGetsNotFound()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
await Assert.ThrowsAsync<ResourceNotFoundException>(
async () => { await Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id, Guid.NewGuid().ToString())); });
}
[Fact]
public async Task WhenGettingNonExistentResource_ThenNotFoundIsThrown()
{
await Assert.ThrowsAsync<ResourceNotFoundException>(
async () => { await Mediator.GetResourceAsync(new ResourceKey<Observation>(Guid.NewGuid().ToString())); });
}
[Fact]
public async Task WhenDeletingSpecificVersion_ThenMethodNotAllowedIsThrown()
{
await Assert.ThrowsAsync<MethodNotAllowedException>(
async () => { await Mediator.DeleteResourceAsync(new ResourceKey<Observation>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()), DeleteOperation.SoftDelete); });
}
[Fact]
public async Task GivenADeletedResource_WhenUpsertingWithValidETagHeader_ThenTheDeletedResourceIsRevived()
{
var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
var deletedResourceKey = await Mediator.DeleteResourceAsync(new ResourceKey("Observation", saveResult.RawResourceElement.Id), DeleteOperation.SoftDelete);
Assert.NotEqual(saveResult.RawResourceElement.VersionId, deletedResourceKey.ResourceKey.VersionId);
await Assert.ThrowsAsync<ResourceGoneException>(
() => Mediator.GetResourceAsync(new ResourceKey<Observation>(saveResult.RawResourceElement.Id)));
var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco();
newResourceValues.Id = saveResult.RawResourceElement.Id;
var updateResult = await Mediator.UpsertResourceAsync(newResourceValues.ToResourceElement(), deletedResourceKey.WeakETag);
Assert.NotNull(updateResult);
Assert.Equal(SaveOutcomeType.Updated, updateResult.Outcome);
Assert.NotNull(updateResult.RawResourceElement);
Assert.Equal(saveResult.RawResourceElement.Id, updateResult.RawResourceElement.Id);
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.SqlServer)]
public async Task GivenATransactionHandler_WhenATransactionIsCommitted_ThenTheResourceShouldBeCreated()
{
string createdId = string.Empty;
using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
{
SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
createdId = saveResult.RawResourceElement.Id;
Assert.NotEqual(string.Empty, createdId);
transactionScope.Complete();
}
ResourceElement getResult = (await Mediator.GetResourceAsync(new ResourceKey<Observation>(createdId))).ToResourceElement(_deserializer);
Assert.Equal(createdId, getResult.Id);
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.SqlServer)]
public async Task GivenACompletedTransaction_WhenStartingASecondTransactionCommitted_ThenTheResourceShouldBeCreated()
{
string createdId1;
string createdId2;
using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
{
SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
createdId1 = saveResult.RawResourceElement.Id;
Assert.NotEqual(string.Empty, createdId1);
transactionScope.Complete();
}
using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
{
SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
createdId2 = saveResult.RawResourceElement.Id;
Assert.NotEqual(string.Empty, createdId2);
transactionScope.Complete();
}
ResourceElement getResult1 = (await Mediator.GetResourceAsync(new ResourceKey<Observation>(createdId1))).ToResourceElement(_deserializer);
Assert.Equal(createdId1, getResult1.Id);
ResourceElement getResult2 = (await Mediator.GetResourceAsync(new ResourceKey<Observation>(createdId2))).ToResourceElement(_deserializer);
Assert.Equal(createdId2, getResult2.Id);
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.SqlServer)]
public async Task GivenATransactionHandler_WhenATransactionIsNotCommitted_ThenNothingShouldBeCreated()
{
string createdId = string.Empty;
using (_ = _fixture.TransactionHandler.BeginTransaction())
{
SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
createdId = saveResult.RawResourceElement.Id;
Assert.NotEqual(string.Empty, createdId);
}
await Assert.ThrowsAsync<ResourceNotFoundException>(
async () => { await Mediator.GetResourceAsync(new ResourceKey<Observation>(createdId)); });
}
[Fact]
[FhirStorageTestsFixtureArgumentSets(DataStore.SqlServer)]
public async Task GivenATransactionHandler_WhenATransactionFailsFailedRequest_ThenNothingShouldCommit()
{
string createdId = string.Empty;
string randomNotFoundId = Guid.NewGuid().ToString();
await Assert.ThrowsAsync<ResourceNotFoundException>(
async () =>
{
using (ITransactionScope transactionScope = _fixture.TransactionHandler.BeginTransaction())
{
SaveOutcome saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight"));
createdId = saveResult.RawResourceElement.Id;
Assert.NotEqual(string.Empty, createdId);
await Mediator.GetResourceAsync(new ResourceKey<Observation>(randomNotFoundId));
transactionScope.Complete();
}
});
await Assert.ThrowsAsync<ResourceNotFoundException>(
async () => { await Mediator.GetResourceAsync(new ResourceKey<Observation>(createdId)); });
}
[Fact]
public async Task GivenAnUpdatedResource_WhenUpdatingSearchParameterIndexAsync_ThenResourceMetadataIsUnchanged()
{
ResourceElement patientResource = CreatePatientResourceElement("Patient", Guid.NewGuid().ToString());
SaveOutcome upsertResult = await Mediator.UpsertResourceAsync(patientResource);
SearchParameter searchParam = null;
const string searchParamName = "newSearchParam";
try
{
searchParam = await CreatePatientSearchParam(searchParamName, SearchParamType.String, "Patient.name");
ISearchValue searchValue = new StringSearchValue(searchParamName);
(ResourceWrapper original, ResourceWrapper updated) = await CreateUpdatedWrapperFromExistingPatient(upsertResult, searchParam, searchValue);
await _dataStore.UpdateSearchParameterIndicesAsync(updated, WeakETag.FromVersionId(original.Version), CancellationToken.None);
// Get the reindexed resource from the database
var resourceKey1 = new ResourceKey(upsertResult.RawResourceElement.InstanceType, upsertResult.RawResourceElement.Id, upsertResult.RawResourceElement.VersionId);
ResourceWrapper reindexed = await _dataStore.GetAsync(resourceKey1, CancellationToken.None);
VerifyReindexedResource(original, reindexed);
}
finally
{
if (searchParam != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None);
}
}
}
[Fact]
public async Task GivenAnUpdatedResourceWithWrongWeakETag_WhenUpdatingSearchParameterIndexAsync_ThenExceptionIsThrown()
{
ResourceElement patientResource = CreatePatientResourceElement("Patient", Guid.NewGuid().ToString());
SaveOutcome upsertResult = await Mediator.UpsertResourceAsync(patientResource);
SearchParameter searchParam1 = null;
const string searchParamName1 = "newSearchParam1";
SearchParameter searchParam2 = null;
const string searchParamName2 = "newSearchParam2";
try
{
searchParam1 = await CreatePatientSearchParam(searchParamName1, SearchParamType.String, "Patient.name");
ISearchValue searchValue1 = new StringSearchValue(searchParamName1);
(ResourceWrapper original, ResourceWrapper updatedWithSearchParam1) = await CreateUpdatedWrapperFromExistingPatient(upsertResult, searchParam1, searchValue1);
await _dataStore.UpsertAsync(updatedWithSearchParam1, WeakETag.FromVersionId(original.Version), allowCreate: false, keepHistory: false, CancellationToken.None);
// Let's update the resource again with new information
searchParam2 = await CreatePatientSearchParam(searchParamName2, SearchParamType.Token, "Patient.gender");
ISearchValue searchValue2 = new TokenSearchValue("system", "code", "text");
// Create the updated wrapper from the original resource that has the outdated version
(_, ResourceWrapper updatedWithSearchParam2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult, searchParam2, searchValue2, original);
// Attempt to reindex the resource
await Assert.ThrowsAsync<PreconditionFailedException>(() => _dataStore.UpdateSearchParameterIndicesAsync(updatedWithSearchParam2, WeakETag.FromVersionId(original.Version), CancellationToken.None));
}
finally
{
if (searchParam1 != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam1.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam1.Url, CancellationToken.None);
}
if (searchParam2 != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam2.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam2.Url, CancellationToken.None);
}
}
}
[Fact]
public async Task GivenADeletedResource_WhenUpdatingSearchParameterIndexAsync_ThenExceptionIsThrown()
{
ResourceElement patientResource = CreatePatientResourceElement("Patient", Guid.NewGuid().ToString());
SaveOutcome upsertResult = await Mediator.UpsertResourceAsync(patientResource);
SearchParameter searchParam = null;
const string searchParamName = "newSearchParam";
try
{
searchParam = await CreatePatientSearchParam(searchParamName, SearchParamType.String, "Patient.name");
ISearchValue searchValue = new StringSearchValue(searchParamName);
// Update the resource wrapper, adding the new search parameter
(ResourceWrapper original, ResourceWrapper updated) = await CreateUpdatedWrapperFromExistingPatient(upsertResult, searchParam, searchValue);
ResourceWrapper deletedWrapper = CreateDeletedWrapper(original);
await _dataStore.UpsertAsync(deletedWrapper, WeakETag.FromVersionId(deletedWrapper.Version), allowCreate: true, keepHistory: false, CancellationToken.None);
// Attempt to reindex the version of the resource that hasn't been deleted
await Assert.ThrowsAsync<PreconditionFailedException>(() => _dataStore.UpdateSearchParameterIndicesAsync(updated, WeakETag.FromVersionId(updated.Version), CancellationToken.None));
}
finally
{
if (searchParam != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None);
}
}
}
[Fact]
public async Task GivenUpdatedResources_WhenBulkUpdatingSearchParameterIndicesAsync_ThenResourceMetadataIsUnchanged()
{
ResourceElement patientResource1 = CreatePatientResourceElement("Patient1", Guid.NewGuid().ToString());
SaveOutcome upsertResult1 = await Mediator.UpsertResourceAsync(patientResource1);
ResourceElement patientResource2 = CreatePatientResourceElement("Patient2", Guid.NewGuid().ToString());
SaveOutcome upsertResult2 = await Mediator.UpsertResourceAsync(patientResource2);
SearchParameter searchParam = null;
const string searchParamName = "newSearchParam";
try
{
searchParam = await CreatePatientSearchParam(searchParamName, SearchParamType.String, "Patient.name");
ISearchValue searchValue = new StringSearchValue(searchParamName);
(ResourceWrapper original1, ResourceWrapper updated1) = await CreateUpdatedWrapperFromExistingPatient(upsertResult1, searchParam, searchValue);
(ResourceWrapper original2, ResourceWrapper updated2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult2, searchParam, searchValue);
var resources = new List<ResourceWrapper> { updated1, updated2 };
await _dataStore.BulkUpdateSearchParameterIndicesAsync(resources, CancellationToken.None);
// Get the reindexed resources from the database
var resourceKey1 = new ResourceKey(upsertResult1.RawResourceElement.InstanceType, upsertResult1.RawResourceElement.Id, upsertResult1.RawResourceElement.VersionId);
ResourceWrapper reindexed1 = await _dataStore.GetAsync(resourceKey1, CancellationToken.None);
var resourceKey2 = new ResourceKey(upsertResult2.RawResourceElement.InstanceType, upsertResult2.RawResourceElement.Id, upsertResult2.RawResourceElement.VersionId);
ResourceWrapper reindexed2 = await _dataStore.GetAsync(resourceKey2, CancellationToken.None);
VerifyReindexedResource(original1, reindexed1);
VerifyReindexedResource(original2, reindexed2);
}
finally
{
if (searchParam != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None);
}
}
}
[Fact]
public async Task GivenUpdatedResourcesWithWrongWeakETag_WhenBulkUpdatingSearchParameterIndicesAsync_ThenExceptionIsThrown()
{
ResourceElement patientResource1 = CreatePatientResourceElement("Patient1", Guid.NewGuid().ToString());
SaveOutcome upsertResult1 = await Mediator.UpsertResourceAsync(patientResource1);
ResourceElement patientResource2 = CreatePatientResourceElement("Patient2", Guid.NewGuid().ToString());
SaveOutcome upsertResult2 = await Mediator.UpsertResourceAsync(patientResource2);
SearchParameter searchParam1 = null;
const string searchParamName1 = "newSearchParam1";
SearchParameter searchParam2 = null;
const string searchParamName2 = "newSearchParam2";
try
{
searchParam1 = await CreatePatientSearchParam(searchParamName1, SearchParamType.String, "Patient.name");
ISearchValue searchValue1 = new StringSearchValue(searchParamName1);
(ResourceWrapper original1, ResourceWrapper updated1) = await CreateUpdatedWrapperFromExistingPatient(upsertResult1, searchParam1, searchValue1);
(ResourceWrapper original2, ResourceWrapper updated2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult2, searchParam1, searchValue1);
await _dataStore.UpsertAsync(updated1, WeakETag.FromVersionId(original1.Version), allowCreate: false, keepHistory: false, CancellationToken.None);
await _dataStore.UpsertAsync(updated2, WeakETag.FromVersionId(original2.Version), allowCreate: false, keepHistory: false, CancellationToken.None);
// Let's update the resources again with new information
searchParam2 = await CreatePatientSearchParam(searchParamName2, SearchParamType.Token, "Patient.gender");
ISearchValue searchValue2 = new TokenSearchValue("system", "code", "text");
// Create the updated wrappers using the original resource and its outdated version
(_, ResourceWrapper updated1WithSearchParam2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult1, searchParam2, searchValue2, original1);
(_, ResourceWrapper updated2WithSearchParam2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult2, searchParam2, searchValue2, original2);
var resources = new List<ResourceWrapper> { updated1WithSearchParam2, updated2WithSearchParam2 };
// Attempt to reindex resources with the old versions
await Assert.ThrowsAsync<PreconditionFailedException>(() => _dataStore.BulkUpdateSearchParameterIndicesAsync(resources, CancellationToken.None));
}
finally
{
if (searchParam1 != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam1.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam1.Url, CancellationToken.None);
}
if (searchParam2 != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam2.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam2.Url, CancellationToken.None);
}
}
}
[Fact]
public async Task GivenDeletedResource_WhenBulkUpdatingSearchParameterIndicesAsync_ThenExceptionIsThrown()
{
ResourceElement patientResource1 = CreatePatientResourceElement("Patient1", Guid.NewGuid().ToString());
SaveOutcome upsertResult1 = await Mediator.UpsertResourceAsync(patientResource1);
ResourceElement patientResource2 = CreatePatientResourceElement("Patient2", Guid.NewGuid().ToString());
SaveOutcome upsertResult2 = await Mediator.UpsertResourceAsync(patientResource2);
SearchParameter searchParam = null;
const string searchParamName = "newSearchParam";
try
{
searchParam = await CreatePatientSearchParam(searchParamName, SearchParamType.String, "Patient.name");
ISearchValue searchValue = new StringSearchValue(searchParamName);
// Update the resource wrappers, adding the new search parameter
(ResourceWrapper original1, ResourceWrapper updated1) = await CreateUpdatedWrapperFromExistingPatient(upsertResult1, searchParam, searchValue);
(_, ResourceWrapper updated2) = await CreateUpdatedWrapperFromExistingPatient(upsertResult2, searchParam, searchValue);
// Delete one of the two resources
ResourceWrapper deletedWrapper = CreateDeletedWrapper(original1);
await _dataStore.UpsertAsync(deletedWrapper, WeakETag.FromVersionId(deletedWrapper.Version), allowCreate: true, keepHistory: false, CancellationToken.None);
var resources = new List<ResourceWrapper> { updated1, updated2 };
// Attempt to reindex both resources, one of which has since been deleted and has a version that is out of date.
await Assert.ThrowsAsync<PreconditionFailedException>(() => _dataStore.BulkUpdateSearchParameterIndicesAsync(resources, CancellationToken.None));
}
finally
{
if (searchParam != null)
{
_searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement());
await _fixture.TestHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None);
}
}
}
private static void VerifyReindexedResource(ResourceWrapper original, ResourceWrapper replaceResult)
{
Assert.Equal(original.ResourceId, replaceResult.ResourceId);
Assert.Equal(original.Version, replaceResult.Version);
Assert.Equal(original.ResourceTypeName, replaceResult.ResourceTypeName);
Assert.Equal(original.LastModified, replaceResult.LastModified);
}
private async Task<(ResourceWrapper original, ResourceWrapper updated)> CreateUpdatedWrapperFromExistingPatient(
SaveOutcome upsertResult,
SearchParameter searchParam,
ISearchValue searchValue,
ResourceWrapper originalWrapper = null,
string updatedId = null)
{
var searchIndex = new SearchIndexEntry(searchParam.ToInfo(), searchValue);
var searchIndices = new List<SearchIndexEntry> { searchIndex };
if (originalWrapper == null)
{
// Get wrapper from data store directly
var resourceKey = new ResourceKey(upsertResult.RawResourceElement.InstanceType, upsertResult.RawResourceElement.Id, upsertResult.RawResourceElement.VersionId);
originalWrapper = await _dataStore.GetAsync(resourceKey, CancellationToken.None);
}
// Add new search index entry to existing wrapper
var updatedWrapper = new ResourceWrapper(
updatedId ?? originalWrapper.ResourceId,
originalWrapper.Version,
originalWrapper.ResourceTypeName,
originalWrapper.RawResource,
new ResourceRequest(HttpMethod.Post, null),
originalWrapper.LastModified,
deleted: false,
searchIndices,
originalWrapper.CompartmentIndices,
originalWrapper.LastModifiedClaims,
_searchParameterDefinitionManager.GetSearchParameterHashForResourceType("Patient"));
return (originalWrapper, updatedWrapper);
}
private ResourceWrapper CreateDeletedWrapper(ResourceWrapper originalWrapper)
{
return new ResourceWrapper(
originalWrapper.ResourceId,
originalWrapper.Version,
originalWrapper.ResourceTypeName,
originalWrapper.RawResource,
new ResourceRequest(HttpMethod.Delete, null),
originalWrapper.LastModified,
deleted: true,
originalWrapper.SearchIndices,
originalWrapper.CompartmentIndices,
originalWrapper.LastModifiedClaims,
originalWrapper.SearchParameterHash);
}
private async Task<SearchParameter> CreatePatientSearchParam(string searchParamName, SearchParamType type, string expression)
{
var searchParam = new SearchParameter
{
Url = $"http://hl7.org/fhir/SearchParameter/Patient-{searchParamName}",
Type = type,
Base = new List<ResourceType?> { ResourceType.Patient },
Expression = expression,
Name = searchParamName,
Code = searchParamName,
};
_searchParameterDefinitionManager.AddNewSearchParameters(new List<ITypedElement> { searchParam.ToTypedElement() });
// Add the search parameter to the datastore
await _fixture.SearchParameterStatusManager.UpdateSearchParameterStatusAsync(new List<string> { searchParam.Url }, SearchParameterStatus.Supported);
return searchParam;
}
private ResourceElement CreatePatientResourceElement(string patientName, string id)
{
var json = Samples.GetJson("Patient");
json = json.Replace("Chalmers", patientName);
json = json.Replace("\"id\": \"example\"", "\"id\": \"" + id + "\"");
var rawResource = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);
return Deserializers.ResourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow);
}
private async Task ExecuteAndVerifyException<TException>(Func<Task> action)
where TException : Exception
{
await Assert.ThrowsAsync<TException>(action);
}
private async Task SetAllowCreateForOperation(bool allowCreate, Func<Task> operation)
{
var observation = _capabilityStatement.Rest[0].Resource.Find(r => r.Type == ResourceType.Observation);
var originalValue = observation.UpdateCreate;
observation.UpdateCreate = allowCreate;
observation.Versioning = CapabilityStatement.ResourceVersionPolicy.Versioned;
_conformanceProvider.ClearCache();
try
{
await operation();
}
finally
{
observation.UpdateCreate = originalValue;
_conformanceProvider.ClearCache();
}
}
}
}
| 49.690501 | 213 | 0.677966 | [
"MIT"
] | Lukas1v/fhir-server | test/Microsoft.Health.Fhir.Shared.Tests.Integration/Persistence/FhirStorageTests.cs | 48,649 | C# |
namespace Animals
{
public class Dog : Animal
{
public Dog(string name, int age, string gender) : base(name, age, gender)
{
}
public override string ProduceSound()
{
return "Woof!";
}
}
} | 17.466667 | 81 | 0.503817 | [
"MIT"
] | NIKONaaaaa/Basic | 04OOP/01InheritanceExercise/Animals/Dog.cs | 264 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Complex.Logger.Model;
namespace Complex.Logger.Interface
{
public interface IJobLogger
{
void Log(string message, LogLevel logLevel);
}
}
| 18 | 52 | 0.734127 | [
"MIT"
] | otro34/complexlogger | Complex.Logger/Interface/IJobLogger.cs | 254 | C# |
using System;
using NumericalGeometryLib.BasicMath;
using NumericalGeometryLib.BasicMath.Matrices;
using NumericalGeometryLib.BasicMath.Tuples;
using NumericalGeometryLib.BasicMath.Tuples.Immutable;
using TextComposerLib.Text.Linear;
namespace GraphicsComposerLib.WebGl.Xeogl.Transforms
{
public sealed class XeoglQRotateTransform : IXeoglNumericalTransform
{
public static XeoglQRotateTransform CreateRotate(double angle, ITuple3D rotateVector)
{
var d = 1 / rotateVector.GetLength();
var cosAngle = d * Math.Cos(angle / 2);
var sinAngle = d * Math.Sin(angle / 2);
return new XeoglQRotateTransform
{
QuaternionX = sinAngle * rotateVector.X,
QuaternionY = sinAngle * rotateVector.Y,
QuaternionZ = sinAngle * rotateVector.Z,
QuaternionW = cosAngle
};
}
public static XeoglQRotateTransform CreateRotate(ITuple3D vector1, ITuple3D vector2)
{
var lengthSquared1 = vector1.GetLengthSquared();
var lengthSquared2 = vector2.GetLengthSquared();
var n1 = Math.Sqrt(lengthSquared1 * lengthSquared2);
var w = n1 + vector1.VectorDot(vector2);
var angle = (2 * Math.Acos(w)).ClampAngle();
double vx, vy, vz;
if (w < 1e-12 * n1)
{
var v1 = Math.Abs(vector1.X) > Math.Abs(vector1.Z)
? new Tuple3D(-vector1.Y, vector1.X, 0)
: new Tuple3D(0, -vector1.Z, vector1.Y);
var d = 1 / v1.GetLength();
vx = d * v1.X;
vy = d * v1.Y;
vz = d * v1.Z;
}
else
{
var v2 = vector1.VectorCross(vector2);
var d = 1 / v2.GetLength();
vx = d * v2.X;
vy = d * v2.Y;
vz = d * v2.Z;
}
var sinAngle = Math.Sin(angle / 2);
return new XeoglQRotateTransform
{
QuaternionX = sinAngle * vx,
QuaternionY = sinAngle * vy,
QuaternionZ = sinAngle * vz,
QuaternionW = w
};
}
public static XeoglQRotateTransform CreateRotateXtoY()
{
//Rotate about z-axis by 90 degrees
return new XeoglQRotateTransform
{
QuaternionX = 0,
QuaternionY = 0,
QuaternionZ = MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public static XeoglQRotateTransform CreateRotateYtoX()
{
//Rotate about z-axis by -90 degrees
return new XeoglQRotateTransform
{
QuaternionX = 0,
QuaternionY = 0,
QuaternionZ = -MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public static XeoglQRotateTransform CreateRotateYtoZ()
{
//Rotate about x-axis by 90 degrees
return new XeoglQRotateTransform
{
QuaternionX = MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionY = 0,
QuaternionZ = 0,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public static XeoglQRotateTransform CreateRotateZtoY()
{
//Rotate about x-axis by -90 degrees
return new XeoglQRotateTransform
{
QuaternionX = -MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionY = 0,
QuaternionZ = 0,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public static XeoglQRotateTransform CreateRotateZtoX()
{
//Rotate about y-axis by 90 degrees
return new XeoglQRotateTransform
{
QuaternionX = 0,
QuaternionY = MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionZ = 0,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public static XeoglQRotateTransform CreateRotateXtoZ()
{
//Rotate about y-axis by -90 degrees
return new XeoglQRotateTransform
{
QuaternionX = 0,
QuaternionY = -MathNet.Numerics.Constants.Sqrt1Over2,
QuaternionZ = 0,
QuaternionW = MathNet.Numerics.Constants.Sqrt1Over2
};
}
public double QuaternionX { get; set; }
public double QuaternionY { get; set; }
public double QuaternionZ { get; set; }
public double QuaternionW { get; set; } = 1;
public bool ContainsMatrix => false;
public bool ContainsQuaternion
=> QuaternionX > 0 || QuaternionY > 0 || QuaternionZ > 0 || QuaternionW > 1 ||
QuaternionX < 0 || QuaternionY < 0 || QuaternionZ < 0 || QuaternionW < 1;
public bool ContainsRotate => false;
public bool ContainsScale => false;
public bool ContainsTranslate => false;
public SquareMatrix4 GetMatrix()
=> SquareMatrix4.CreateIdentityMatrix();
public Tuple4D GetQuaternionTuple()
=> new Tuple4D(QuaternionX, QuaternionY, QuaternionZ, QuaternionW);
public Tuple3D GetRotateTuple()
=> Tuple3D.Zero;
public Tuple3D GetScaleTuple()
=> new Tuple3D(1, 1, 1);
public Tuple3D GetTranslateTuple()
=> Tuple3D.Zero;
public string GetMatrixText()
=> GetMatrix().ToJavaScriptNumbersArrayText();
public string GetQuaternionText()
=> GetQuaternionTuple().ToJavaScriptNumbersArrayText();
public string GetRotateText()
=> GetRotateTuple().ToJavaScriptNumbersArrayText();
public string GetScaleText()
=> GetScaleTuple().ToJavaScriptNumbersArrayText();
public string GetTranslateText()
=> GetTranslateTuple().ToJavaScriptNumbersArrayText();
public override string ToString()
{
var composer = new LinearTextComposer();
if (ContainsQuaternion)
{
composer
.Append("quaternion: [")
.Append(QuaternionX.ToString("G"))
.Append(",")
.Append(QuaternionY.ToString("G"))
.Append(",")
.Append(QuaternionZ.ToString("G"))
.Append(",")
.Append(QuaternionW.ToString("G"))
.Append("]");
}
return composer.ToString();
}
}
} | 31.556561 | 93 | 0.537138 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | GraphicsComposerLib/GraphicsComposerLib.WebGl/Xeogl/Transforms/XeoglQRotateTransform.cs | 6,976 | C# |
/*
* Copyright (c) 2018, FusionAuth, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
using System.Collections.Generic;
using System;
namespace io.fusionauth.domain.oauth2 {
/**
* @author Daniel DeGroff
*/
public class IntrospectResponse: Dictionary<string, object> {
public IntrospectResponse with(Action<IntrospectResponse> action) {
action(this);
return this;
}
}
}
| 27.588235 | 71 | 0.722814 | [
"Apache-2.0"
] | FusionAuth/fusionauth-netcore-client | fusionauth-netcore-client/domain/io/fusionauth/domain/oauth2/IntrospectResponse.cs | 938 | C# |
using GameInterface.Cells;
using MCTProcon29Protocol.Methods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace GameInterface
{
public class GameData
{
public byte FinishTurn { get; set; } = 60;
public int TimeLimitSeconds { get; set; } = 5;
private MainWindowViewModel viewModel;
private System.Random rand = new System.Random();
//---------------------------------------
//ViewModelと連動させるデータ(画面上に現れるデータ)
private Cell[,] cellDataValue = null;
public Cell[,] CellData
{
get => cellDataValue;
private set
{
cellDataValue = value;
viewModel.CellData = value;
}
}
public Agent[] Agents
{
get => viewModel.Agents;
set => viewModel.Agents = value;
}
private int[] playerScores = new int[2];
public int[] PlayerScores
{
get => playerScores;
set
{
playerScores = value;
viewModel.PlayerScores = value;
}
}
//----------------------------------------
public int SecondCount { get; set; }
public bool IsGameStarted { get; set; } = false;
public bool IsNextTurnStart { get; set; } = true;
public bool IsAutoSkipTurn { get; set; }
public bool IsPause { get; set; }
public int NowTurn { get; set; }
public int BoardHeight { get; private set; }
public int BoardWidth { get; private set; }
public int SelectPosAgent { get; set; }
public GameSettings.SettingStructure CurrentGameSettings { get; set; }
public List<Decided>[] Decisions = new List<Decided>[2];
public GameData(MainWindowViewModel _viewModel)
{
viewModel = _viewModel;
}
public void InitGameData(GameSettings.SettingStructure settings)
{
CurrentGameSettings = settings;
SecondCount = 0;
NowTurn = 1;
FinishTurn = settings.Turns;
TimeLimitSeconds = settings.LimitTime;
IsAutoSkipTurn = settings.IsAutoSkip;
if(settings.BoardCreation == GameSettings.BoardCreation.QRCode)
{
settings.BoardWidth = (byte)settings.QCCell.GetLength(0);
settings.BoardHeight = (byte)settings.QCCell.GetLength(1);
}
InitCellData(settings);
InitAgents(settings);
}
void InitCellData(GameSettings.SettingStructure settings)
{
if (settings.BoardCreation == GameSettings.BoardCreation.Random)
{
BoardHeight = settings.BoardHeight;
BoardWidth = settings.BoardWidth;
//水平方向か垂直方向のどちらかを対称にするフラグをランダムに立てる
bool isVertical;
bool isHorizontal;
do
{
isVertical = rand.Next(2) == 1 ? true : false;
isHorizontal = rand.Next(2) == 1 ? true : false;
} while (!isVertical && !isHorizontal);
int randWidth, randHeight;
randWidth = (isHorizontal) ? (BoardWidth + 1) / 2 : BoardWidth;
randHeight = (isVertical) ? (BoardHeight + 1) / 2 : BoardHeight;
CellData = new Cell[BoardWidth, BoardHeight];
for (int i = 0; i < BoardWidth; i++)
{
for (int j = 0; j < BoardHeight; j++)
{
if (i < randWidth && j < randHeight)
{
//10%の確率で値を0以下にする
if (rand.Next(1, 100) > 10)
CellData[i, j] = new Cell(rand.Next(1, 14));
else
CellData[i, j] = new Cell(rand.Next(-14, 0));
}
else if (j >= randHeight)
CellData[i, j] = new Cell(CellData[i, BoardHeight - 1 - j].Score);
else
CellData[i, j] = new Cell(CellData[BoardWidth - 1 - i, j].Score);
}
}
}
else
{
CellData = settings.QCCell;
BoardWidth = CellData.GetLength(0);
BoardHeight = CellData.GetLength(1);
}
}
void InitAgents(GameSettings.SettingStructure settings)
{
if (settings.BoardCreation == GameSettings.BoardCreation.Random)
{
/*
配置は
0 2
3 1
*/
int[] agentsX = new int[4];
int[] agentsY = new int[4];
agentsX[0] = agentsX[3] = rand.Next(1, BoardWidth / 2 - 1);
agentsY[0] = agentsY[2] = rand.Next(1, BoardHeight / 2 - 1);
agentsX[2] = agentsX[1] = BoardWidth - 1 - agentsX[0];
agentsY[3] = agentsY[1] = BoardHeight - 1 - agentsY[0];
for (int i = 0; i < Constants.AgentsNum; i++)
{
Agents[i].playerNum = (i / Constants.PlayersNum);
Agents[i].Point = new Point(agentsX[i], agentsY[i]);
CellData[agentsX[i], agentsY[i]].AreaState_ =
i / Constants.PlayersNum == 0 ? TeamColor.Area1P : TeamColor.Area2P;
CellData[agentsX[i], agentsY[i]].AgentState =
i / Constants.PlayersNum == 0 ? TeamColor.Area1P : TeamColor.Area2P;
}
}
else
{
var _Agents = settings.QCAgent;
var posState = QRCodeReader.AgentPositioningState.Horizontal;
if (QRCodeReader.EnemyAgentSelectDialog.ShowDialog(out QRCodeReader.AgentPositioningState result, settings) == true)
posState = result;
_Agents[2] = new Agent();
_Agents[3] = new Agent();
switch(posState)
{
case QRCodeReader.AgentPositioningState.Horizontal:
_Agents[2].Point = new Point(_Agents[0].Point.X, settings.BoardHeight - 1 - _Agents[0].Point.Y);
_Agents[3].Point = new Point(_Agents[1].Point.X, settings.BoardHeight - 1 - _Agents[1].Point.Y);
break;
case QRCodeReader.AgentPositioningState.Vertical:
_Agents[2].Point = new Point(settings.BoardWidth - 1 - _Agents[0].Point.X, _Agents[0].Point.Y);
_Agents[3].Point = new Point(settings.BoardWidth - 1 - _Agents[1].Point.X, _Agents[1].Point.Y);
break;
}
Agents = _Agents;
for (int i = 0; i < Agents.Length; ++i)
{
Agents[i].playerNum = i / Constants.PlayersNum;
CellData[Agents[i].Point.X, Agents[i].Point.Y].AreaState_ =
i / Constants.PlayersNum == 0 ? TeamColor.Area1P : TeamColor.Area2P;
}
}
}
}
}
| 39.185185 | 132 | 0.486767 | [
"MIT"
] | mct-procon/procon2018-Interface | GameInterface/GameInterface/GameData.cs | 7,538 | C# |
#if UNITY_EDITOR || UNITY_SWITCH
using System;
using System.Runtime.InteropServices;
using UnityEngine.Experimental.Input.Controls;
using UnityEngine.Experimental.Input.Layouts;
using UnityEngine.Experimental.Input.LowLevel;
using UnityEngine.Experimental.Input.Plugins.Switch.LowLevel;
using UnityEngine.Experimental.Input.Utilities;
////TODO: Haptics support (!!)
////REVIEW: The Switch controller can be used to point at things; can we somehow help leverage that?
namespace UnityEngine.Experimental.Input.Plugins.Switch.LowLevel
{
/// <summary>
/// Structure of HID input reports for Switch NPad controllers.
/// </summary>
/// <seealso href="http://en-americas-support.nintendo.com/app/answers/detail/a_id/22634/~/joy-con-controller-diagram"/>
[StructLayout(LayoutKind.Explicit, Size = 60)]
public struct NPadInputState : IInputStateTypeInfo
{
public FourCC GetFormat()
{
return new FourCC('N', 'P', 'A', 'D');
}
[InputControl(name = "dpad")]
[InputControl(name = "buttonNorth", displayName = "X", bit = (uint)Button.North)]
[InputControl(name = "buttonSouth", displayName = "B", bit = (uint)Button.South, usage = "Back")]
[InputControl(name = "buttonWest", displayName = "Y", bit = (uint)Button.West, usage = "SecondaryAction")]
[InputControl(name = "buttonEast", displayName = "A", bit = (uint)Button.East, usage = "PrimaryAction")]
[InputControl(name = "leftStickPress", displayName = "Left Stick", bit = (uint)Button.StickL)]
[InputControl(name = "rightStickPress", displayName = "Right Stick", bit = (uint)Button.StickR)]
[InputControl(name = "leftShoulder", displayName = "L", bit = (uint)Button.L)]
[InputControl(name = "rightShoulder", displayName = "R", bit = (uint)Button.R)]
[InputControl(name = "leftTrigger", displayName = "ZL", format = "BIT", bit = (uint)Button.ZL)]
[InputControl(name = "rightTrigger", displayName = "ZR", format = "BIT", bit = (uint)Button.ZR)]
[InputControl(name = "start", displayName = "Plus", bit = (uint)Button.Plus, usage = "Menu")]
[InputControl(name = "select", displayName = "Minus", bit = (uint)Button.Minus)]
[InputControl(name = "leftSL", displayName = "SL (Left)", layout = "Button", bit = (uint)Button.LSL)]
[InputControl(name = "leftSR", displayName = "SR (Left)", layout = "Button", bit = (uint)Button.LSR)]
[InputControl(name = "rightSL", displayName = "SL (Right)", layout = "Button", bit = (uint)Button.RSL)]
[InputControl(name = "rightSR", displayName = "SR (Right)", layout = "Button", bit = (uint)Button.RSR)]
[FieldOffset(0)]
public uint buttons;
[FieldOffset(4)]
public Vector2 leftStick;
[FieldOffset(12)]
public Vector2 rightStick;
[InputControl(name = "acceleration")]
[FieldOffset(20)]
public Vector3 acceleration;
[InputControl(name = "attitude")]
[FieldOffset(32)]
public Quaternion attitude;
[InputControl(name = "angularVelocity")]
[FieldOffset(48)]
public Vector3 angularVelocity;
public float leftTrigger => ((buttons & (1 << (int)Button.ZL)) != 0) ? 1f : 0f;
public float rightTrigger => ((buttons & (1 << (int)Button.ZR)) != 0) ? 1f : 0f;
public enum Button
{
// Dpad buttons. Important to be first in the bitfield as we'll
// point the DpadControl to it.
// IMPORTANT: Order has to match what is expected by DpadControl.
Up,
Down,
Left,
Right,
North,
South,
West,
East,
StickL,
StickR,
L,
R,
ZL,
ZR,
Plus,
Minus,
LSL,
LSR,
RSL,
RSR,
X = North,
B = South,
Y = West,
A = East,
}
public NPadInputState WithButton(Button button, bool value = true)
{
var bit = (uint)1 << (int)button;
if (value)
buttons |= bit;
else
buttons &= ~bit;
return this;
}
}
/// <summary>
/// Switch output report sent as command to the backend.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NPadStatusReport : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC('N', 'P', 'D', 'S');
public const int kSize = InputDeviceCommand.kBaseCommandSize + 24;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 0)]
public NPad.NpadId npadId;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 1)]
public NPad.Orientation orientation;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 2)]
public short padding0;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 4)]
public NPad.NpadStyle styleMask;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 8)]
public int colorLeftMain;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 12)]
public int colorLeftSub;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 16)]
public int colorRightMain;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 20)]
public int colorRightSub;
public FourCC GetTypeStatic()
{
return Type;
}
public static NPadStatusReport Create()
{
return new NPadStatusReport
{
baseCommand = new InputDeviceCommand(Type, kSize),
};
}
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NPadControllerSupportCommand : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC('N', 'P', 'D', 'U');
public const int kSize = InputDeviceCommand.kBaseCommandSize + 8;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 0)]
public int command;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 4)]
public int option;
public enum Command : int
{
kShowUI,
kSetHorizontalLayout,
kStartSixAxisSensor,
kStopSixAxisSensor,
}
public FourCC GetTypeStatic()
{
return Type;
}
public static NPadControllerSupportCommand Create(NPadControllerSupportCommand.Command _command, int _option = 0)
{
return new NPadControllerSupportCommand
{
baseCommand = new InputDeviceCommand(Type, kSize),
command = (int)_command,
option = _option,
};
}
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NpadDeviceIOCTLShowUI : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC("NSUI");
public const int kSize = InputDeviceCommand.kBaseCommandSize;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
public FourCC GetTypeStatic() { return Type; }
public static NpadDeviceIOCTLShowUI Create()
{
return new NpadDeviceIOCTLShowUI
{
baseCommand = new InputDeviceCommand(Type, kSize),
};
}
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NpadDeviceIOCTLSetOrientation : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC("NSOR");
public const int kSize = InputDeviceCommand.kBaseCommandSize + 1;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 0)]
public NPad.Orientation orientation;
public FourCC GetTypeStatic() { return Type; }
public static NpadDeviceIOCTLSetOrientation Create(NPad.Orientation _orientation)
{
return new NpadDeviceIOCTLSetOrientation
{
baseCommand = new InputDeviceCommand(Type, kSize),
orientation = _orientation,
};
}
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NpadDeviceIOCTLStartSixAxisSensor : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC("SXST");
public const int kSize = InputDeviceCommand.kBaseCommandSize;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
public FourCC GetTypeStatic() { return Type; }
public static NpadDeviceIOCTLStartSixAxisSensor Create()
{
return new NpadDeviceIOCTLStartSixAxisSensor
{
baseCommand = new InputDeviceCommand(Type, kSize),
};
}
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NpadDeviceIOCTLStopSixAxisSensor : IInputDeviceCommandInfo
{
public static FourCC Type => new FourCC("SXSP");
public const int kSize = InputDeviceCommand.kBaseCommandSize;
[FieldOffset(0)]
public InputDeviceCommand baseCommand;
public FourCC GetTypeStatic() { return Type; }
public static NpadDeviceIOCTLStopSixAxisSensor Create()
{
return new NpadDeviceIOCTLStopSixAxisSensor
{
baseCommand = new InputDeviceCommand(Type, kSize),
};
}
}
/// <summary>
/// Switch output report sent as command to backend.
/// </summary>
// IMPORTANT: Struct must match the NpadDeviceIOCTLOutputReport in native
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct NPadDeviceIOCTLOutputCommand : IInputDeviceCommandInfo
{
public static FourCC Type { get { return new FourCC('N', 'P', 'G', 'O'); } }
public const int kSize = InputDeviceCommand.kBaseCommandSize + 20;
public const float kDefaultFrequencyLow = 160.0f;
public const float kDefaultFrequencyHigh = 320.0f;
public enum NPadRumblePostion : byte
{
Left = 0x02,
Right = 0x04,
All = 0xFF,
None = 0x00,
}
[FieldOffset(0)] public InputDeviceCommand baseCommand;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 0)]
public byte positionFlags;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 4)]
public float amplitudeLow;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 8)]
public float frequencyLow;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 12)]
public float amplitudeHigh;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + 16)]
public float frequencyHigh;
public FourCC GetTypeStatic() { return Type; }
public static NPadDeviceIOCTLOutputCommand Create()
{
return new NPadDeviceIOCTLOutputCommand()
{
baseCommand = new InputDeviceCommand(Type, kSize),
positionFlags = (byte)NPadRumblePostion.None,
amplitudeLow = 0,
frequencyLow = kDefaultFrequencyLow,
amplitudeHigh = 0,
frequencyHigh = kDefaultFrequencyHigh
};
}
}
}
namespace UnityEngine.Experimental.Input.Plugins.Switch
{
/// <summary>
/// An NPad controller for Switch, which can be a Joy-Con.
/// </summary>
/// <seealso cref="NPadInputState"/>
[InputControlLayout(stateType = typeof(NPadInputState))]
public class NPad : Gamepad, INPadRumble
{
public ButtonControl leftSL { get; private set; }
public ButtonControl leftSR { get; private set; }
public ButtonControl rightSL { get; private set; }
public ButtonControl rightSR { get; private set; }
public Vector3Control acceleration { get; private set; }
public QuaternionControl attitude { get; private set; }
public Vector3Control angularVelocity { get; private set; }
public enum Orientation : byte
{
Vertical,
Horizontal,
Default = Vertical,
}
public enum NpadId : byte
{
No1 = 0x00,
No2 = 0x01,
No3 = 0x02,
No4 = 0x03,
No5 = 0x04,
No6 = 0x05,
No7 = 0x06,
No8 = 0x07,
Handheld = 0x20,
Debug = 0xF0,
Invalid = 0xFF,
}
//orientation matters for stick axes!!!!
//there's a touchpad and 90% of games don't support it
//each person could play with a different style
[Flags]
public enum NpadStyle
{
FullKey = 1 << 0,//separate;or pro controller;only one accel
Handheld = 1 << 1,//docked to switch
JoyDual = 1 << 2,//separate; one accel per joycon
JoyLeft = 1 << 3,//just one; orientation matters
JoyRight = 1 << 4,//just one; orientation matters
}
public struct JoyConColor
{
public Color32 Main;
public Color32 Sub;
}
public Orientation orientation
{
get
{
RefreshConfigurationIfNeeded();
return m_Orientation;
}
}
public NpadId npadId
{
get
{
RefreshConfigurationIfNeeded();
return m_NpadId;
}
}
public NpadStyle styleMask
{
get
{
RefreshConfigurationIfNeeded();
return m_StyleMask;
}
}
public JoyConColor leftControllerColor
{
get
{
RefreshConfigurationIfNeeded();
return m_LeftControllerColor;
}
}
public JoyConColor rightControllerColor
{
get
{
RefreshConfigurationIfNeeded();
return m_RightControllerColor;
}
}
private bool m_IsDirty;
private Orientation m_Orientation;
private NpadId m_NpadId = NpadId.Invalid;
private NpadStyle m_StyleMask;
private JoyConColor m_LeftControllerColor;
private JoyConColor m_RightControllerColor;
private struct NPadRumbleValues
{
public float? amplitudeLow;
public float? frequencyLow;
public float? amplitudeHigh;
public float? frequencyHigh;
public bool HasValues
{
get { return amplitudeLow.HasValue && frequencyLow.HasValue && amplitudeHigh.HasValue && frequencyHigh.HasValue; }
}
public void SetRumbleValues(float lowAmplitude, float lowFrequency, float highAmplitude, float highFrequency)
{
amplitudeLow = Mathf.Clamp01(lowAmplitude);
frequencyLow = lowFrequency;
amplitudeHigh = Mathf.Clamp01(highAmplitude);
frequencyHigh = highFrequency;
}
public void Reset()
{
amplitudeLow = null;
frequencyLow = null;
amplitudeHigh = null;
frequencyLow = null;
}
public void ApplyRumbleValues(ref NPadDeviceIOCTLOutputCommand cmd)
{
cmd.amplitudeLow = (float)amplitudeLow;
cmd.frequencyLow = (float)frequencyLow;
cmd.amplitudeHigh = (float)amplitudeHigh;
cmd.frequencyHigh = (float)frequencyHigh;
}
}
private NPadRumbleValues m_leftRumbleValues;
private NPadRumbleValues m_rightRumbleValues;
protected override void RefreshConfiguration()
{
base.RefreshConfiguration();
var command = NPadStatusReport.Create();
if (ExecuteCommand(ref command) > 0)
{
m_NpadId = command.npadId;
m_Orientation = command.orientation;
m_StyleMask = command.styleMask;
ReadNNColorIntoJoyConColor(ref m_LeftControllerColor, command.colorLeftMain, command.colorLeftSub);
ReadNNColorIntoJoyConColor(ref m_RightControllerColor, command.colorRightMain, command.colorRightSub);
}
}
// NOTE: This function should be static
public long SetOrientationToSingleJoyCon(Orientation _orientation)
{
var supportCommand = NpadDeviceIOCTLSetOrientation.Create(_orientation);
return ExecuteCommand(ref supportCommand);
}
public long StartSixAxisSensor()
{
var supportCommand = NpadDeviceIOCTLStartSixAxisSensor.Create();
return ExecuteCommand(ref supportCommand);
}
public long StopSixAxisSensor()
{
var supportCommand = NpadDeviceIOCTLStopSixAxisSensor.Create();
return ExecuteCommand(ref supportCommand);
}
protected override void FinishSetup(InputDeviceBuilder builder)
{
base.FinishSetup(builder);
leftSL = builder.GetControl<ButtonControl>(this, "leftSL");
leftSR = builder.GetControl<ButtonControl>(this, "leftSR");
rightSL = builder.GetControl<ButtonControl>(this, "rightSL");
rightSR = builder.GetControl<ButtonControl>(this, "rightSR");
acceleration = builder.GetControl<Vector3Control>(this, "acceleration");
attitude = builder.GetControl<QuaternionControl>(this, "attitude");
angularVelocity = builder.GetControl<Vector3Control>(this, "angularVelocity");
}
private static void ReadNNColorIntoJoyConColor(ref JoyConColor controllerColor, int mainColor, int subColor)
{
controllerColor.Main = ConvertNNColorToColor32(mainColor);
controllerColor.Sub = ConvertNNColorToColor32(subColor);
}
private static Color32 ConvertNNColorToColor32(int color)
{
return new Color32((byte)(color & 0xFF), (byte)((color >> 8) & 0xFF), (byte)((color >> 16) & 0xFF), (byte)((color >> 24) & 0xFF));
}
public override void PauseHaptics()
{
var cmd = NPadDeviceIOCTLOutputCommand.Create();
ExecuteCommand(ref cmd);
}
public override void ResetHaptics()
{
var cmd = NPadDeviceIOCTLOutputCommand.Create();
ExecuteCommand(ref cmd);
m_leftRumbleValues.Reset();
m_rightRumbleValues.Reset();
}
public override void ResumeHaptics()
{
if (m_leftRumbleValues.Equals(m_rightRumbleValues) && m_leftRumbleValues.HasValues)
{
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.All;
m_leftRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
else
{
if (m_leftRumbleValues.HasValues)
{
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.Left;
m_leftRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
if (m_rightRumbleValues.HasValues)
{
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.Right;
m_rightRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
}
}
/// <summary>
/// Set rummble intensity for all low and high frequency rumble motors
/// </summary>
/// <param name="lowFrequency">Low frequency motor's vibration intensity, 0..1 range</param>
/// <param name="highFrequency">High frequency motor's vibration intensity, 0..1 range</param>
public override void SetMotorSpeeds(float lowFrequency, float highFrequency)
{
SetMotorSpeeds(lowFrequency, NPadDeviceIOCTLOutputCommand.kDefaultFrequencyLow, highFrequency, NPadDeviceIOCTLOutputCommand.kDefaultFrequencyHigh);
}
/// <summary>
/// Set the intensity and vibration frequency for all low and high frequency rumble motors
/// </summary>
/// <param name="lowAmplitude">Low frequency motor's vibration intensity, 0..1 range</param>
/// <param name="lowFrequency">Low frequency motor's vibration frequency in Hz</param>
/// <param name="highAmplitude">High frequency motor's vibration intensity, 0..1 range</param>
/// <param name="highFrequency">High frequency motor's vibration frequency in Hz</param>
public void SetMotorSpeeds(float lowAmplitude, float lowFrequency, float highAmplitude, float highFrequency)
{
m_leftRumbleValues.SetRumbleValues(lowAmplitude, lowFrequency, highAmplitude, highFrequency);
m_rightRumbleValues.SetRumbleValues(lowAmplitude, lowFrequency, highAmplitude, highFrequency);
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.All;
m_leftRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
/// <summary>
/// Set the intensity and vibration frequency for the left low and high frequency rumble motors
/// </summary>
/// <param name="lowAmplitude">Low frequency motor's vibration intensity, 0..1 range</param>
/// <param name="lowFrequency">Low frequency motor's vibration frequency in Hz</param>
/// <param name="highAmplitude">High frequency motor's vibration intensity, 0..1 range</param>
/// <param name="highFrequency">High frequency motor's vibration frequency in Hz</param>
public void SetMotorSpeedLeft(float lowAmplitude, float lowFrequency, float highAmplitude, float highFrequency)
{
m_leftRumbleValues.SetRumbleValues(lowAmplitude, lowFrequency, highAmplitude, highFrequency);
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.Left;
m_leftRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
/// <summary>
/// Set the intensity and vibration frequency for the right low and high frequency rumble motors
/// </summary>
/// <param name="lowAmplitude">Low frequency motor's vibration intensity, 0..1 range</param>
/// <param name="lowFrequency">Low frequency motor's vibration frequency in Hz</param>
/// <param name="highAmplitude">High frequency motor's vibration intensity, 0..1 range</param>
/// <param name="highFrequency">High frequency motor's vibration frequency in Hz</param>
public void SetMotorSpeedRight(float lowAmplitude, float lowFrequency, float highAmplitude, float highFrequency)
{
m_rightRumbleValues.SetRumbleValues(lowAmplitude, lowFrequency, highAmplitude, highFrequency);
var cmd = NPadDeviceIOCTLOutputCommand.Create();
cmd.positionFlags = (byte)NPadDeviceIOCTLOutputCommand.NPadRumblePostion.Right;
m_rightRumbleValues.ApplyRumbleValues(ref cmd);
ExecuteCommand(ref cmd);
}
}
}
#endif // UNITY_EDITOR || UNITY_SWITCH
| 37.073846 | 159 | 0.607312 | [
"MIT"
] | ToadsworthLP/Millenium | Library/PackageCache/com.unity.inputsystem@0.2.6-preview/InputSystem/Plugins/Switch/NPad.cs | 24,098 | C# |
using System;
using System.Collections.Generic;
using Android.Runtime;
using Java.Interop;
namespace Xamarin.Test {
// Metadata.xml XPath class reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']"
[global::Android.Runtime.Register ("xamarin/test/SomeObject", DoNotGenerateAcw=true)]
public partial class SomeObject : global::Java.Lang.Object {
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myStrings']"
[Register ("myStrings")]
public IList<string> MyStrings {
get {
const string __id = "myStrings.[Ljava/lang/String;";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<string>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "myStrings.[Ljava/lang/String;";
IntPtr native_value = global::Android.Runtime.JavaArray<string>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myInts']"
[Register ("myInts")]
public IList<int> MyInts {
get {
const string __id = "myInts.[I";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<int>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "myInts.[I";
IntPtr native_value = global::Android.Runtime.JavaArray<int>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mybools']"
[Register ("mybools")]
public IList<bool> Mybools {
get {
const string __id = "mybools.[Z";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<bool>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "mybools.[Z";
IntPtr native_value = global::Android.Runtime.JavaArray<bool>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myObjects']"
[Register ("myObjects")]
public IList<Java.Lang.Object> MyObjects {
get {
const string __id = "myObjects.[Ljava/lang/Object;";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<global::Java.Lang.Object>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "myObjects.[Ljava/lang/Object;";
IntPtr native_value = global::Android.Runtime.JavaArray<global::Java.Lang.Object>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myfloats']"
[Register ("myfloats")]
public IList<float> Myfloats {
get {
const string __id = "myfloats.[F";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<float>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "myfloats.[F";
IntPtr native_value = global::Android.Runtime.JavaArray<float>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mydoubles']"
[Register ("mydoubles")]
public IList<double> Mydoubles {
get {
const string __id = "mydoubles.[D";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<double>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "mydoubles.[D";
IntPtr native_value = global::Android.Runtime.JavaArray<double>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mylongs']"
[Register ("mylongs")]
public IList<long> Mylongs {
get {
const string __id = "mylongs.[J";
var __v = _members.InstanceFields.GetObjectValue (__id, this);
return global::Android.Runtime.JavaArray<long>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef);
}
set {
const string __id = "mylongs.[J";
IntPtr native_value = global::Android.Runtime.JavaArray<long>.ToLocalJniHandle (value);
try {
_members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value));
} finally {
global::Android.Runtime.JNIEnv.DeleteLocalRef (native_value);
}
}
}
static readonly JniPeerMembers _members = new JniPeerMembers ("xamarin/test/SomeObject", typeof (SomeObject));
internal static new IntPtr class_ref {
get { return _members.JniPeerType.PeerReference.Handle; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
public override global::Java.Interop.JniPeerMembers JniPeerMembers {
get { return _members; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
protected override IntPtr ThresholdClass {
get { return _members.JniPeerType.PeerReference.Handle; }
}
[global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)]
[global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)]
protected override global::System.Type ThresholdType {
get { return _members.ManagedPeerType; }
}
protected SomeObject (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer)
{
}
}
}
| 36.94359 | 135 | 0.722238 | [
"MIT"
] | dphamsafetrust/java.interop | tests/generator-Tests/expected.ji/Arrays/Xamarin.Test.SomeObject.cs | 7,204 | C# |
using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Windows.Forms;
using Server;
using VenomRAT_HVNC.Server.Helper;
namespace VenomRAT_HVNC.Server.Forms
{
public partial class FormCertificate : Form
{
public FormCertificate()
{
this.InitializeComponent();
}
private void FormCertificate_Load(object sender, EventArgs e)
{
try
{
string text = Application.StartupPath + "\\BackupCertificate.zip";
if (File.Exists(text))
{
MessageBox.Show(this, "Found a zip backup, Extracting (BackupCertificate.zip)", "Certificate backup", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
ZipFile.ExtractToDirectory(text, Application.StartupPath);
Settings.ServerCertificate = new X509Certificate2(Settings.CertificatePath);
base.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Certificate", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private async void Button1_Click(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrWhiteSpace(this.textBox1.Text))
{
this.button1.Text = "Please wait";
this.button1.Enabled = false;
this.textBox1.Enabled = false;
await Task.Run(delegate ()
{
try
{
string text = Application.StartupPath + "\\BackupCertificate.zip";
Settings.ServerCertificate = CreateCertificate.CreateCertificateAuthority(this.textBox1.Text, 1024);
File.WriteAllBytes(Settings.CertificatePath, Settings.ServerCertificate.Export(X509ContentType.Pfx));
Program.form1.listView1.BeginInvoke(new MethodInvoker(delegate ()
{
MessageBox.Show(this, "Do not forget to Save The BackupCertificate.zip", "Certificate", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
base.Close();
}));
}
catch (Exception ex2)
{
Exception ex3 = ex2;
Exception ex = ex3;
Program.form1.listView1.BeginInvoke(new MethodInvoker(delegate ()
{
MessageBox.Show(this, ex.Message, "Certificate", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.button1.Text = "OK";
this.button1.Enabled = true;
this.textBox1.Enabled = true;
}));
}
});
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Certificate", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.button1.Text = "Ok";
this.button1.Enabled = true;
}
}
}
}
| 41.5 | 169 | 0.500861 | [
"Unlicense"
] | GitPlaya/Venom5-HVNC-Rat | VenomRAT_HVNC/Server/Forms/FormCertificate.cs | 3,486 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System.Runtime.Serialization;
namespace Microsoft.WindowsAzurePack.Samples.DataContracts
{
/// <summary>
/// Type of a resource provider.
/// </summary>
[DataContract(Namespace = "http://schemas.microsoft.com/windowsazure")]
public enum ResourceProviderType
{
/// <summary>
/// Standard type
/// </summary>
[EnumMember]
Standard = 0,
/// <summary>
/// Usage service type
/// </summary>
[EnumMember]
UsageProvider,
/// <summary>
/// The cloud service provider
/// </summary>
[EnumMember]
CloudServiceProvider,
}
}
| 25.294118 | 75 | 0.488372 | [
"MIT"
] | Bhaskers-Blu-Org2/Phoenix | CMP/CmpWap/ApiClients/DataContracts/ResourceProviderType.cs | 862 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Edge.Hub.Core.Test
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Edge.Hub.CloudProxy;
using Microsoft.Azure.Devices.Edge.Hub.Core.Device;
using Microsoft.Azure.Devices.Edge.Hub.Core.Identity;
using Microsoft.Azure.Devices.Edge.Hub.Core.Routing;
using Microsoft.Azure.Devices.Edge.Storage;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Test.Common;
using Microsoft.Azure.Devices.Routing.Core;
using Microsoft.Azure.Devices.Shared;
using Moq;
using Xunit;
using Constants = Microsoft.Azure.Devices.Edge.Hub.Core.Constants;
using IMessage = Microsoft.Azure.Devices.Edge.Hub.Core.IMessage;
[Unit]
public class EdgeHubConnectionTest
{
[Theory]
[InlineData("1.0", null)]
[InlineData("1.1", null)]
[InlineData("1.2", null)]
[InlineData("1.3", null)]
[InlineData("1", typeof(ArgumentException))]
[InlineData("", typeof(ArgumentException))]
[InlineData(null, typeof(ArgumentException))]
[InlineData("0.1", typeof(InvalidOperationException))]
[InlineData("2.0", typeof(InvalidOperationException))]
[InlineData("2.1", typeof(InvalidOperationException))]
public void SchemaVersionCheckTest(string schemaVersion, Type expectedException)
{
if (expectedException != null)
{
Assert.Throws(expectedException, () => EdgeHubConnection.ValidateSchemaVersion(schemaVersion));
}
else
{
EdgeHubConnection.ValidateSchemaVersion(schemaVersion);
}
}
[Fact]
public async Task HandleMethodInvocationTest()
{
// Arrange
var edgeHubIdentity = Mock.Of<IModuleIdentity>();
var twinManager = Mock.Of<ITwinManager>();
var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>());
var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>();
var twinMessageConverter = Mock.Of<Core.IMessageConverter<Shared.Twin>>();
var versionInfo = new VersionInfo("1.0", "1", "123");
var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>();
deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask);
var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object);
string correlationId = Guid.NewGuid().ToString();
var requestPayload = new
{
deviceIds = new[]
{
"d1",
"d2"
}
};
byte[] requestBytes = requestPayload.ToBytes();
var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
// Act
DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest);
// Assert
Assert.NotNull(directMethodResponse);
Assert.Equal(HttpStatusCode.OK, directMethodResponse.HttpStatusCode);
}
[Fact]
public async Task HandleMethodInvocationBadInputTest()
{
// Arrange
var edgeHubIdentity = Mock.Of<IModuleIdentity>();
var twinManager = Mock.Of<ITwinManager>();
var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>());
var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>();
var twinMessageConverter = Mock.Of<Core.IMessageConverter<Shared.Twin>>();
var versionInfo = new VersionInfo("1.0", "1", "123");
var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>();
deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask);
var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object);
string correlationId = Guid.NewGuid().ToString();
var requestPayload = new[]
{
"d1",
"d2"
};
byte[] requestBytes = requestPayload.ToBytes();
var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
// Act
DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest);
// Assert
Assert.NotNull(directMethodResponse);
Assert.Equal(HttpStatusCode.BadRequest, directMethodResponse.HttpStatusCode);
}
[Fact]
public async Task HandleMethodInvocationServerErrorTest()
{
// Arrange
var edgeHubIdentity = Mock.Of<IModuleIdentity>();
var twinManager = Mock.Of<ITwinManager>();
var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>());
var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>();
var twinMessageConverter = Mock.Of<Core.IMessageConverter<Shared.Twin>>();
var versionInfo = new VersionInfo("1.0", "1", "123");
var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>();
deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception("Foo"));
var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object);
string correlationId = Guid.NewGuid().ToString();
var requestPayload = new
{
deviceIds = new[]
{
"d1",
"d2"
}
};
byte[] requestBytes = requestPayload.ToBytes();
var directMethodRequest = new DirectMethodRequest(correlationId, Constants.ServiceIdentityRefreshMethodName, requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
// Act
DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest);
// Assert
Assert.NotNull(directMethodResponse);
Assert.Equal(HttpStatusCode.InternalServerError, directMethodResponse.HttpStatusCode);
}
[Fact]
public async Task HandleMethodInvocationInvalidMethodNameTest()
{
// Arrange
var edgeHubIdentity = Mock.Of<IModuleIdentity>();
var twinManager = Mock.Of<ITwinManager>();
var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>());
var twinCollectionMessageConverter = Mock.Of<Core.IMessageConverter<TwinCollection>>();
var twinMessageConverter = Mock.Of<Core.IMessageConverter<Shared.Twin>>();
var versionInfo = new VersionInfo("1.0", "1", "123");
var deviceScopeIdentitiesCache = new Mock<IDeviceScopeIdentitiesCache>();
deviceScopeIdentitiesCache.Setup(d => d.RefreshServiceIdentities(It.IsAny<IEnumerable<string>>())).Returns(Task.CompletedTask);
var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache.Object);
string correlationId = Guid.NewGuid().ToString();
var requestPayload = new
{
deviceIds = new[]
{
"d1",
"d2"
}
};
byte[] requestBytes = requestPayload.ToBytes();
var directMethodRequest = new DirectMethodRequest(correlationId, "ping", requestBytes, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
// Act
DirectMethodResponse directMethodResponse = await edgeHubConnection.HandleMethodInvocation(directMethodRequest);
// Assert
Assert.NotNull(directMethodResponse);
Assert.Equal(HttpStatusCode.NotFound, directMethodResponse.HttpStatusCode);
}
[Fact]
public async Task HandleDeviceConnectedDisconnectedEvents()
{
// Arrange
var edgeHubIdentity = Mock.Of<IModuleIdentity>(i => i.Id == "edgeD1/$edgeHub");
var twinManager = Mock.Of<ITwinManager>();
var routeFactory = new EdgeRouteFactory(Mock.Of<IEndpointFactory>());
var twinCollectionMessageConverter = new TwinCollectionMessageConverter();
var twinMessageConverter = new TwinMessageConverter();
var versionInfo = new VersionInfo("1.0", "1", "123");
var deviceScopeIdentitiesCache = Mock.Of<IDeviceScopeIdentitiesCache>();
var edgeHubConnection = new EdgeHubConnection(edgeHubIdentity, twinManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, deviceScopeIdentitiesCache);
Mock.Get(twinManager).Setup(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>())).Returns(Task.CompletedTask);
// Act
edgeHubConnection.DeviceConnected(this, Mock.Of<IIdentity>(i => i.Id == "d1"));
edgeHubConnection.DeviceConnected(this, Mock.Of<IIdentity>(i => i.Id == "edgeD1/$edgeHub"));
// Assert
await Task.Delay(TimeSpan.FromSeconds(2));
Mock.Get(twinManager).Verify(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>()), Times.Once);
// Act
edgeHubConnection.DeviceDisconnected(this, Mock.Of<IIdentity>(i => i.Id == "d1"));
edgeHubConnection.DeviceDisconnected(this, Mock.Of<IIdentity>(i => i.Id == "edgeD1/$edgeHub"));
// Assert
await Task.Delay(TimeSpan.FromSeconds(2));
Mock.Get(twinManager).Verify(t => t.UpdateReportedPropertiesAsync(It.IsAny<string>(), It.IsAny<IMessage>()), Times.Exactly(2));
}
}
}
| 50.658879 | 204 | 0.6516 | [
"MIT"
] | CIPop/iotedge | edge-hub/test/Microsoft.Azure.Devices.Edge.Hub.Core.Test/EdgeHubConnectionTest.cs | 10,841 | C# |
namespace Correlation.Contexts
{
/// <summary>
/// Class that contains information about correlation context.
/// </summary>
public sealed class CorrelationContext
{
/// <summary>
/// Create instance of <see cref="CorrelationContext" />.
/// </summary>
internal CorrelationContext() { }
/// <summary>
/// Unique identifier of current correlation context.
/// </summary>
public string Id { get; set; }
}
}
| 26.789474 | 67 | 0.561886 | [
"MIT"
] | DoctorOnline/Correlation | Correlation/Contexts/CorrelationContext.cs | 511 | C# |
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.RDS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.RDS.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for SubnetAlreadyInUseException operation
/// </summary>
public class SubnetAlreadyInUseExceptionUnmarshaller : IErrorResponseUnmarshaller<SubnetAlreadyInUseException, XmlUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public SubnetAlreadyInUseException Unmarshall(XmlUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public SubnetAlreadyInUseException Unmarshall(XmlUnmarshallerContext context, ErrorResponse errorResponse)
{
SubnetAlreadyInUseException response = new SubnetAlreadyInUseException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
}
}
return response;
}
private static SubnetAlreadyInUseExceptionUnmarshaller _instance = new SubnetAlreadyInUseExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SubnetAlreadyInUseExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.534091 | 138 | 0.651743 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/SubnetAlreadyInUseExceptionUnmarshaller.cs | 3,127 | C# |
/* Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBApi;
namespace IB.messages
{
class AccountUpdateMultiMessage
{
private int reqId;
private string account;
private string modelCode;
private string key;
private string value;
private string currency;
public AccountUpdateMultiMessage(int reqId, string account, string modelCode, string key, string value, string currency)
{
Account = account;
ModelCode = modelCode;
Key = key;
Value = value;
Currency = currency;
}
public int ReqId
{
get { return reqId; }
set { reqId = value; }
}
public string Account
{
get { return account; }
set { account = value; }
}
public string ModelCode
{
get { return modelCode; }
set { modelCode = value; }
}
public string Key
{
get { return key; }
set { key = value; }
}
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public string Currency
{
get { return currency; }
set { currency = value; }
}
}
}
| 24.074627 | 128 | 0.531308 | [
"MIT"
] | ryanclouser/ibdata | IBData/messages/AccountUpdateMultiMessage.cs | 1,615 | C# |
using System;
namespace Stockpile.Public.Sdk.Models
{
public class StockKey
{
public Guid StockId { get; set; }
public string Key { get; set; }
}
} | 17.7 | 41 | 0.60452 | [
"MIT"
] | aluitink/stockpile | Stockpile.Public.Sdk/Models/StockKey.cs | 179 | 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 Microsoft.Diagnostics.NETCore.Client;
using Microsoft.Internal.Common.Utils;
using Microsoft.Tools.Common;
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Binding;
using System.CommandLine.Rendering;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.Tools.Trace
{
internal static class CollectCommandHandler
{
delegate Task<int> CollectDelegate(CancellationToken ct, IConsole console, int processId, FileInfo output, uint buffersize, string providers, string profile, TraceFileFormat format, TimeSpan duration, string clrevents, string clreventlevel, string name);
/// <summary>
/// Collects a diagnostic trace from a currently running process.
/// </summary>
/// <param name="ct">The cancellation token</param>
/// <param name="console"></param>
/// <param name="processId">The process to collect the trace from.</param>
/// <param name="name">The name of process to collect the trace from.</param>
/// <param name="output">The output path for the collected trace data.</param>
/// <param name="buffersize">Sets the size of the in-memory circular buffer in megabytes.</param>
/// <param name="providers">A list of EventPipe providers to be enabled. This is in the form 'Provider[,Provider]', where Provider is in the form: 'KnownProviderName[:Flags[:Level][:KeyValueArgs]]', and KeyValueArgs is in the form: '[key1=value1][;key2=value2]'</param>
/// <param name="profile">A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly.</param>
/// <param name="format">The desired format of the created trace file.</param>
/// <param name="duration">The duration of trace to be taken. </param>
/// <param name="clrevents">A list of CLR events to be emitted.</param>
/// <param name="clreventlevel">The verbosity level of CLR events</param>
/// <returns></returns>
private static async Task<int> Collect(CancellationToken ct, IConsole console, int processId, FileInfo output, uint buffersize, string providers, string profile, TraceFileFormat format, TimeSpan duration, string clrevents, string clreventlevel, string name)
{
try
{
Debug.Assert(output != null);
Debug.Assert(profile != null);
// Either processName or processId has to be specified.
if (name != null)
{
if (processId != 0)
{
Console.WriteLine("Can only specify either --name or --process-id option.");
return ErrorCodes.ArgumentError;
}
processId = CommandUtils.FindProcessIdWithName(name);
if (processId < 0)
{
return ErrorCodes.ArgumentError;
}
}
if (processId < 0)
{
Console.Error.WriteLine("Process ID should not be negative.");
return ErrorCodes.ArgumentError;
}
else if (processId == 0)
{
Console.Error.WriteLine("--process-id is required");
return ErrorCodes.ArgumentError;
}
if (profile.Length == 0 && providers.Length == 0 && clrevents.Length == 0)
{
Console.Out.WriteLine("No profile or providers specified, defaulting to trace profile 'cpu-sampling'");
profile = "cpu-sampling";
}
Dictionary<string, string> enabledBy = new Dictionary<string, string>();
var providerCollection = Extensions.ToProviders(providers);
foreach (EventPipeProvider providerCollectionProvider in providerCollection)
{
enabledBy[providerCollectionProvider.Name] = "--providers ";
}
if (profile.Length != 0)
{
var selectedProfile = ListProfilesCommandHandler.DotNETRuntimeProfiles
.FirstOrDefault(p => p.Name.Equals(profile, StringComparison.OrdinalIgnoreCase));
if (selectedProfile == null)
{
Console.Error.WriteLine($"Invalid profile name: {profile}");
return ErrorCodes.ArgumentError;
}
Profile.MergeProfileAndProviders(selectedProfile, providerCollection, enabledBy);
}
// Parse --clrevents parameter
if (clrevents.Length != 0)
{
// Ignore --clrevents if CLR event provider was already specified via --profile or --providers command.
if (enabledBy.ContainsKey(Extensions.CLREventProviderName))
{
Console.WriteLine($"The argument --clrevents {clrevents} will be ignored because the CLR provider was configured via either --profile or --providers command.");
}
else
{
var clrProvider = Extensions.ToCLREventPipeProvider(clrevents, clreventlevel);
providerCollection.Add(clrProvider);
enabledBy[Extensions.CLREventProviderName] = "--clrevents";
}
}
if (providerCollection.Count <= 0)
{
Console.Error.WriteLine("No providers were specified to start a trace.");
return ErrorCodes.ArgumentError;
}
PrintProviders(providerCollection, enabledBy);
var process = Process.GetProcessById(processId);
var shouldExit = new ManualResetEvent(false);
var shouldStopAfterDuration = duration != default(TimeSpan);
var rundownRequested = false;
System.Timers.Timer durationTimer = null;
ct.Register(() => shouldExit.Set());
var diagnosticsClient = new DiagnosticsClient(processId);
using (VirtualTerminalMode vTermMode = VirtualTerminalMode.TryEnable())
{
EventPipeSession session = null;
try
{
session = diagnosticsClient.StartEventPipeSession(providerCollection, true, (int)buffersize);
}
catch (DiagnosticsClientException e)
{
Console.Error.WriteLine($"Unable to start a tracing session: {e.ToString()}");
}
if (session == null)
{
Console.Error.WriteLine("Unable to create session.");
return ErrorCodes.SessionCreationError;
}
if (shouldStopAfterDuration)
{
durationTimer = new System.Timers.Timer(duration.TotalMilliseconds);
durationTimer.Elapsed += (s, e) => shouldExit.Set();
durationTimer.AutoReset = false;
}
var stopwatch = new Stopwatch();
durationTimer?.Start();
stopwatch.Start();
LineRewriter rewriter = null;
using (var fs = new FileStream(output.FullName, FileMode.Create, FileAccess.Write))
{
Console.Out.WriteLine($"Process : {process.MainModule.FileName}");
Console.Out.WriteLine($"Output File : {fs.Name}");
if (shouldStopAfterDuration)
Console.Out.WriteLine($"Trace Duration : {duration.ToString(@"dd\:hh\:mm\:ss")}");
Console.Out.WriteLine("\n\n");
var fileInfo = new FileInfo(output.FullName);
Task copyTask = session.EventStream.CopyToAsync(fs).ContinueWith((task) => shouldExit.Set());
if (!Console.IsOutputRedirected)
{
rewriter = new LineRewriter { LineToClear = Console.CursorTop -1 };
Console.CursorVisible = false;
}
Action printStatus = () =>
{
if (!Console.IsOutputRedirected)
{
rewriter?.RewriteConsoleLine();
fileInfo.Refresh();
Console.Out.WriteLine($"[{stopwatch.Elapsed.ToString(@"dd\:hh\:mm\:ss")}]\tRecording trace {GetSize(fileInfo.Length)}");
Console.Out.WriteLine("Press <Enter> or <Ctrl+C> to exit...");
}
if (rundownRequested)
Console.Out.WriteLine("Stopping the trace. This may take up to minutes depending on the application being traced.");
};
while (!shouldExit.WaitOne(100) && !(!Console.IsInputRedirected && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter))
printStatus();
// if the CopyToAsync ended early (target program exited, etc.), the we don't need to stop the session.
if (!copyTask.Wait(0))
{
// Behavior concerning Enter moving text in the terminal buffer when at the bottom of the buffer
// is different between Console/Terminals on Windows and Mac/Linux
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
!Console.IsOutputRedirected &&
rewriter != null &&
Math.Abs(Console.CursorTop - Console.BufferHeight) == 1)
{
rewriter.LineToClear--;
}
durationTimer?.Stop();
rundownRequested = true;
session.Stop();
do
{
printStatus();
} while (!copyTask.Wait(100));
}
}
Console.Out.WriteLine("\nTrace completed.");
if (format != TraceFileFormat.NetTrace)
TraceFileFormatConverter.ConvertToFormat(format, output.FullName);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
return ErrorCodes.TracingError;
}
finally
{
if (console.GetTerminal() != null)
Console.CursorVisible = true;
}
return await Task.FromResult(0);
}
private static void PrintProviders(IReadOnlyList<EventPipeProvider> providers, Dictionary<string, string> enabledBy)
{
Console.Out.WriteLine("");
Console.Out.Write(String.Format("{0, -40}","Provider Name")); // +4 is for the tab
Console.Out.Write(String.Format("{0, -20}","Keywords"));
Console.Out.Write(String.Format("{0, -20}","Level"));
Console.Out.Write("Enabled By\r\n");
foreach (var provider in providers)
{
Console.Out.WriteLine(String.Format("{0, -80}", $"{GetProviderDisplayString(provider)}") + $"{enabledBy[provider.Name]}");
}
Console.Out.WriteLine();
}
private static string GetProviderDisplayString(EventPipeProvider provider) =>
String.Format("{0, -40}", provider.Name) + String.Format("0x{0, -18}", $"{provider.Keywords:X16}") + String.Format("{0, -8}", provider.EventLevel.ToString() + $"({(int)provider.EventLevel})");
private static string GetSize(long length)
{
if (length > 1e9)
return String.Format("{0,-8} (GB)", $"{length / 1e9:0.00##}");
else if (length > 1e6)
return String.Format("{0,-8} (MB)", $"{length / 1e6:0.00##}");
else if (length > 1e3)
return String.Format("{0,-8} (KB)", $"{length / 1e3:0.00##}");
else
return String.Format("{0,-8} (B)", $"{length / 1.0:0.00##}");
}
public static Command CollectCommand() =>
new Command(
name: "collect",
description: "Collects a diagnostic trace from a currently running process")
{
// Handler
HandlerDescriptor.FromDelegate((CollectDelegate)Collect).GetCommandHandler(),
// Options
CommonOptions.ProcessIdOption(),
CircularBufferOption(),
OutputPathOption(),
ProvidersOption(),
ProfileOption(),
CommonOptions.FormatOption(),
DurationOption(),
CLREventsOption(),
CLREventLevelOption(),
CommonOptions.NameOption()
};
private static uint DefaultCircularBufferSizeInMB() => 256;
private static Option CircularBufferOption() =>
new Option(
alias: "--buffersize",
description: $"Sets the size of the in-memory circular buffer in megabytes. Default {DefaultCircularBufferSizeInMB()} MB.")
{
Argument = new Argument<uint>(name: "size", getDefaultValue: DefaultCircularBufferSizeInMB)
};
public static string DefaultTraceName => "trace.nettrace";
private static Option OutputPathOption() =>
new Option(
aliases: new[] { "-o", "--output" },
description: $"The output path for the collected trace data. If not specified it defaults to '{DefaultTraceName}'.")
{
Argument = new Argument<FileInfo>(name: "trace-file-path", getDefaultValue: () => new FileInfo(DefaultTraceName))
};
private static Option ProvidersOption() =>
new Option(
alias: "--providers",
description: @"A list of EventPipe providers to be enabled. This is in the form 'Provider[,Provider]', where Provider is in the form: 'KnownProviderName[:Flags[:Level][:KeyValueArgs]]', and KeyValueArgs is in the form: '[key1=value1][;key2=value2]'. These providers are in addition to any providers implied by the --profile argument. If there is any discrepancy for a particular provider, the configuration here takes precedence over the implicit configuration from the profile.")
{
Argument = new Argument<string>(name: "list-of-comma-separated-providers", getDefaultValue: () => string.Empty) // TODO: Can we specify an actual type?
};
private static Option ProfileOption() =>
new Option(
alias: "--profile",
description: @"A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly.")
{
Argument = new Argument<string>(name: "profile-name", getDefaultValue: () => string.Empty)
};
private static Option DurationOption() =>
new Option(
alias: "--duration",
description: @"When specified, will trace for the given timespan and then automatically stop the trace. Provided in the form of dd:hh:mm:ss.")
{
Argument = new Argument<TimeSpan>(name: "duration-timespan", getDefaultValue: () => default)
};
private static Option CLREventsOption() =>
new Option(
alias: "--clrevents",
description: @"List of CLR runtime events to emit.")
{
Argument = new Argument<string>(name: "clrevents", getDefaultValue: () => string.Empty)
};
private static Option CLREventLevelOption() =>
new Option(
alias: "--clreventlevel",
description: @"Verbosity of CLR events to be emitted.")
{
Argument = new Argument<string>(name: "clreventlevel", getDefaultValue: () => string.Empty)
};
}
}
| 48.946176 | 496 | 0.535942 | [
"MIT"
] | danmosemsft/diagnostics | src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs | 17,280 | C# |
<<<<<<< HEAD
<<<<<<< HEAD
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
=======
=======
>>>>>>> update form orginal repo
#region Copyright
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
// All Rights Reserved
#endregion
<<<<<<< HEAD
>>>>>>> Merges latest changes from release/9.4.x into development (#3178)
=======
>>>>>>> update form orginal repo
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Caching;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Security;
using DotNetNuke.Services.FileSystem;
namespace DotNetNuke.Providers.FolderProviders.Components
{
public abstract class BaseRemoteStorageProvider : FolderProvider
{
#region Private Members
private readonly string _encryptionKey = Host.GUID;
private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance;
#endregion
#region Private Methods
private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key)
{
var cacheKey = string.Format(ObjectCacheKey, folderMapping.FolderMappingID, key);
return CBO.GetCachedObject<IRemoteStorageItem>(new CacheItemArgs(cacheKey,
ObjectCacheTimeout,
CacheItemPriority.Default,
folderMapping.FolderMappingID),
c =>
{
var list = GetObjectList(folderMapping, key);
//return list.FirstOrDefault(i => i.Key == key);
return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));
});
}
#endregion
#region Protected Properties
protected virtual string FileNotFoundMessage
{
get { return String.Empty; }
}
protected virtual string ObjectCacheKey
{
get { return String.Empty; }
}
protected virtual int ObjectCacheTimeout
{
get { return 150; }
}
protected virtual string ListObjectsCacheKey
{
get { return String.Empty; }
}
protected virtual int ListObjectsCacheTimeout
{
get { return 300; }
}
#endregion
public override bool SupportsMappedPaths
{
get { return true; }
}
public override bool SupportsMoveFile
{
get { return false; }
}
public override bool SupportsMoveFolder
{
get { return true; }
}
#region Protected Methods
protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri);
protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri);
protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder);
protected static bool GetBooleanSetting(FolderMappingInfo folderMapping, string settingName)
{
return Boolean.Parse(folderMapping.FolderMappingSettings[settingName].ToString());
}
protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string settingName, int defaultValue)
{
int value;
if (int.TryParse(GetSetting(folderMapping, settingName), out value))
{
return value;
}
return defaultValue;
}
protected abstract Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri);
protected abstract IList<IRemoteStorageItem> GetObjectList(FolderMappingInfo folderMapping);
protected virtual IList<IRemoteStorageItem> GetObjectList(FolderMappingInfo folderMapping, string path)
{
return GetObjectList(folderMapping);
}
protected static string GetSetting(FolderMappingInfo folderMapping, string settingName)
{
Requires.NotNull(nameof(folderMapping), folderMapping);
Requires.NotNullOrEmpty(nameof(settingName), settingName);
return folderMapping.FolderMappingSettings[settingName]?.ToString();
}
protected abstract void MoveFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri);
protected abstract void MoveFolderInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri);
protected abstract void UpdateFileInternal(Stream stream, FolderMappingInfo folderMapping, string uri);
protected virtual IRemoteStorageItem GetStorageItem(FolderMappingInfo folderMapping, string key)
{
return GetStorageItemInternal(folderMapping, key);
}
#endregion
/// <summary>
/// Adds a new folder
/// </summary>
public override void AddFolder(string folderPath, FolderMappingInfo folderMapping)
{
AddFolder(folderPath, folderMapping, folderPath);
}
/// <summary>
/// Adds a new file to the specified folder.
/// </summary>
public override void AddFile(IFolderInfo folder, string fileName, Stream content)
{
Requires.NotNull("folder", folder);
Requires.NotNullOrEmpty("fileName", fileName);
Requires.NotNull("content", content);
UpdateFile(folder, fileName, content);
}
public virtual void ClearCache(int folderMappingId)
{
var cacheKey = String.Format(ListObjectsCacheKey, folderMappingId);
DataCache.RemoveCache(cacheKey);
//Clear cached objects
DataCache.ClearCache(String.Format(ObjectCacheKey, folderMappingId, String.Empty));
}
/// <summary>
/// Copies the specified file to the destination folder.
/// </summary>
public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping)
{
Requires.NotNull("folderPath", folderPath);
Requires.NotNullOrEmpty("fileName", fileName);
Requires.NotNull("newFolderPath", newFolderPath);
Requires.NotNull("folderMapping", folderMapping);
if (folderPath == newFolderPath) return;
CopyFileInternal(folderMapping, folderPath + fileName, newFolderPath + fileName);
}
/// <summary>
/// Deletes the specified file.
/// </summary>
public override void DeleteFile(IFileInfo file)
{
Requires.NotNull("file", file);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
DeleteFileInternal(folderMapping, folder.MappedPath + file.FileName);
}
/// <remarks>
/// Azure Storage doesn't support folders, but we need to delete the file added while creating the folder.
/// </remarks>
public override void DeleteFolder(IFolderInfo folder)
{
Requires.NotNull("folder", folder);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
DeleteFolderInternal(folderMapping, folder);
}
/// <summary>
/// Checks the existence of the specified file.
/// </summary>
public override bool FileExists(IFolderInfo folder, string fileName)
{
Requires.NotNull("folder", folder);
Requires.NotNullOrEmpty("fileName", fileName);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
var item = GetStorageItem(folderMapping, folder.MappedPath + fileName);
return (item != null);
}
/// <summary>
/// Checks the existence of the specified folder.
/// </summary>
public override bool FolderExists(string folderPath, FolderMappingInfo folderMapping)
{
Requires.NotNull("folderPath", folderPath);
Requires.NotNull("folderMapping", folderMapping);
//the root folder should always exist.
if (folderPath == "")
{
return true;
}
var list = GetObjectList(folderMapping, folderPath);
return list.Any(o => o.Key.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase));
}
/// <remarks>
/// Amazon doesn't support file attributes.
/// </remarks>
public override FileAttributes? GetFileAttributes(IFileInfo file)
{
return null;
}
/// <summary>
/// Gets the list of file names contained in the specified folder.
/// </summary>
public override string[] GetFiles(IFolderInfo folder)
{
Requires.NotNull("folder", folder);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
var list = GetObjectList(folderMapping, folder.MappedPath);
var mappedPath = folder.MappedPath;
//return (from i in list
// let f = i.Key
// let r = (!string.IsNullOrEmpty(mappedPath) ? f.Replace(mappedPath, "") : f)
// where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > mappedPath.Length && r.IndexOf("/", StringComparison.Ordinal) == -1
// select Path.GetFileName(f)).ToArray();
var pattern = "^" + mappedPath;
return (from i in list
let f = i.Key
let r = (!string.IsNullOrEmpty(mappedPath) ? Regex.Replace(f, pattern, "", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) : f)
where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > mappedPath.Length && r.IndexOf("/", StringComparison.Ordinal) == -1
select Path.GetFileName(f)).ToArray();
}
/// <summary>
/// Gets the file length.
/// </summary>
public override long GetFileSize(IFileInfo file)
{
Requires.NotNull("file", file);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
var item = GetStorageItem(folderMapping, folder.MappedPath + file.FileName);
if (item == null)
{
throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath);
}
return item.Size;
}
/// <summary>
/// Gets a file Stream of the specified file.
/// </summary>
public override Stream GetFileStream(IFileInfo file)
{
Requires.NotNull("file", file);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
return GetFileStreamInternal(folderMapping, folder.MappedPath + file.FileName);
}
/// <summary>
/// Gets a file Stream of the specified file.
/// </summary>
public override Stream GetFileStream(IFolderInfo folder, string fileName)
{
Requires.NotNull("folder", folder);
Requires.NotNullOrEmpty("fileName", fileName);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
return GetFileStreamInternal(folderMapping, folder.MappedPath + fileName);
}
/// <summary>
/// Gets the time when the specified file was last modified.
/// </summary>
public override DateTime GetLastModificationTime(IFileInfo file)
{
Requires.NotNull("file", file);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
var item = GetStorageItem(folderMapping, folder.MappedPath+file.FileName);
if (item == null)
{
throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath);
}
return item.LastModified;
}
/// <summary>
/// Gets the list of subfolders for the specified folder.
/// </summary>
public override IEnumerable<string> GetSubFolders(string folderPath, FolderMappingInfo folderMapping)
{
Requires.NotNull("folderPath", folderPath);
Requires.NotNull("folderMapping", folderMapping);
var list = GetObjectList(folderMapping, folderPath);
var pattern = "^" + Regex.Escape(folderPath);
return (from o in list
let f = o.Key
let r =
(!string.IsNullOrEmpty(folderPath)
? Regex.Replace(f, pattern, "", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2))
: f)
where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase)
&& f.Length > folderPath.Length
&& r.IndexOf("/", StringComparison.Ordinal) > -1
select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList();
//var mylist = (from o in list
// let f = o.Key
// let r = (!string.IsNullOrEmpty(folderPath) ? RegexUtils.GetCachedRegex(Regex.Escape(folderPath)).Replace(f, string.Empty, 1) : f)
// where f.StartsWith(folderPath)
// && f.Length > folderPath.Length
// && r.IndexOf("/", StringComparison.Ordinal) > -1
// select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList();
//return mylist;
}
/// <summary>
/// Indicates if the specified file is synchronized.
/// </summary>
/// <remarks>
/// For now, it returns false always until we find a better way to check if the file is synchronized.
/// </remarks>
public override bool IsInSync(IFileInfo file)
{
return Convert.ToInt32((file.LastModificationTime - GetLastModificationTime(file)).TotalSeconds) == 0;
}
/// <summary>
/// Moves the folder and files at the specified folder path to the new folder path.
/// </summary>
public override void MoveFolder(string folderPath, string newFolderPath, FolderMappingInfo folderMapping)
{
Requires.NotNullOrEmpty("folderPath", folderPath);
Requires.NotNullOrEmpty("newFolderPath", newFolderPath);
Requires.NotNull("folderMapping", folderMapping);
MoveFolderInternal(folderMapping, folderPath, newFolderPath);
}
/// <summary>
/// Renames the specified file using the new filename.
/// </summary>
public override void RenameFile(IFileInfo file, string newFileName)
{
Requires.NotNull("file", file);
Requires.NotNullOrEmpty("newFileName", newFileName);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
MoveFileInternal(folderMapping, folder.MappedPath + file.FileName, folder.MappedPath + newFileName);
}
/// <summary>
/// Renames the specified folder using the new foldername.
/// </summary>
public override void RenameFolder(IFolderInfo folder, string newFolderName)
{
Requires.NotNull("folder", folder);
Requires.NotNullOrEmpty("newFolderName", newFolderName);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
var mappedPath = folder.MappedPath;
if (mappedPath == folder.FolderName + "/" || mappedPath.EndsWith("/" + folder.FolderName + "/", StringComparison.Ordinal))
{
var newMappedPath =
PathUtils.Instance.FormatFolderPath(
mappedPath.Substring(0, mappedPath.LastIndexOf(folder.FolderName, StringComparison.Ordinal)) +
newFolderName);
MoveFolderInternal(folderMapping, mappedPath, newMappedPath);
}
}
/// <remarks>
/// No implementation needed because this provider doesn't support FileAttributes.
/// </remarks>
public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttributes)
{
}
/// <remarks>
/// Amazon doesn't support file attributes.
/// </remarks>
public override bool SupportsFileAttributes()
{
return false;
}
/// <summary>
/// Updates the content of the specified file. It creates it if it doesn't exist.
/// </summary>
public override void UpdateFile(IFileInfo file, Stream content)
{
Requires.NotNull("file", file);
Requires.NotNull("content", content);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
UpdateFileInternal(content, folderMapping, folder.MappedPath + file.FileName);
}
/// <summary>
/// Updates the content of the specified file. It creates it if it doesn't exist.
/// </summary>
public override void UpdateFile(IFolderInfo folder, string fileName, Stream content)
{
Requires.NotNull("folder", folder);
Requires.NotNullOrEmpty("fileName", fileName);
Requires.NotNull("content", content);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
UpdateFileInternal(content, folderMapping, folder.MappedPath + fileName);
}
public override string GetHashCode(IFileInfo file)
{
Requires.NotNull("file", file);
var folder = FolderManager.Instance.GetFolder(file.FolderId);
var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID);
var item = GetStorageItem(folderMapping, folder.MappedPath + file.FileName);
if (item == null)
{
throw new FileNotFoundException(FileNotFoundMessage, file.RelativePath);
}
return (item.Size == file.Size) ? item.HashCode : String.Empty;
}
public override string GetHashCode(IFileInfo file, Stream fileContent)
{
if (FileExists(FolderManager.Instance.GetFolder(file.FolderId), file.FileName))
{
return GetHashCode(file);
}
return String.Empty;
}
}
}
| 38.239006 | 170 | 0.615781 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs | 20,004 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
namespace Steeltoe.Security.DataProtection.CredHub
{
public class RsaGenerationRequest : CredHubGenerateRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="RsaGenerationRequest"/> class.
/// Use to request a new RSA Credential
/// </summary>
/// <param name="credentialName">Name of credential</param>
/// <param name="keyLength">Optional Key Length (default: 2048)</param>
/// <param name="overwriteMode">Overwrite existing credential (default: no-overwrite)</param>
public RsaGenerationRequest(string credentialName, CertificateKeyLength keyLength = CertificateKeyLength.Length_2048, OverwiteMode overwriteMode = OverwiteMode.converge)
{
Name = credentialName;
Type = CredentialType.RSA;
Parameters = new KeyParameters { KeyLength = keyLength };
Mode = overwriteMode;
}
}
} | 47.833333 | 177 | 0.680314 | [
"Apache-2.0"
] | Chatina73/steeltoe | src/Security/src/DataProtection.CredHubBase/Credentials/RSA/RsaGenerationRequest.cs | 1,150 | C# |
namespace UnityAtoms
{
public class BoolListener : GameEventListener<bool, BoolAction, BoolEvent, UnityBoolEvent> { }
}
| 24.8 | 98 | 0.774194 | [
"MIT"
] | AKOM-Studio/unity-atoms | Source/Bool/BoolListener.cs | 124 | C# |
// Mico C# reference source
// Copyright (c) 2020-2020 COMCREATE. All rights reserved.
using UnityEngine;
namespace Mico.Context
{
public abstract class MonoInstaller : MonoBehaviour, IInstaller
{
public abstract void InstallRegisters(DiContainer container);
}
} | 23.666667 | 69 | 0.735915 | [
"MIT"
] | ToshikiImagawa/MICO | Assets/Mico/Context/Scripts/Runtime/MonoInstaller.cs | 284 | C# |
using System;
using System.Security.Claims;
using DotNetCqs.DependencyInjection;
namespace DotNetCqs.MessageProcessor
{
public class InvokingHandlerEventArgs : EventArgs
{
public InvokingHandlerEventArgs(IHandlerScope scope, object handler, Message message)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Handler = handler;
Message = message ?? throw new ArgumentNullException(nameof(message));
}
/// <summary>
/// State that will be passed on to <see cref="HandlerInvokedEventArgs" />.
/// </summary>
/// <remarks>
/// Use it if you need to clean up something once the handler have been executed.
/// </remarks>
public object ApplicationState { get; set; }
public object Handler { get; }
/// <summary>
/// Messaging being processed
/// </summary>
public Message Message { get; }
/// <summary>
/// Scope used to locate handlers.
/// </summary>
public IHandlerScope Scope { get; set; }
public ClaimsPrincipal Principal { get; set; }
}
} | 31.210526 | 93 | 0.596965 | [
"Apache-2.0"
] | jgauffin/dotnetcqs | src/DotNetCqs/MessageProcessor/InvokingHandlerEventArgs.cs | 1,188 | C# |
using NUnit.Framework;
using DragonchainSDK.Credentials;
namespace DragonchainSDK.Tests
{
[TestFixture]
public class CredentialServiceUnitTests
{
[Test]
public void GetAuthorizationHeader_Test()
{
var credentialService = new CredentialService("testId", "key", "keyId");
Assert.AreEqual("DC1-HMAC-SHA256 keyId:8Bc+h0parZxGeMB9rYzzRUuNxxHSIjGqSD4W/635A9k=",
credentialService.GetAuthorizationHeader("GET", "/path", "timestamp", "application/json", ""));
Assert.AreEqual("DC1-HMAC-SHA256 keyId:PkVjUxWZr6ST4xh+JxYFZresaFhQbk8sggWqyWv/XkU=",
credentialService.GetAuthorizationHeader("POST", "/new_path", "timestamp", "application/json", "\"body\""));
}
}
} | 38.55 | 124 | 0.667964 | [
"Apache-2.0"
] | FitzyCodesThings/dragonchain-sdk-dotnetstandard | dragonchain-sdk.tests/CredentialServiceUnitTests.cs | 773 | C# |
namespace BeUtl.Commands;
public sealed class RemoveCommand<T> : IRecordableCommand
{
public RemoveCommand(IList<T> list, T item)
{
List = list;
Item = item;
Index = list.IndexOf(Item);
}
public IList<T> List { get; }
public T Item { get; }
public int Index { get; private set; }
public void Do()
{
Index = List.IndexOf(Item);
List.RemoveAt(Index);
}
public void Redo()
{
Do();
}
public void Undo()
{
List.Insert(Index, Item);
}
}
| 16.323529 | 57 | 0.538739 | [
"MIT"
] | YiB-PC/BeUtl | src/BeUtl.Core/Commands/RemoveCommand{T}.cs | 557 | 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 kafka-2018-11-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Kafka.Model
{
/// <summary>
///
/// </summary>
public partial class StateInfo
{
private string _code;
private string _message;
/// <summary>
/// Gets and sets the property Code.
/// </summary>
public string Code
{
get { return this._code; }
set { this._code = value; }
}
// Check to see if Code property is set
internal bool IsSetCode()
{
return this._code != null;
}
/// <summary>
/// Gets and sets the property Message.
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
// Check to see if Message property is set
internal bool IsSetMessage()
{
return this._message != null;
}
}
} | 25.957143 | 103 | 0.609796 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Kafka/Generated/Model/StateInfo.cs | 1,817 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CanvasColorSwitcher : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 16 | 52 | 0.634868 | [
"MIT"
] | Scott-Natter/ColorRunner | Assets/Level/CanvasColorSwitcher.cs | 306 | C# |
// Licensed to Elasticsearch B.V under
// one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Diagnostics;
using Elastic.Apm.Api;
using Elastic.Apm.Helpers;
using Elastic.Apm.Libraries.Ben.Demystifier;
using Elastic.Apm.Logging;
using Elastic.Apm.Model;
using Elastic.Apm.ServerInfo;
namespace Elastic.Apm.Filters
{
/// <summary>
/// Stack trace capturing itself happens on the application thread (in order to get the real stack trace).
/// This filter turns <see cref="Span.RawStackTrace" /> (which is a plain .NET System.Diagnostics.StackTrace instance) into
/// <see cref="Span.StackTrace" /> (which is the representation of the intake API stacktrace model).
/// This can be done on a non-application thread right before the span gets sent to the APM Server.
/// </summary>
internal class SpanStackTraceCapturingFilter
{
private readonly IApmServerInfo _apmServerInfo;
private readonly IApmLogger _logger;
public SpanStackTraceCapturingFilter(IApmLogger logger, IApmServerInfo apmServerInfo) =>
(_logger, _apmServerInfo) = (logger, apmServerInfo);
public ISpan Filter(ISpan iSpan)
{
if (!(iSpan is Span span)) return iSpan;
if (span.RawStackTrace == null) return span;
StackFrame[] trace;
try
{
// I saw EnhancedStackTrace throwing exceptions in some environments
// therefore we try-catch and fall back to a non-demystified call stack.
trace = new EnhancedStackTrace(span.RawStackTrace).GetFrames();
}
catch
{
trace = span.RawStackTrace.GetFrames();
}
span.StackTrace = StacktraceHelper.GenerateApmStackTrace(trace,
_logger,
span.Configuration, _apmServerInfo, $"Span `{span.Name}'");
return span;
}
}
}
| 32.571429 | 124 | 0.741228 | [
"Apache-2.0"
] | SebastienDegodez/apm-agent-dotnet | src/Elastic.Apm/Filters/SpanStackTraceCapturingFilter.cs | 1,824 | C# |
//
// Author:
// Aaron Bockover <abock@xamarin.com>
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using mshtml;
namespace Xamarin.CrossBrowser
{
[ComVisible (true)]
[ClassInterface (ClassInterfaceType.None)]
public partial class WrappedObject
{
public ScriptContext Context { get; }
internal readonly object ComObject;
internal WrappedObject (ScriptContext context, object comObject)
{
if (context == null)
throw new ArgumentNullException (nameof(context));
if (comObject == null)
throw new ArgumentNullException (nameof(comObject));
Context = context;
ComObject = comObject;
}
public override string ToString ()
{
try {
// do not call Invoke here to prevent introducing a possible
// cycle if anyone tries to add some CWL/ToString debugging.
return (string)ComObject.GetType ().InvokeMember (
"toString", BindingFlags.InvokeMethod, null, ComObject, null);
} catch {
return ComObject.ToString ();
}
}
public virtual void SetProperty (string property, object value)
{
// NOTE: COM does not support defining new properties on an object via
// InvokeMember (even with BindingFlags.PutDispProperty, etc.), so we
// must go through the JS bridge which performs the property set in
// JS code via a COM method invocation on the bridge. Sad.
//
// ComObject.GetType ().InvokeMember (property, BindingFlags.SetProperty,
// null, ComObject, new [] { ScriptContext.ToComObject (value) });
Context.Bridge.SetProperty (this, property, value);
}
public virtual dynamic GetProperty (string property)
{
return Context.FromComObject (ComObject.GetType ().InvokeMember (
property, BindingFlags.GetProperty, null, ComObject, null));
}
public virtual IEnumerable<dynamic> GetPropertyNames ()
{
dynamic propertyNames = Context.Bridge.GetPropertyNames (this);
for (int i = 0; i < propertyNames.length; i++)
yield return propertyNames [i];
}
public virtual bool HasProperty (string property) => Context.Bridge.HasProperty (this, property);
dynamic ComInvoke (string method, object [] arguments)
{
return Context.FromComObject (ComObject.GetType ().InvokeMember (
method, BindingFlags.InvokeMethod, null, ComObject, arguments));
}
public dynamic Invoke (string method, params object [] arguments)
{
return ComInvoke (method, Context.ToComObjectArray (arguments));
}
public dynamic Invoke (string method, IEnumerable<object> arguments)
{
return ComInvoke (method, Context.ToComObjectArray (arguments.ToArray ()));
}
public static bool operator == (WrappedObject a, WrappedObject b)
{
if (ReferenceEquals (a, b))
return true;
if ((object)a == null || (object)b == null)
return false;
return a.Equals (b);
}
public static bool operator != (WrappedObject a, WrappedObject b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
var wrapped = obj as WrappedObject;
return wrapped != null && ComObject.Equals (wrapped.ComObject);
}
public override int GetHashCode ()
{
return ComObject.GetHashCode ();
}
internal T Wrap<T> (object value) where T : WrappedObject => Wrap<T> (Context, value);
internal static T Wrap<T> (ScriptContext context, object value) where T : WrappedObject
{
return value == null ? null : (T)Inflate<T> (context, value);
}
static WrappedObject Inflate<T> (ScriptContext context, object nativeObject) where T : WrappedObject
{
if (nativeObject is IHTMLDocument2)
return new HtmlDocument (context, (IHTMLDocument2)nativeObject);
if (nativeObject is IHTMLStyleElement)
return new HtmlStyleElement (context, (IHTMLStyleElement)nativeObject);
if (nativeObject is IHTMLInputElement)
return new HtmlInputElement(context, (IHTMLInputElement)nativeObject);
if (nativeObject is IHTMLElement)
return new HtmlElement (context, (IHTMLElement)nativeObject);
if (nativeObject is IDOMKeyboardEvent)
return new KeyboardEvent (context, (IDOMKeyboardEvent)nativeObject);
if (nativeObject is IDOMUIEvent)
return new UIEvent (context, (IDOMUIEvent)nativeObject);
if (nativeObject is IDOMEvent)
return new Event (context, (IDOMEvent)nativeObject);
if (nativeObject is IHTMLDOMTextNode)
return new Text (context, (IHTMLDOMTextNode)nativeObject);
if (nativeObject is IHTMLDOMNode)
return new Node (context, (IHTMLDOMNode)nativeObject);
if (nativeObject is IHTMLSelection)
return new Selection (context, (IHTMLSelection)nativeObject);
if (nativeObject is IHTMLDOMRange)
return new Range (context, (IHTMLDOMRange)nativeObject);
if (nativeObject is IHTMLStyleSheetsCollection)
return new StyleSheetList (context, (IHTMLStyleSheetsCollection)nativeObject);
if (nativeObject is IHTMLStyleSheet)
return new CssStyleSheet (context, (IHTMLStyleSheet)nativeObject);
if (nativeObject is IHTMLCSSStyleDeclaration)
return new CssStyleDeclaration (context, (IHTMLCSSStyleDeclaration)nativeObject);
if (nativeObject is IHTMLCSSRule)
return new CssRule (context, (IHTMLCSSRule)nativeObject);
if (nativeObject is IHTMLRect)
return new ClientRect (context, (IHTMLRect)nativeObject);
return new WrappedObject (context, nativeObject);
}
protected static T Convert<T> (object o)
{
if (typeof(T) == typeof(string))
return (T)(object)o?.ToString ();
throw new ArgumentException ($"unable to convert to {typeof(T)}");
}
}
} | 35.994681 | 108 | 0.607507 | [
"MIT"
] | Bhaskers-Blu-Org2/workbooks | Clients/CrossBrowser/Xamarin.CrossBrowser.Wpf/WrappedObject.cs | 6,767 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GSoft.Dynamite.Fields;
using GSoft.Dynamite.ValueTypes;
using Microsoft.Office.DocumentManagement;
using Microsoft.SharePoint;
namespace GSoft.Dynamite.ValueTypes.Writers
{
/// <summary>
/// Writes Principal values to SharePoint list items, field definition's DefaultValue
/// and folder MetadataDefaults.
/// </summary>
public class PrincipalValueWriter : BaseValueWriter<PrincipalValue>
{
/// <summary>
/// Writes a Principal field value to a SPListItem
/// </summary>
/// <param name="item">The SharePoint List Item</param>
/// <param name="fieldValueInfo">The field and value information</param>
public override void WriteValueToListItem(SPListItem item, FieldValueInfo fieldValueInfo)
{
var principal = fieldValueInfo.Value as PrincipalValue;
var newValue = principal != null ? FormatPrincipalString(principal) : null;
item[fieldValueInfo.FieldInfo.InternalName] = newValue;
}
/// <summary>
/// Writes a Principal value as an SPField's default value
/// </summary>
/// <param name="parentFieldCollection">The parent field collection within which we can find the specific field to update</param>
/// <param name="fieldValueInfo">The field and value information</param>
public override void WriteValueToFieldDefault(SPFieldCollection parentFieldCollection, FieldValueInfo fieldValueInfo)
{
var defaultValue = (PrincipalValue)fieldValueInfo.Value;
var field = parentFieldCollection[fieldValueInfo.FieldInfo.Id];
if (defaultValue != null)
{
field.DefaultValue = FormatPrincipalString(defaultValue);
}
else
{
field.DefaultValue = null;
}
}
/// <summary>
/// Writes a field value as an SPFolder's default column value
/// </summary>
/// <param name="folder">The folder for which we wish to update a field's default value</param>
/// <param name="fieldValueInfo">The field and value information</param>
public override void WriteValueToFolderDefault(SPFolder folder, FieldValueInfo fieldValueInfo)
{
throw new NotSupportedException(
string.Format(
CultureInfo.InvariantCulture,
"WriteValueToFolderDefault - Initializing a folder column default value with PrincipalValue is not supported (fieldName={0}).",
fieldValueInfo.FieldInfo.InternalName));
}
private static string FormatPrincipalString(PrincipalValue principalValue)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0};#{1}",
principalValue.Id,
(principalValue.DisplayName ?? string.Empty).Replace(";", ";;"));
}
}
} | 40.921053 | 147 | 0.640836 | [
"MIT"
] | NunoEdgarGFlowHub/Dynamite | Source/GSoft.Dynamite/ValueTypes/Writers/PrincipalValueWriter.cs | 3,112 | C# |
using System.Collections.Generic;
using System.Security.Claims;
namespace JN.Authentication.HelperClasses
{
public class ChallengeResult
{
public int StatusCode { get; set; }
public string TextToWriteOutput { get; set; }
public string ContentType { get; set; }
}
public class ValidationResult
{
public bool Success { get; set; }
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public string ErrorDescription2 { get; }
public IEnumerable<Claim> Claims { get; set; }
}
}
| 23.8 | 54 | 0.640336 | [
"MIT"
] | jlnovais/JN.Authentication | JN.Authentication/HelperClasses/Results.cs | 597 | C# |
#if WITH_EDITOR
#if PLATFORM_64BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
/// <summary>Represents the appearance of an SCheckBox</summary>
[StructLayout(LayoutKind.Explicit,Size=1616)]
public partial struct FCheckBoxStyle
{
/// <summary>The visual type of the checkbox</summary>
[FieldOffset(8)]
public ESlateCheckBoxType CheckBoxType;
/// <summary>CheckBox appearance when the CheckBox is unchecked (normal)</summary>
[FieldOffset(16)]
public FSlateBrush UncheckedImage;
/// <summary>CheckBox appearance when the CheckBox is unchecked and hovered</summary>
[FieldOffset(168)]
public FSlateBrush UncheckedHoveredImage;
/// <summary>CheckBox appearance when the CheckBox is unchecked and hovered</summary>
[FieldOffset(320)]
public FSlateBrush UncheckedPressedImage;
/// <summary>CheckBox appearance when the CheckBox is checked</summary>
[FieldOffset(472)]
public FSlateBrush CheckedImage;
/// <summary>CheckBox appearance when checked and hovered</summary>
[FieldOffset(624)]
public FSlateBrush CheckedHoveredImage;
/// <summary>CheckBox appearance when checked and pressed</summary>
[FieldOffset(776)]
public FSlateBrush CheckedPressedImage;
/// <summary>CheckBox appearance when the CheckBox is undetermined</summary>
[FieldOffset(928)]
public FSlateBrush UndeterminedImage;
/// <summary>CheckBox appearance when CheckBox is undetermined and hovered</summary>
[FieldOffset(1080)]
public FSlateBrush UndeterminedHoveredImage;
/// <summary>CheckBox appearance when CheckBox is undetermined and pressed</summary>
[FieldOffset(1232)]
public FSlateBrush UndeterminedPressedImage;
/// <summary>Padding</summary>
[FieldOffset(1384)]
public FMargin Padding;
/// <summary>The foreground color</summary>
[FieldOffset(1400)]
public FSlateColor ForegroundColor;
/// <summary>BorderBackgroundColor refers to the actual color and opacity of the supplied border image on toggle buttons</summary>
[FieldOffset(1440)]
public FSlateColor BorderBackgroundColor;
/// <summary>The sound the check box should play when checked</summary>
[FieldOffset(1480)]
public FSlateSound CheckedSlateSound;
/// <summary>The sound the check box should play when unchecked</summary>
[FieldOffset(1512)]
public FSlateSound UncheckedSlateSound;
/// <summary>The sound the check box should play when initially hovered over</summary>
[FieldOffset(1544)]
public FSlateSound HoveredSlateSound;
[FieldOffset(1576)]
public FName CheckedSound;
[FieldOffset(1588)]
public FName UncheckedSound;
[FieldOffset(1600)]
public FName HoveredSound;
}
}
#endif
#endif
| 37.666667 | 132 | 0.772124 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Editor_64bits/FCheckBoxStyle.cs | 2,712 | C# |
using System.Collections.Generic;
using System.Net;
namespace Elysium
{
/// <summary>
/// A response from an API call that includes the deserialized object instance.
/// </summary>
public interface IApiResponse<out T>
{
/// <summary>
/// Object deserialized from the JSON response body.
/// </summary>
T Body { get; }
/// <summary>
/// The original non-deserialized http response.
/// </summary>
IResponse HttpResponse { get; }
}
/// <summary>
/// Represents a generic HTTP response
/// </summary>
public interface IResponse
{
/// <summary>
/// Raw response body. Typically a string, but when requesting images, it will be a byte array.
/// </summary>
object Body { get; }
/// <summary>
/// Information about the API.
/// </summary>
IReadOnlyDictionary<string, string> Headers { get; }
/// <summary>
/// The response status code.
/// </summary>
HttpStatusCode StatusCode { get; }
/// <summary>
/// The content type of the response.
/// </summary>
string ContentType { get; }
}
} | 26.06383 | 103 | 0.549388 | [
"MIT"
] | ElysiumLabs/Elysium-Client | Source/Elysium.Service.Client/Http/IResponse.cs | 1,227 | C# |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX;
using SharpDX.DirectWrite;
namespace CustomFont
{
/// <summary>
/// This FontFileStream implem is reading data from a <see cref="DataStream"/>.
/// </summary>
public class ResourceFontFileStream : CallbackBase, FontFileStream
{
private readonly DataStream _stream;
/// <summary>
/// Initializes a new instance of the <see cref="ResourceFontFileStream"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public ResourceFontFileStream(DataStream stream)
{
this._stream = stream;
}
/// <summary>
/// Reads a fragment from a font file.
/// </summary>
/// <param name="fragmentStart">When this method returns, contains an address of a reference to the start of the font file fragment. This parameter is passed uninitialized.</param>
/// <param name="fileOffset">The offset of the fragment, in bytes, from the beginning of the font file.</param>
/// <param name="fragmentSize">The size of the file fragment, in bytes.</param>
/// <param name="fragmentContext">When this method returns, contains the address of</param>
/// <remarks>
/// Note that ReadFileFragment implementations must check whether the requested font file fragment is within the file bounds. Otherwise, an error should be returned from ReadFileFragment. {{DirectWrite}} may invoke <see cref="SharpDX.DirectWrite.FontFileStream"/> methods on the same object from multiple threads simultaneously. Therefore, ReadFileFragment implementations that rely on internal mutable state must serialize access to such state across multiple threads. For example, an implementation that uses separate Seek and Read operations to read a file fragment must place the code block containing Seek and Read calls under a lock or a critical section.
/// </remarks>
/// <unmanaged>HRESULT IDWriteFontFileStream::ReadFileFragment([Out, Buffer] const void** fragmentStart,[None] __int64 fileOffset,[None] __int64 fragmentSize,[Out] void** fragmentContext)</unmanaged>
void FontFileStream.ReadFileFragment(out IntPtr fragmentStart, long fileOffset, long fragmentSize, out IntPtr fragmentContext)
{
lock (this)
{
fragmentContext = IntPtr.Zero;
_stream.Position = fileOffset;
fragmentStart = _stream.PositionPointer;
}
}
/// <summary>
/// Releases a fragment from a file.
/// </summary>
/// <param name="fragmentContext">A reference to the client-defined context of a font fragment returned from {{ReadFileFragment}}.</param>
/// <unmanaged>void IDWriteFontFileStream::ReleaseFileFragment([None] void* fragmentContext)</unmanaged>
void FontFileStream.ReleaseFileFragment(IntPtr fragmentContext)
{
// Nothing to release. No context are used
}
/// <summary>
/// Obtains the total size of a file.
/// </summary>
/// <returns>the total size of the file.</returns>
/// <remarks>
/// Implementing GetFileSize() for asynchronously loaded font files may require downloading the complete file contents. Therefore, this method should be used only for operations that either require a complete font file to be loaded (for example, copying a font file) or that need to make decisions based on the value of the file size (for example, validation against a persisted file size).
/// </remarks>
/// <unmanaged>HRESULT IDWriteFontFileStream::GetFileSize([Out] __int64* fileSize)</unmanaged>
long FontFileStream.GetFileSize()
{
return _stream.Length;
}
/// <summary>
/// Obtains the last modified time of the file.
/// </summary>
/// <returns>
/// the last modified time of the file in the format that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC).
/// </returns>
/// <remarks>
/// The "last modified time" is used by DirectWrite font selection algorithms to determine whether one font resource is more up to date than another one.
/// </remarks>
/// <unmanaged>HRESULT IDWriteFontFileStream::GetLastWriteTime([Out] __int64* lastWriteTime)</unmanaged>
long FontFileStream.GetLastWriteTime()
{
return 0;
}
}
} | 55.762376 | 671 | 0.684659 | [
"MIT"
] | BillChen2K/LearningRepo | Course/ComputerGraphics/Work2/第二次作业/SharpDX-Samples-master/SharpDX-Samples-master/Desktop/DirectWrite/CustomFont/ResourceFontFileStream.cs | 5,634 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using osu.Framework.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace osu.Framework.Testing
{
public class DynamicClassCompiler<T> : IDisposable
where T : IDynamicallyCompile
{
public event Action CompilationStarted;
public event Action<Type> CompilationFinished;
public event Action<Exception> CompilationFailed;
private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
private string lastTouchedFile;
private T checkpointObject;
public void Checkpoint(T obj)
{
checkpointObject = obj;
}
private readonly List<string> requiredFiles = new List<string>();
private List<string> requiredTypeNames = new List<string>();
private HashSet<string> assemblies;
private readonly List<string> validDirectories = new List<string>();
public void Start()
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
Task.Run(() =>
{
var basePath = getSolutionPath(di);
if (!Directory.Exists(basePath))
return;
foreach (var dir in Directory.GetDirectories(basePath))
{
// only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files.
if (!Directory.GetFiles(dir, "*.csproj").Any())
continue;
lock (compileLock) // enumeration over this list occurs during compilation
validDirectories.Add(dir);
var fsw = new FileSystemWatcher(dir, @"*.cs")
{
EnableRaisingEvents = true,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.FileName,
};
fsw.Renamed += onChange;
fsw.Changed += onChange;
fsw.Created += onChange;
watchers.Add(fsw);
}
});
string getSolutionPath(DirectoryInfo d)
{
if (d == null)
return null;
return d.GetFiles().Any(f => f.Extension == ".sln") ? d.FullName : getSolutionPath(d.Parent);
}
}
private void onChange(object sender, FileSystemEventArgs e)
{
lock (compileLock)
{
if (checkpointObject == null || isCompiling)
return;
var checkpointName = checkpointObject.GetType().Name;
var reqTypes = checkpointObject.RequiredTypes.Select(t => removeGenerics(t.Name)).ToList();
// add ourselves as a required type.
reqTypes.Add(removeGenerics(checkpointName));
// if we are a TestCase, add the class we are testing automatically.
reqTypes.Add(TestScene.RemovePrefix(removeGenerics(checkpointName)));
if (!reqTypes.Contains(Path.GetFileNameWithoutExtension(e.Name)))
return;
if (!reqTypes.SequenceEqual(requiredTypeNames))
{
requiredTypeNames = reqTypes;
requiredFiles.Clear();
foreach (var d in validDirectories)
{
requiredFiles.AddRange(Directory
.EnumerateFiles(d, "*.cs", SearchOption.AllDirectories)
.Where(fw => requiredTypeNames.Contains(Path.GetFileNameWithoutExtension(fw))));
}
}
lastTouchedFile = e.FullPath;
isCompiling = true;
Task.Run(recompile)
.ContinueWith(_ => isCompiling = false);
}
}
/// <summary>
/// Removes the "`1[T]" generic specification from type name output.
/// </summary>
private string removeGenerics(string checkpointName) => checkpointName.Split('`').First();
private int currentVersion;
private bool isCompiling;
private readonly object compileLock = new object();
private void recompile()
{
if (assemblies == null)
{
assemblies = new HashSet<string>();
foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
assemblies.Add(ass.Location);
}
assemblies.Add(typeof(JetBrains.Annotations.NotNullAttribute).Assembly.Location);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
// ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[]
{
#if DEBUG
"DEBUG",
#endif
#if TRACE
"TRACE",
#endif
#if RELEASE
"RELEASE",
#endif
}, languageVersion: LanguageVersion.CSharp7_3);
var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));
while (!checkFileReady(lastTouchedFile))
Thread.Sleep(10);
Logger.Log($@"Recompiling {Path.GetFileName(checkpointObject.GetType().Name)}...", LoggingTarget.Runtime, LogLevel.Important);
CompilationStarted?.Invoke();
// ensure we don't duplicate the dynamic suffix.
string assemblyNamespace = checkpointObject.GetType().Assembly.GetName().Name.Replace(".Dynamic", "");
string assemblyVersion = $"{++currentVersion}.0.*";
string dynamicNamespace = $"{assemblyNamespace}.Dynamic";
var compilation = CSharpCompilation.Create(
dynamicNamespace,
requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOptions, file))
// Compile the assembly with a new version so that it replaces the existing one
.Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions))
,
references,
options
);
using (var ms = new MemoryStream())
{
var compilationResult = compilation.Emit(ms);
if (compilationResult.Success)
{
ms.Seek(0, SeekOrigin.Begin);
CompilationFinished?.Invoke(
Assembly.Load(ms.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == checkpointObject.GetType().FullName)
);
}
else
{
foreach (var diagnostic in compilationResult.Diagnostics)
{
if (diagnostic.Severity < DiagnosticSeverity.Error)
continue;
CompilationFailed?.Invoke(new Exception(diagnostic.ToString()));
}
}
}
}
/// <summary>
/// Check whether a file has finished being written to.
/// </summary>
private static bool checkFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
#region IDisposable Support
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
isDisposed = true;
watchers.ForEach(w => w.Dispose());
}
}
~DynamicClassCompiler()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| 35.225681 | 159 | 0.528333 | [
"MIT"
] | HoutarouOreki/osu-framework | osu.Framework/Testing/DynamicClassCompiler.cs | 8,797 | C# |
namespace Gliber
{
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using static Newtonsoft.Json.Linq.JObject;
internal class SelectivePropertiesJsonConverter<TSrc> :JsonConverter
{
private readonly IEnumerable<string> selectedProperties;
public SelectivePropertiesJsonConverter(IEnumerable<string> selectedProperties)
{
this.selectedProperties = selectedProperties;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var jo = FromObject(value);
// Note: ToList() is needed here to prevent "collection was modified" error
foreach (var prop in jo.Properties().ToList())
{
if (!this.selectedProperties.Contains(prop.Name))
{
prop.Remove();
}
}
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TSrc);
// return false;
}
}
} | 28.020833 | 124 | 0.590335 | [
"MIT"
] | goldytech/Gliber | src/Gliber/SelectivePropertiesJsonConverter.cs | 1,347 | C# |
using blazor_inlineEditor.CustomAnnotations;
using System;
using System.ComponentModel.DataAnnotations;
namespace blazor_inlineEditor.Models
{
public class User
{
[Required(ErrorMessage = "Please enter Name")]
public string Name { get; set; }
[LessThanCurrentDate(ErrorMessage = "Please pick date it the past")]
public DateTime Birthday { get; set; }
[EnumDataType(typeof(Gender), ErrorMessage = "Please pick valid value")]
public Gender Gender { get; set; }
[Range(0, 300, ErrorMessage = "Please enter size between 0 and 300cm")]
public int HeightInCentimeters { get; set; }
[Range(0, 3, ErrorMessage = "Please enter size between 0 and 3m")]
public double HeightInMeters { get; set; }
[EmailAddress(ErrorMessage = "Please enter valid email address")]
public string Email { get; set; }
[MinLength(6, ErrorMessage = "Please enter 6+ characters")]
public string Password { get; set; }
}
public enum Gender
{
[Display(Name = "Female")]
FEMALE,
[Display(Name = "Male")]
MALE,
[Display(Name = "Diverse")]
DIVERSE
}
}
| 29.390244 | 80 | 0.624896 | [
"MIT"
] | hiiammalte/blazor_InlineEditor | blazor_inlineEditor/Models/User.cs | 1,207 | C# |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
namespace Aurora.Services.DataService
{
public class LocalRegionConnector : ConnectorBase, IRegionConnector
{
private IGenericData GD;
#region IRegionConnector Members
public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore simBase,
string defaultConnectionString)
{
GD = GenericData;
if (source.Configs[Name] != null)
defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
GD.ConnectToDatabase(defaultConnectionString, "Region",
source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));
DataManager.DataManager.RegisterPlugin(Name + "Local", this);
if (source.Configs["AuroraConnectors"].GetString("RegionConnector", "LocalConnector") == "LocalConnector")
{
DataManager.DataManager.RegisterPlugin(this);
}
Init(simBase, Name);
}
public string Name
{
get { return "IRegionConnector"; }
}
/// <summary>
/// Adds a new telehub in the region. Replaces an old one automatically.
/// </summary>
/// <param name = "telehub"></param>
/// <param name="regionhandle"> </param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public void AddTelehub(Telehub telehub, ulong regionhandle)
{
object remoteValue = DoRemote(telehub, regionhandle);
if (remoteValue != null || m_doRemoteOnly)
return;
//Look for a telehub first.
if (FindTelehub(new UUID(telehub.RegionID), 0) != null)
{
Dictionary<string, object> values = new Dictionary<string, object>();
values["TelehubLocX"] = telehub.TelehubLocX;
values["TelehubLocY"] = telehub.TelehubLocY;
values["TelehubLocZ"] = telehub.TelehubLocZ;
values["TelehubRotX"] = telehub.TelehubRotX;
values["TelehubRotY"] = telehub.TelehubRotY;
values["TelehubRotZ"] = telehub.TelehubRotZ;
values["Spawns"] = telehub.BuildFromList(telehub.SpawnPos);
values["ObjectUUID"] = telehub.ObjectUUID;
values["Name"] = telehub.Name;
QueryFilter filter = new QueryFilter();
filter.andFilters["RegionID"] = telehub.RegionID;
//Found one, time to update it.
GD.Update("telehubs", values, null, filter, null, null);
}
else
{
//Make a new one
GD.Insert("telehubs", new object[]{
telehub.RegionID,
telehub.RegionLocX,
telehub.RegionLocY,
telehub.TelehubLocX,
telehub.TelehubLocY,
telehub.TelehubLocZ,
telehub.TelehubRotX,
telehub.TelehubRotY,
telehub.TelehubRotZ,
telehub.BuildFromList(telehub.SpawnPos),
telehub.ObjectUUID,
telehub.Name
});
}
}
/// <summary>
/// Removes the telehub if it exists.
/// </summary>
/// <param name = "regionID"></param>
/// <param name="regionHandle"> </param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public void RemoveTelehub(UUID regionID, ulong regionHandle)
{
object remoteValue = DoRemote(regionID, regionHandle);
if (remoteValue != null || m_doRemoteOnly)
return;
//Look for a telehub first.
// Why? ~ SignpostMarv
if (FindTelehub(regionID, 0) != null)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["RegionID"] = regionID;
GD.Delete("telehubs", filter);
}
}
/// <summary>
/// Attempts to find a telehub in the region; if one is not found, returns false.
/// </summary>
/// <param name = "regionID">Region ID</param>
/// <param name="regionHandle"> </param>
/// <returns></returns>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public Telehub FindTelehub(UUID regionID, ulong regionHandle)
{
object remoteValue = DoRemote(regionID, regionHandle);
if (remoteValue != null || m_doRemoteOnly)
return (Telehub)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["RegionID"] = regionID;
List<string> telehubposition = GD.Query(new[]{
"RegionLocX",
"RegionLocY",
"TelehubLocX",
"TelehubLocY",
"TelehubLocZ",
"TelehubRotX",
"TelehubRotY",
"TelehubRotZ",
"Spawns",
"ObjectUUID",
"Name"
}, "telehubs", filter, null, null, null);
//Not the right number of values, so its not there.
return (telehubposition.Count != 11) ? null : new Telehub
{
RegionID = regionID,
RegionLocX = float.Parse(telehubposition[0]),
RegionLocY = float.Parse(telehubposition[1]),
TelehubLocX = float.Parse(telehubposition[2]),
TelehubLocY = float.Parse(telehubposition[3]),
TelehubLocZ = float.Parse(telehubposition[4]),
TelehubRotX = float.Parse(telehubposition[5]),
TelehubRotY = float.Parse(telehubposition[6]),
TelehubRotZ = float.Parse(telehubposition[7]),
SpawnPos = Telehub.BuildToList(telehubposition[8]),
ObjectUUID = UUID.Parse(telehubposition[9]),
Name = telehubposition[10]
};
}
#endregion
public void Dispose()
{
}
}
} | 42.518135 | 119 | 0.569827 | [
"BSD-3-Clause"
] | BillyWarrhol/Aurora-Sim | Aurora/Services/DataService/Connectors/Local/LocalRegionConnector.cs | 8,206 | C# |
using SRFS.Model.Clusters;
using System;
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;
namespace SRFS.Model.Data {
public class SrfsAccessRule : IEquatable<SrfsAccessRule> {
// Public
#region Constructors
public SrfsAccessRule(FileSystemObjectType type, int id, FileSystemAccessRule rule) {
_type = type;
_id = id;
_accessRule = rule;
}
public SrfsAccessRule(Directory dir, FileSystemAccessRule rule) {
_type = FileSystemObjectType.Directory;
_id = dir.ID;
_accessRule = rule;
}
public SrfsAccessRule(File file, FileSystemAccessRule rule) {
_type = FileSystemObjectType.File;
_id = file.ID;
_accessRule = rule;
}
public SrfsAccessRule(BinaryReader reader) {
_type = (FileSystemObjectType)reader.ReadByte();
_id = reader.ReadInt32();
SecurityIdentifier identityReference = reader.ReadSecurityIdentifier();
FileSystemRights fileSystemRights = (FileSystemRights)reader.ReadInt32();
InheritanceFlags inheritanceFlags = (InheritanceFlags)reader.ReadInt32();
PropagationFlags propagationFlags = (PropagationFlags)reader.ReadInt32();
AccessControlType accessControlType = (AccessControlType)reader.ReadInt32();
_accessRule = new FileSystemAccessRule(identityReference, fileSystemRights, inheritanceFlags, propagationFlags, accessControlType);
}
#endregion
#region Properties
public const int StorageLength =
sizeof(byte) + // File System Object Type
sizeof(int) + // ID
Constants.SecurityIdentifierLength + // Identity Reference
sizeof(int) + // File System Rights
sizeof(int) + // Inheritance Flags
sizeof(int) + // Propagation Flags
sizeof(int); // Access Control Type
public FileSystemObjectType FileSystemObjectType => _type;
public int ID => _id;
public FileSystemAccessRule Rule => _accessRule;
#endregion
#region Methods
public static ObjectArrayCluster<SrfsAccessRule> CreateArrayCluster(int address, int clusterSizeBytes, Guid volumeID) =>
new ObjectArrayCluster<SrfsAccessRule>(
address,
clusterSizeBytes,
volumeID,
ClusterType.AccessRulesTable,
StorageLength,
(writer, value) => value.Write(writer),
(reader) => new SrfsAccessRule(reader),
(writer) => writer.Write(_zero));
public void Write(BinaryWriter writer) {
writer.Write((byte)_type);
writer.Write(_id);
writer.Write((SecurityIdentifier)_accessRule.IdentityReference);
writer.Write((int)_accessRule.FileSystemRights);
writer.Write((int)_accessRule.InheritanceFlags);
writer.Write((int)_accessRule.PropagationFlags);
writer.Write((int)_accessRule.AccessControlType);
}
//--- IEquatable Implementation ---
public bool Equals(SrfsAccessRule obj) {
return _id == obj._id &&
_type == obj._type &&
_accessRule.IdentityReference == obj._accessRule.IdentityReference &&
_accessRule.FileSystemRights == obj._accessRule.FileSystemRights &&
_accessRule.InheritanceFlags == obj._accessRule.InheritanceFlags &&
_accessRule.PropagationFlags == obj._accessRule.PropagationFlags &&
_accessRule.AccessControlType == obj._accessRule.AccessControlType;
}
//--- Object Overrides ---
public override bool Equals(object obj) {
if (obj is SrfsAccessRule) return Equals((SrfsAccessRule)obj);
return false;
}
public override int GetHashCode() {
return _id.GetHashCode();
}
#endregion
// Private
#region Fields
private static readonly byte[] _zero = new byte[StorageLength];
private readonly FileSystemObjectType _type;
private readonly int _id;
private readonly FileSystemAccessRule _accessRule;
#endregion
}
}
| 35.322581 | 143 | 0.621689 | [
"MIT"
] | BadCodebot/SRFS2 | SRFS.Model/Data/SrfsAccessRule.cs | 4,382 | C# |
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloMonoGame.Entities
{
class Player : IEntity, ICollidable
{
public string Name { get; set; }
public Vector3 Position { get; set; }
public Vector3 Rotation { get; set; }
public BoundingBox BoundingBox { get; set; }
public void SetPosition(int x, int y, int z)
{
Position = new Vector3(x, y, z);
}
public void SetPosition(Vector3 positon)
{
throw new NotImplementedException();
}
public void Update(GameTime gameTime)
{
throw new NotImplementedException();
}
}
}
| 22.911765 | 52 | 0.607189 | [
"MIT"
] | antopilo/monovoxl | World/Entities/Player.cs | 781 | C# |
using System;
namespace AlgorithmVisualizer.DataStructures.BinaryTree
{
static class BinaryTreeTests
{
// A class to test BinarySearchTree, TreeUtils
public static void RunTests()
{
BinarySearchTree<int> BST = new BinarySearchTree<int>();
int[] vals = new int[] { 3, 1, 5, 0, 2, 4, 6 };
//int[] vals = new int[] { 5, 1, 3, 0, 2, 4, 6 };
foreach (int val in vals) if (!BST.Add(val)) Console.WriteLine($"Failed to add {val}");
BST.Print();
Console.WriteLine("==================================================");
Console.WriteLine("Size of tree: " + TreeUtils<int>.Size(BST.Root));
Console.WriteLine("Height of tree: " + TreeUtils<int>.Height(BST.Root));
Console.WriteLine("Is BST ? " + BST.IsBST());
bool containsAllInsertedValues = true;
foreach (int val in vals) if (!BST.Contains(val)) containsAllInsertedValues = false;
Console.WriteLine($"Contains all inserted values ? {containsAllInsertedValues}");
Console.WriteLine("==================================================");
Console.Write("PreOrder: \n");
Console.Write("Rec: "); TreeUtils<int>.PrintPreOrderRec(BST.Root); Console.WriteLine();
Console.Write("Itr: "); TreeUtils<int>.PrintPreOrderItr(BST.Root); Console.WriteLine();
Console.Write("Itr: "); TreeUtils<int>.PrintPreOrderItrMorris(BST.Root); Console.WriteLine();
Console.Write("InOrder: \n");
Console.Write("Rec: "); TreeUtils<int>.PrintInOrderRec(BST.Root); Console.WriteLine();
Console.Write("Itr: "); TreeUtils<int>.PrintInOrderItr(BST.Root); Console.WriteLine();
Console.Write("Itr: "); TreeUtils<int>.PrintInOrderItrMorris(BST.Root); Console.WriteLine();
Console.Write("PostOrder: \n");
Console.Write("Rec: "); TreeUtils<int>.PrintPostOrderRec(BST.Root); Console.WriteLine();
Console.Write("Itr: "); TreeUtils<int>.PrintPostOrderItr(BST.Root); Console.WriteLine();
Console.Write("LevelOrder: \n");
TreeUtils<int>.PrintLevelOrder(BST.Root); Console.WriteLine();
Console.Write("ReverseLevelOrder: \n");
TreeUtils<int>.PrintReverseLevelOrder(BST.Root); Console.WriteLine();
Console.Write("LevelByLevel: \n");
TreeUtils<int>.PrintLevelByLevelOrder(BST.Root); Console.WriteLine();
Console.WriteLine("==================================================");
foreach (int val in vals) if (!BST.Remove(val)) Console.WriteLine($"Failed to remove {val}");
BST.Print();
Console.WriteLine($"Is empty ? {BST.NodeCount == 0}");
}
}
}
| 41.15 | 96 | 0.647631 | [
"MIT"
] | garbagemeal/algorithm-visualizer | AlgorithmVisualizer/DataStructures/BinaryTree/BinaryTreeTests.cs | 2,471 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SymbolResourceUWPApp1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SymbolResourceUWPApp1")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 36.517241 | 84 | 0.745987 | [
"MIT"
] | Myfreedom614/UWP-Samples | SymbolResourceUWPApp1/SymbolResourceUWPApp1/Properties/AssemblyInfo.cs | 1,062 | C# |
namespace Windows.Bits
{
/// <summary>
/// Priority of the transfer job.
/// </summary>
public enum DownloadPriority
{
/// <summary>
/// Transfers the job in the foreground
/// </summary>
Foreground = 0,
/// <summary>
/// Transfers the job in the background. This is the highest background
/// priority level.
/// </summary>
High = 1,
/// <summary>
/// Transfers the job in the background. This is the default priority
/// level for a job
/// </summary>
Normal = 2,
/// <summary>
/// Transfers the job in the background. This is the lowest background
/// priority level
/// </summary>
Low = 3,
}
}
| 19.727273 | 74 | 0.614439 | [
"MIT"
] | MobileEssentials/Windows.Bits | src/Windows.Bits/DownloadPriority.cs | 653 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using GitIssue.Exceptions;
using GitIssue.Issues;
using GitIssue.Issues.Json;
using GitIssue.Values;
using Newtonsoft.Json;
namespace GitIssue.Fields
{
/// <summary>
/// FieldInfo Class
/// </summary>
[JsonObject]
public class FieldInfo
{
private static IFieldReader[]? readers;
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
public FieldInfo() : this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
/// <param name="required"></param>
public FieldInfo(bool required)
{
Required = required;
}
/// <summary>
/// Gets the list of field readers
/// </summary>
[JsonIgnore]
public IFieldReader[] Readers
{
get
{
return readers ??= GetType().Assembly.GetTypes()
.Where(t => t.IsPublic)
.Where(t => t.IsGenericType == false)
.Where(t => t.IsAbstract == false)
.Where(t => typeof(IFieldReader).IsAssignableFrom(t))
.Where(t => t.GetConstructor(Type.EmptyTypes) != null)
.Select(Activator.CreateInstance)
.Cast<IFieldReader>()
.ToArray();
}
}
/// <summary>
/// Gets or sets if the field is required on a given issue
/// </summary>
[JsonProperty]
[DefaultValue(false)]
public bool Required { get; set; }
/// <summary>
/// Gets or sets the data type for the field
/// </summary>
[JsonProperty]
public virtual TypeValue FieldType { get; set; } = TypeValue.Create<JsonValueField>();
/// <summary>
/// Gets or sets the metadata for the field
/// </summary>
[JsonProperty]
[DefaultValue("")]
public virtual string FieldMetadata { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the value type for the field
/// </summary>
[JsonProperty]
public virtual TypeValue ValueType { get; set; } = TypeValue.Create<string>();
/// <summary>
/// Gets or sets the metadata for the values
/// </summary>
[JsonProperty]
[DefaultValue("")]
public virtual string ValueMetadata { get; set; } = string.Empty;
/// <summary>
/// Determines if the field is valid
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
public virtual bool IsValid(IField field)
{
return false;
}
/// <summary>
/// Creates a new issue field
/// </summary>
/// <param name="issue"></param>
/// <param name="key"></param>
/// <returns></returns>
public IField CreateField(Issue issue, FieldKey key)
{
foreach (var provider in Readers)
if (provider.CanCreateField(this))
return provider.CreateField(issue, key, this);
throw new IssueNotFoundException("Unable to create issue with given field");
}
/// <summary>
/// Reads an existing issue field
/// </summary>
/// <param name="issue"></param>
/// <param name="key"></param>
/// <returns></returns>
public async Task<IField> ReadFieldAsync(Issue issue, FieldKey key)
{
foreach (var provider in Readers)
if (provider.CanReadField(this))
return await provider.ReadFieldAsync(issue, key, this);
throw new IssueNotFoundException("Unable to read issue with given field");
}
}
/// <summary>
/// FieldInfo Class
/// </summary>
[JsonObject]
public class FieldInfo<T> : FieldInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
public FieldInfo() : this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
/// <param name="required"></param>
public FieldInfo(bool required) : base(required)
{
Required = required;
}
/// <summary>
/// Gets or sets the data type
/// </summary>
[JsonProperty]
public override TypeValue ValueType
{
get => TypeValue.Create<T>();
set => throw new ArgumentException("Cannot set data type for generic data info");
}
}
/// <summary>
/// FieldInfo Class
/// </summary>
[JsonObject]
public class FieldInfo<T1, T2> : FieldInfo<T1>
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
public FieldInfo() : this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FieldInfo" /> class
/// </summary>
/// <param name="required"></param>
public FieldInfo(bool required) : base(required)
{
Required = required;
}
/// <summary>
/// Gets or sets the field type
/// </summary>
[JsonProperty]
public override TypeValue FieldType
{
get => TypeValue.Create<T2>();
set => throw new ArgumentException("Cannot set data type for generic field info");
}
}
} | 30.340206 | 94 | 0.515121 | [
"MIT"
] | lennoncork/GitIssue | src/GitIssue/Fields/FieldInfo.cs | 5,888 | C# |
using Bridge.Test.NUnit;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
/// <summary>
/// This is an extraction of Dotnet sources for Sorted List, which
/// was failing with Bridge. As this was the test case to reproduce the
/// issue, it was left here as the unit test. It was not provided the
/// exact address where the code was extracted from.
/// </summary>
[TestFixture(TestNameFormat = "#3599 - {0}")]
public class Bridge3599
{
#pragma warning disable CS0169 // The field is never used
public class SortedList<TK, TV> :
IDictionary<TK, TV>
{
private TK[] keys; // Do not rename (binary serialization)
private TV[] values; // Do not rename (binary serialization)
private int _size; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private IComparer<TK> comparer; // Do not rename (binary serialization)
private KeyList keyList; // Do not rename (binary serialization)
private ValueList valueList; // Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private const int DefaultCapacity = 4;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to DefaultCapacity, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
keys = new TK[] { };
values = new TV[] { };
_size = 0;
comparer = Comparer<TK>.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "SR.ArgumentOutOfRange_NeedNonNegNum");
keys = new TK[capacity];
values = new TV[capacity];
comparer = Comparer<TK>.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer<TK> comparer)
: this()
{
if (comparer != null)
{
this.comparer = comparer;
}
}
// Constructs a new sorted dictionary with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(int capacity, IComparer<TK> comparer)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TK, TV> dictionary)
: this(dictionary, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TK, TV> dictionary, IComparer<TK> comparer)
: this((dictionary != null ? dictionary.Count : 0), comparer)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
int count = dictionary.Count;
if (count != 0)
{
TK[] keys = this.keys;
dictionary.Keys.CopyTo(keys, 0);
dictionary.Values.CopyTo(values, 0);
Debug.Assert(count == this.keys.Length);
if (count > 1)
{
comparer = Comparer; // obtain default if this is null.
keys = dictionary.OrderBy(x => x.Key, comparer).Select(x => x.Key).ToArray();
for (int i = 1; i != keys.Length; ++i)
{
if (comparer.Compare(keys[i - 1], keys[i]) == 0)
{
throw new ArgumentException("SR.Format(SR.Argument_AddingDuplicate, keys[i])");
}
}
}
}
_size = count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public void Add(TK key, TV value)
{
if (key == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TK>(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException("SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)");
Insert(~i, key, value);
}
void ICollection<KeyValuePair<TK, TV>>.Add(KeyValuePair<TK, TV> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TK, TV>>.Contains(KeyValuePair<TK, TV> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TV>.Default.Equals(values[index], keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TK, TV>>.Remove(KeyValuePair<TK, TV> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TV>.Default.Equals(values[index], keyValuePair.Value))
{
RemoveAt(index);
return true;
}
return false;
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public int Capacity
{
get
{
return keys.Length;
}
set
{
if (value != keys.Length)
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "SR.ArgumentOutOfRange_SmallCapacity");
}
if (value > 0)
{
TK[] newKeys = new TK[value];
TV[] newValues = new TV[value];
if (_size > 0)
{
Array.Copy(keys, 0, newKeys, 0, _size);
Array.Copy(values, 0, newValues, 0, _size);
}
keys = newKeys;
values = newValues;
}
else
{
keys = new TK[] { };
values = new TV[] { };
}
}
}
}
public IComparer<TK> Comparer
{
get
{
return comparer;
}
}
// Returns the number of entries in this sorted list.
public int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
public IList<TK> Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection<TK> IDictionary<TK, TV>.Keys
{
get
{
return GetKeyListHelper();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public IList<TV> Values
{
get
{
return GetValueListHelper();
}
}
ICollection<TV> IDictionary<TK, TV>.Values
{
get
{
return GetValueListHelper();
}
}
private KeyList GetKeyListHelper()
{
if (keyList == null)
keyList = new KeyList(this);
return keyList;
}
private ValueList GetValueListHelper()
{
if (valueList == null)
valueList = new ValueList(this);
return valueList;
}
bool ICollection<KeyValuePair<TK, TV>>.IsReadOnly
{
get { return false; }
}
// Removes all entries from this sorted list.
public void Clear()
{
// clear does not change the capacity
version++;
// TODO:
// Don't need to doc this but we clear the elements so that the gc can reclaim the references.
//if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
//{
// Array.Clear(keys, 0, _size);
//}
//if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
//{
// Array.Clear(values, 0, _size);
//}
_size = 0;
}
// Checks if this sorted list contains an entry with the given key.
public bool ContainsKey(TK key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
public bool ContainsValue(TV value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
void ICollection<KeyValuePair<TK, TV>>.CopyTo(KeyValuePair<TK, TV>[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "SR.ArgumentOutOfRange_Index");
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException("SR.Arg_ArrayPlusOffTooSmall");
}
for (int i = 0; i < Count; i++)
{
KeyValuePair<TK, TV> entry = new KeyValuePair<TK, TV>(keys[i], values[i]);
array[arrayIndex + i] = entry;
}
}
private const int MaxArrayLength = 0X7FEFFFFF;
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the current capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
private TV GetByIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, "SR.ArgumentOutOfRange_Index");
return values[index];
}
public IEnumerator<KeyValuePair<TK, TV>> GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TK, TV>> IEnumerable<KeyValuePair<TK, TV>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
// Returns the key of the entry at the given index.
private TK GetKey(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, "SR.ArgumentOutOfRange_Index");
return keys[index];
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
public TV this[TK key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0)
return values[i];
throw new KeyNotFoundException("SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())");
}
set
{
if (((object)key) == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TK>(keys, 0, _size, key, comparer);
if (i >= 0)
{
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
public int IndexOfKey(TK key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
int ret = Array.BinarySearch<TK>(keys, 0, _size, key, comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
public int IndexOfValue(TV value)
{
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, TK key, TV value)
{
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
public bool TryGetValue(TK key, out TV value)
{
int i = IndexOfKey(key);
if (i >= 0)
{
value = values[i];
return true;
}
value = default(TV);
return false;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, "SR.ArgumentOutOfRange_Index");
_size--;
if (index < _size)
{
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
// TODO :
//if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
//{
// keys[_size] = default(TKey);
//}
//if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
//{
// values[_size] = default(TValue);
//}
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
public bool Remove(TK key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
return i >= 0;
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// SortedList.Clear();
// SortedList.TrimExcess();
public void TrimExcess()
{
int threshold = (int)(((double)keys.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return (key is TK);
}
private struct Enumerator : IEnumerator<KeyValuePair<TK, TV>>, IDictionaryEnumerator
{
private SortedList<TK, TV> _sortedList;
private TK _key;
private TV _value;
private int _index;
private int _version;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedList<TK, TV> sortedList, int getEnumeratorRetType)
{
_sortedList = sortedList;
_index = 0;
_version = _sortedList.version;
_getEnumeratorRetType = getEnumeratorRetType;
_key = default(TK);
_value = default(TV);
}
public void Dispose()
{
_index = 0;
_key = default(TK);
_value = default(TV);
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
return _key;
}
}
public bool MoveNext()
{
if (_version != _sortedList.version) throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
if ((uint)_index < (uint)_sortedList.Count)
{
_key = _sortedList.keys[_index];
_value = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_key = default(TK);
_value = default(TV);
return false;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
return new DictionaryEntry(_key, _value);
}
}
public KeyValuePair<TK, TV> Current
{
get
{
return new KeyValuePair<TK, TV>(_key, _value);
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_key, _value);
}
else
{
return new KeyValuePair<TK, TV>(_key, _value);
}
}
}
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
return _value;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
}
_index = 0;
_key = default(TK);
_value = default(TV);
}
}
private sealed class SortedListKeyEnumerator : IEnumerator<TK>, IEnumerator
{
private SortedList<TK, TV> _sortedList;
private int _index;
private int _version;
private TK _currentKey;
internal SortedListKeyEnumerator(SortedList<TK, TV> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentKey = default(TK);
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentKey = _sortedList.keys[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentKey = default(TK);
return false;
}
public TK Current
{
get
{
return _currentKey;
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
}
_index = 0;
_currentKey = default(TK);
}
}
private sealed class SortedListValueEnumerator : IEnumerator<TV>, IEnumerator
{
private SortedList<TK, TV> _sortedList;
private int _index;
private int _version;
private TV _currentValue;
internal SortedListValueEnumerator(SortedList<TK, TV> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentValue = default(TV);
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentValue = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentValue = default(TV);
return false;
}
public TV Current
{
get
{
return _currentValue;
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException("SR.InvalidOperation_EnumOpCantHappen");
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException("SR.InvalidOperation_EnumFailedVersion");
}
_index = 0;
_currentValue = default(TV);
}
}
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyList : IList<TK>, ICollection
{
private SortedList<TK, TV> _dict; // Do not rename (binary serialization)
internal KeyList(SortedList<TK, TV> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TK key)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public void Clear()
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public bool Contains(TK key)
{
return _dict.ContainsKey(key);
}
public void CopyTo(TK[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException("SR.Arg_RankMultiDimNotSupported, nameof(array)");
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("SR.Argument_InvalidArrayType, nameof(array)");
}
}
public void Insert(int index, TK value)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public TK this[int index]
{
get
{
return _dict.GetKey(index);
}
set
{
throw new NotSupportedException("SR.NotSupported_KeyCollectionSet");
}
}
public IEnumerator<TK> GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
public int IndexOf(TK key)
{
if (((object)key) == null)
throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TK>(_dict.keys, 0,
_dict.Count, key, _dict.comparer);
if (i >= 0) return i;
return -1;
}
public bool Remove(TK key)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
}
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueList : IList<TV>, ICollection
{
private SortedList<TK, TV> _dict; // Do not rename (binary serialization)
internal ValueList(SortedList<TK, TV> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TV key)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public void Clear()
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public bool Contains(TV value)
{
return _dict.ContainsValue(value);
}
public void CopyTo(TV[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int index)
{
if (array != null && array.Rank != 1)
throw new ArgumentException("SR.Arg_RankMultiDimNotSupported, nameof(array)");
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array, index, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("SR.Argument_InvalidArrayType, nameof(array)");
}
}
public void Insert(int index, TV value)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
public TV this[int index]
{
get
{
return _dict.GetByIndex(index);
}
set
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
}
public IEnumerator<TV> GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
public int IndexOf(TV value)
{
return Array.IndexOf(_dict.values, value, 0, _dict.Count);
}
public bool Remove(TV value)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException("SR.NotSupported_SortedListNestedWrite");
}
}
#pragma warning restore CS0169 // The field is never used
}
/// <summary>
/// Just ensure whether the static-used class can be referenced.
/// </summary>
[Test]
public static void TestCustomListImplementation()
{
Assert.AreEqual(0, new SortedList<int, int>().Count(), "Sorted list implementation works.");
}
}
} | 37.092019 | 134 | 0.456522 | [
"Apache-2.0"
] | AndreyZM/Bridge | Tests/Batch3/BridgeIssues/3500/N3599.cs | 39,503 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsVar_SRequest.
/// </summary>
public partial class WorkbookFunctionsVar_SRequest : BaseRequest, IWorkbookFunctionsVar_SRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsVar_SRequest.
/// </summary>
public WorkbookFunctionsVar_SRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFunctionsVar_SRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsVar_SRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsVar_SRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsVar_SRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.858824 | 153 | 0.57543 | [
"MIT"
] | twsouthwick/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsVar_SRequest.cs | 2,963 | C# |
using IITAcademicAutomationSystem.Areas.One;
using IITAcademicAutomationSystem.DAL;
using IITAcademicAutomationSystem.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace IITAcademicAutomationSystem
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Database.SetInitializer(new AppInitializer());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperConfig.RegisterMappings();
CreateRolesAndUsers();
}
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
protected void CreateRolesAndUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
// Admin role and user
if (!roleManager.RoleExists("Admin"))
{
var role = new IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "iit.du.ac.bd@gmail.com";
user.Email = "iit.du.ac.bd@gmail.com";
user.FullName = "Institute of Information Technology";
user.Designation = "University of Dhaka";
user.EmailConfirmed = true;
user.LockoutEnabled = true;
string userPWD = "iit123";
var chkUser = UserManager.Create(user, userPWD);
if (chkUser.Succeeded)
{
UserManager.AddToRole(user.Id, "Admin");
}
}
// Student role
if (!roleManager.RoleExists("Student"))
{
var role = new IdentityRole();
role.Name = "Student";
roleManager.Create(role);
}
// Teacher role
if (!roleManager.RoleExists("Teacher"))
{
var role = new IdentityRole();
role.Name = "Teacher";
roleManager.Create(role);
}
// Program Officer Regular role
if (!roleManager.RoleExists("Program Officer Regular"))
{
var role = new IdentityRole();
role.Name = "Program Officer Regular";
roleManager.Create(role);
}
// Program Officer Evening role
if (!roleManager.RoleExists("Program Officer Evening"))
{
var role = new IdentityRole();
role.Name = "Program Officer Evening";
roleManager.Create(role);
}
// Batch coordinator role
if (!roleManager.RoleExists("Batch Coordinator"))
{
var role = new IdentityRole();
role.Name = "Batch Coordinator";
roleManager.Create(role);
}
}
}
}
| 33.963636 | 104 | 0.565578 | [
"MIT"
] | JobayerAhmmed/IITAcademicAutomationSystem | IITAcademicAutomationSystem/Global.asax.cs | 3,738 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("10_AnimalType")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("10_AnimalType")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2ada983-013a-496d-a647-c434fc05c69e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.748207 | [
"MIT"
] | Brankovanov/SoftUniCourses | 1.ProgrammingBasics/complexConditions/10_AnimalType/Properties/AssemblyInfo.cs | 1,397 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace simple_tcp_repeater_net
{
class Program
{
static void Main(string[] args)
{
TcpListener server = null;
try
{
IPAddress iPAddress = IPAddress.Parse("127.0.0.1");
int PORT = 3001;
server = new TcpListener(iPAddress, PORT);
server.Start();
byte[] bytes = new byte[256];
bool continueLoop = true;
Console.WriteLine($"listening on {PORT}");
while (continueLoop)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(data);
if (data.ToLower().Trim() == "bye")
{
// New Feature, End the process after sending
// terminal message to the client.
byte[] hangup = Encoding.ASCII.GetBytes("hangup");
stream.Write(hangup);
//continueLoop = false;
//break;
}
else
{
data = $"You said \"{data}\"";
byte[] message = Encoding.ASCII.GetBytes(data);
stream.Write(message);
}
}
client.Close();
Console.WriteLine("");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
if (!(server is null))
{
server.Stop();
Console.WriteLine("Stopped Listening");
}
}
}
}
}
| 32.242857 | 78 | 0.383695 | [
"MIT"
] | jrcs3/Frakenapp-01 | dotnet-apps/simple-tcp-repeater-net/Program.cs | 2,259 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FacebookUtillity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FacebookUtillity")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("26d8c540-34de-4137-8861-a77158b73a49")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.749286 | [
"MIT"
] | Bhaskers-Blu-Org2/BusinessPlatformApps | Functions/Code/Facebook/FacebookUtillity/Properties/AssemblyInfo.cs | 1,403 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BenchmarkProgram")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BenchmarkProgram")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("ff30d891-4116-4f6b-bf4a-7d77862ff1c9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972973 | 84 | 0.746619 | [
"MIT"
] | mattchamb/Construct.NET | BenchmarkProgram/Properties/AssemblyInfo.cs | 1,408 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xorcerer.Wizard.Network")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("logan")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 35.5 | 82 | 0.744467 | [
"MIT"
] | Xorcerer/Wizard | Wizard/AssemblyInfo.cs | 994 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CorvEngine.Scenes {
/// <summary>
/// Contains the properties for this level.
/// </summary>
public class LevelProperty {
// TODO: This should be ComponentArgument integrated somehow,
// so as to allow us to generate properties with more interesting values.
/// <summary>
/// The name of this property.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The value of this property.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Creates a new MapProperty.
/// </summary>
public LevelProperty(string name, string value) {
Name = name;
Value = value;
}
}
}
| 22.84375 | 75 | 0.662107 | [
"MIT"
] | Kapps/Corvus | Corvus/CorvEngine/Scenes/LevelProperty.cs | 733 | C# |
using GameScreen.Viewmodel;
namespace GameScreen.Location
{
public class NewRelatedLocationViewmodel: ViewModelBase
{
private string _name;
private string _id;
public delegate NewRelatedLocationViewmodel Factory(string id, string name);
public NewRelatedLocationViewmodel(string id, string name)
{
_id = id;
_name = name;
}
public string Id
{
get => _id;
private set => SetProperty(ref _id, value);
}
public string Name
{
get => _name;
private set => SetProperty(ref _name, value);
}
}
} | 23.172414 | 84 | 0.561012 | [
"MIT"
] | zerotwooneone/GameScreen | GameScreen/Location/NewRelatedLocationViewmodel.cs | 674 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace What_time_is_it
{
class Program
{
static void Main(string[] args)
{
// Variable of DateTime type, at first empty
DateTime now;
// Storing of current date and time into our variable
now = DateTime.Now;
// Output
Console.WriteLine("Now is " + now);
// Waiting for Enter
Console.ReadLine();
}
}
}
| 20.62963 | 65 | 0.567325 | [
"MIT"
] | balee323/CSharp_for_abs_beginners | csharp-programming-for-absolute-begs/Chapter 05/1 What time is it/What time is it/Program.cs | 559 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Datadog.Trace.ClrProfiler.Emit;
using Datadog.Trace.ClrProfiler.Helpers;
using Datadog.Trace.Configuration;
using Datadog.Trace.DuckTyping;
using Datadog.Trace.Headers;
using Datadog.Trace.Logging;
using Datadog.Trace.Tagging;
namespace Datadog.Trace.ClrProfiler.Integrations
{
/// <summary>
/// Tracer integration for HttpClientHandler.
/// </summary>
public static class HttpMessageHandlerIntegration
{
private const string SystemNetHttp = "System.Net.Http";
private const string Major4 = "4";
private const string Major5 = "5";
private const string HttpMessageHandlerTypeName = "HttpMessageHandler";
private const string HttpClientHandlerTypeName = "HttpClientHandler";
private const string HttpMessageHandler = SystemNetHttp + "." + HttpMessageHandlerTypeName;
private const string HttpClientHandler = SystemNetHttp + "." + HttpClientHandlerTypeName;
private const string SendAsync = "SendAsync";
private static readonly IntegrationInfo IntegrationId = IntegrationRegistry.GetIntegrationInfo(nameof(IntegrationIds.HttpMessageHandler));
private static readonly IntegrationInfo SocketHandlerIntegrationId = IntegrationRegistry.GetIntegrationInfo(nameof(IntegrationIds.HttpSocketsHandler));
private static readonly Vendors.Serilog.ILogger Log = DatadogLogging.GetLogger(typeof(HttpMessageHandlerIntegration));
private static readonly string[] NamespaceAndNameFilters = { ClrNames.GenericTask, ClrNames.HttpRequestMessage, ClrNames.CancellationToken };
private static Type _httpMessageHandlerResultType;
private static Type _httpClientHandlerResultType;
/// <summary>
/// Instrumentation wrapper for HttpMessageHandler.SendAsync/>.
/// </summary>
/// <param name="handler">The HttpMessageHandler instance to instrument.</param>
/// <param name="request">The HttpRequestMessage that represents the current HTTP request.</param>
/// <param name="boxedCancellationToken">The <see cref="CancellationToken"/> value used in the original method call.</param>
/// <param name="opCode">The OpCode used in the original method call.</param>
/// <param name="mdToken">The mdToken of the original method call.</param>
/// <param name="moduleVersionPtr">A pointer to the module version GUID.</param>
/// <returns>Returns the value returned by the inner method call.</returns>
[InterceptMethod(
TargetAssembly = SystemNetHttp,
TargetType = HttpMessageHandler,
TargetMethod = SendAsync,
TargetSignatureTypes = new[] { ClrNames.HttpResponseMessageTask, ClrNames.HttpRequestMessage, ClrNames.CancellationToken },
TargetMinimumVersion = Major4,
TargetMaximumVersion = Major5)]
public static object HttpMessageHandler_SendAsync(
object handler,
object request,
object boxedCancellationToken,
int opCode,
int mdToken,
long moduleVersionPtr)
{
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
// original signature:
// Task<HttpResponseMessage> HttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
var cancellationToken = (CancellationToken)boxedCancellationToken;
var callOpCode = (OpCodeValue)opCode;
var httpMessageHandler = handler.GetInstrumentedType(SystemNetHttp, HttpMessageHandlerTypeName);
Func<object, object, CancellationToken, object> instrumentedMethod = null;
try
{
instrumentedMethod =
MethodBuilder<Func<object, object, CancellationToken, object>>
.Start(moduleVersionPtr, mdToken, opCode, SendAsync)
.WithConcreteType(httpMessageHandler)
.WithParameters(request, cancellationToken)
.WithNamespaceAndNameFilters(NamespaceAndNameFilters)
.Build();
}
catch (Exception ex)
{
Log.ErrorRetrievingMethod(
exception: ex,
moduleVersionPointer: moduleVersionPtr,
mdToken: mdToken,
opCode: opCode,
instrumentedType: HttpMessageHandler,
methodName: SendAsync,
instanceType: handler.GetType().AssemblyQualifiedName);
throw;
}
var reportedType = callOpCode == OpCodeValue.Call ? httpMessageHandler : handler.GetType();
var requestValue = request.As<HttpRequestMessageStruct>();
var isHttpClientHandler = handler.GetInstrumentedType(SystemNetHttp, HttpClientHandlerTypeName) != null;
if (!(isHttpClientHandler || IsSocketsHttpHandlerEnabled(reportedType)) ||
!IsTracingEnabled(requestValue.Headers))
{
// skip instrumentation
return instrumentedMethod(handler, request, cancellationToken);
}
Type taskResultType = _httpMessageHandlerResultType;
if (taskResultType == null || taskResultType.Assembly != httpMessageHandler.Assembly)
{
try
{
var currentHttpAssembly = httpMessageHandler.Assembly;
taskResultType = currentHttpAssembly.GetType("System.Net.Http.HttpResponseMessage", true);
_httpMessageHandlerResultType = taskResultType;
}
catch (Exception ex)
{
// This shouldn't happen because the System.Net.Http assembly should have been loaded if this method was called
// profiled app will not continue working as expected without this method
Log.Error(ex, "Error finding types in the user System.Net.Http assembly.");
throw;
}
}
return SendAsyncInternal(
instrumentedMethod,
reportedType,
requestValue,
handler,
request,
cancellationToken)
.Cast(taskResultType);
}
/// <summary>
/// Instrumentation wrapper for HttpClientHandler.SendAsync.
/// </summary>
/// <param name="handler">The HttpClientHandler instance to instrument.</param>
/// <param name="request">The HttpRequestMessage that represents the current HTTP request.</param>
/// <param name="boxedCancellationToken">The <see cref="CancellationToken"/> value used in the original method call.</param>
/// <param name="opCode">The OpCode used in the original method call.</param>
/// <param name="mdToken">The mdToken of the original method call.</param>
/// <param name="moduleVersionPtr">A pointer to the module version GUID.</param>
/// <returns>Returns the value returned by the inner method call.</returns>
[InterceptMethod(
TargetAssembly = SystemNetHttp,
TargetType = HttpClientHandler,
TargetMethod = SendAsync,
TargetSignatureTypes = new[] { ClrNames.HttpResponseMessageTask, ClrNames.HttpRequestMessage, ClrNames.CancellationToken },
TargetMinimumVersion = Major4,
TargetMaximumVersion = Major5)]
public static object HttpClientHandler_SendAsync(
object handler,
object request,
object boxedCancellationToken,
int opCode,
int mdToken,
long moduleVersionPtr)
{
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
// original signature:
// Task<HttpResponseMessage> HttpClientHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
var cancellationToken = (CancellationToken)boxedCancellationToken;
var callOpCode = (OpCodeValue)opCode;
var httpClientHandler = handler.GetInstrumentedType(SystemNetHttp, HttpClientHandlerTypeName);
Func<object, object, CancellationToken, object> instrumentedMethod = null;
try
{
instrumentedMethod =
MethodBuilder<Func<object, object, CancellationToken, object>>
.Start(moduleVersionPtr, mdToken, opCode, SendAsync)
.WithConcreteType(httpClientHandler)
.WithParameters(request, cancellationToken)
.WithNamespaceAndNameFilters(NamespaceAndNameFilters)
.Build();
}
catch (Exception ex)
{
Log.ErrorRetrievingMethod(
exception: ex,
moduleVersionPointer: moduleVersionPtr,
mdToken: mdToken,
opCode: opCode,
instrumentedType: HttpClientHandler,
methodName: SendAsync,
instanceType: handler.GetType().AssemblyQualifiedName);
throw;
}
var requestValue = request.As<HttpRequestMessageStruct>();
var reportedType = callOpCode == OpCodeValue.Call ? httpClientHandler : handler.GetType();
if (!IsTracingEnabled(requestValue.Headers))
{
// skip instrumentation
return instrumentedMethod(handler, request, cancellationToken);
}
Type taskResultType = _httpClientHandlerResultType;
if (taskResultType == null || taskResultType.Assembly != httpClientHandler.Assembly)
{
try
{
var currentHttpAssembly = httpClientHandler.Assembly;
taskResultType = currentHttpAssembly.GetType("System.Net.Http.HttpResponseMessage", true);
_httpClientHandlerResultType = taskResultType;
}
catch (Exception ex)
{
// This shouldn't happen because the System.Net.Http assembly should have been loaded if this method was called
// profiled app will not continue working as expected without this method
Log.Error(ex, "Error finding types in the user System.Net.Http assembly.");
throw;
}
}
return SendAsyncInternal(
instrumentedMethod,
reportedType,
requestValue,
handler,
request,
cancellationToken)
.Cast(taskResultType);
}
private static async Task<object> SendAsyncInternal(
Func<object, object, CancellationToken, object> sendAsync,
Type reportedType,
HttpRequestMessageStruct requestValue,
object handler,
object request,
CancellationToken cancellationToken)
{
var httpMethod = requestValue.Method.Method;
var requestUri = requestValue.RequestUri;
using (var scope = ScopeFactory.CreateOutboundHttpScope(Tracer.Instance, httpMethod, requestUri, IntegrationId, out var tags))
{
try
{
if (scope != null)
{
tags.HttpClientHandlerType = reportedType.FullName;
// add distributed tracing headers to the HTTP request
SpanContextPropagator.Instance.Inject(scope.Span.Context, new HttpHeadersCollection(requestValue.Headers));
}
var task = (Task)sendAsync(handler, request, cancellationToken);
await task.ConfigureAwait(false);
var response = task.As<TaskObjectStruct>().Result;
// this tag can only be set after the response is returned
int statusCode = response.As<HttpResponseMessageStruct>().StatusCode;
if (scope != null)
{
tags.HttpStatusCode = HttpTags.ConvertStatusCodeToString(statusCode);
}
return response;
}
catch (Exception ex)
{
scope?.Span.SetException(ex);
throw;
}
}
}
private static bool IsSocketsHttpHandlerEnabled(Type reportedType)
{
return Tracer.Instance.Settings.IsIntegrationEnabled(SocketHandlerIntegrationId, defaultValue: false)
&& reportedType.FullName.Equals("System.Net.Http.SocketsHttpHandler", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTracingEnabled(IRequestHeaders headers)
{
if (headers.TryGetValues(HttpHeaderNames.TracingEnabled, out var headerValues))
{
if (headerValues is string[] arrayValues)
{
for (var i = 0; i < arrayValues.Length; i++)
{
if (string.Equals(arrayValues[i], "false", StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
if (headerValues != null && headerValues.Any(s => string.Equals(s, "false", StringComparison.OrdinalIgnoreCase)))
{
// tracing is disabled for this request via http header
return false;
}
}
return true;
}
/********************
* Duck Typing Types
*/
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
#pragma warning disable SA1201 // Elements must appear in the correct order
#pragma warning disable SA1600 // Elements must be documented
[DuckCopy]
public struct HttpRequestMessageStruct
{
public HttpMethodStruct Method;
public Uri RequestUri;
public IRequestHeaders Headers;
}
[DuckCopy]
public struct HttpMethodStruct
{
public string Method;
}
public interface IRequestHeaders
{
bool TryGetValues(string name, out IEnumerable<string> values);
bool Remove(string name);
void Add(string name, string value);
}
[DuckCopy]
public struct HttpResponseMessageStruct
{
public int StatusCode;
}
[DuckCopy]
public struct TaskObjectStruct
{
public object Result;
}
internal readonly struct HttpHeadersCollection : IHeadersCollection
{
private readonly IRequestHeaders _headers;
public HttpHeadersCollection(IRequestHeaders headers)
{
_headers = headers ?? throw new ArgumentNullException(nameof(headers));
}
public IEnumerable<string> GetValues(string name)
{
if (_headers.TryGetValues(name, out IEnumerable<string> values))
{
return values;
}
return Enumerable.Empty<string>();
}
public void Set(string name, string value)
{
_headers.Remove(name);
_headers.Add(name, value);
}
public void Add(string name, string value)
{
_headers.Add(name, value);
}
public void Remove(string name)
{
_headers.Remove(name);
}
}
}
}
| 40.798507 | 159 | 0.583074 | [
"Apache-2.0"
] | link04/dd-trace-dotnet | src/Datadog.Trace.ClrProfiler.Managed/Integrations/HttpMessageHandlerIntegration.cs | 16,401 | C# |
namespace WebBrowser
{
partial class HomePageForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.InputBoxHomePageInputLabel = new System.Windows.Forms.Label();
this.inputChangeHomePage = new System.Windows.Forms.TextBox();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this.confirmbuttonChangeHomePage = new System.Windows.Forms.Button();
this.cancelbuttonChangeHomePage = new System.Windows.Forms.Button();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.currentHomePageAddressLabel = new System.Windows.Forms.Label();
this.currentHomeAddress = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel3, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel4, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 42.07921F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 57.92079F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(284, 223);
this.tableLayoutPanel1.TabIndex = 0;
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.ColumnCount = 1;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel3.Controls.Add(this.InputBoxHomePageInputLabel, 0, 0);
this.tableLayoutPanel3.Controls.Add(this.inputChangeHomePage, 0, 1);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 80);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 2;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(278, 99);
this.tableLayoutPanel3.TabIndex = 1;
//
// InputBoxHomePageInputLabel
//
this.InputBoxHomePageInputLabel.AutoSize = true;
this.InputBoxHomePageInputLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.InputBoxHomePageInputLabel.Location = new System.Drawing.Point(3, 0);
this.InputBoxHomePageInputLabel.Name = "InputBoxHomePageInputLabel";
this.InputBoxHomePageInputLabel.Size = new System.Drawing.Size(251, 40);
this.InputBoxHomePageInputLabel.TabIndex = 0;
this.InputBoxHomePageInputLabel.Text = "Please change the address in this field:";
//
// inputChangeHomePage
//
this.inputChangeHomePage.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.inputChangeHomePage.Location = new System.Drawing.Point(3, 52);
this.inputChangeHomePage.Name = "inputChangeHomePage";
this.inputChangeHomePage.Size = new System.Drawing.Size(272, 26);
this.inputChangeHomePage.TabIndex = 1;
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.ColumnCount = 2;
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.Controls.Add(this.confirmbuttonChangeHomePage, 0, 0);
this.tableLayoutPanel4.Controls.Add(this.cancelbuttonChangeHomePage, 1, 0);
this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 185);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 1;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.Size = new System.Drawing.Size(278, 35);
this.tableLayoutPanel4.TabIndex = 2;
//
// confirmbuttonChangeHomePage
//
this.confirmbuttonChangeHomePage.Location = new System.Drawing.Point(3, 3);
this.confirmbuttonChangeHomePage.Name = "confirmbuttonChangeHomePage";
this.confirmbuttonChangeHomePage.Size = new System.Drawing.Size(75, 23);
this.confirmbuttonChangeHomePage.TabIndex = 0;
this.confirmbuttonChangeHomePage.Text = "Confirm";
this.confirmbuttonChangeHomePage.UseVisualStyleBackColor = true;
this.confirmbuttonChangeHomePage.Click += new System.EventHandler(this.ConfirmbuttonChangeHomePage_Click);
//
// cancelbuttonChangeHomePage
//
this.cancelbuttonChangeHomePage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cancelbuttonChangeHomePage.Location = new System.Drawing.Point(200, 3);
this.cancelbuttonChangeHomePage.Name = "cancelbuttonChangeHomePage";
this.cancelbuttonChangeHomePage.Size = new System.Drawing.Size(75, 23);
this.cancelbuttonChangeHomePage.TabIndex = 1;
this.cancelbuttonChangeHomePage.Text = "Cancel";
this.cancelbuttonChangeHomePage.UseVisualStyleBackColor = true;
this.cancelbuttonChangeHomePage.Click += new System.EventHandler(this.CancelbuttonChangeHomePage_Click);
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.ColumnCount = 1;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.Controls.Add(this.currentHomePageAddressLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.currentHomeAddress, 0, 1);
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 2;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(278, 71);
this.tableLayoutPanel2.TabIndex = 3;
//
// currentHomePageAddressLabel
//
this.currentHomePageAddressLabel.AutoSize = true;
this.currentHomePageAddressLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.currentHomePageAddressLabel.Location = new System.Drawing.Point(3, 0);
this.currentHomePageAddressLabel.Name = "currentHomePageAddressLabel";
this.currentHomePageAddressLabel.Size = new System.Drawing.Size(217, 20);
this.currentHomePageAddressLabel.TabIndex = 0;
this.currentHomePageAddressLabel.Text = "Current Home Page Address:";
//
// currentHomeAddress
//
this.currentHomeAddress.AutoSize = true;
this.currentHomeAddress.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.currentHomeAddress.Location = new System.Drawing.Point(3, 35);
this.currentHomeAddress.Name = "currentHomeAddress";
this.currentHomeAddress.Size = new System.Drawing.Size(108, 13);
this.currentHomeAddress.TabIndex = 1;
this.currentHomeAddress.Text = "No Home Address";
//
// HomePageForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 223);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "HomePageForm";
this.Text = "HomePageForm";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.Label InputBoxHomePageInputLabel;
private System.Windows.Forms.TextBox inputChangeHomePage;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.Button confirmbuttonChangeHomePage;
private System.Windows.Forms.Button cancelbuttonChangeHomePage;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Label currentHomePageAddressLabel;
private System.Windows.Forms.Label currentHomeAddress;
}
} | 60.606061 | 187 | 0.67 | [
"MIT"
] | dimartinot/Web-Browser-in-C-Sharp | WebBrowser/HomePageForm.Designer.cs | 12,002 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspNetCore.VersionInfo.Providers
{
public class EnvironmentVariablesProvider : IInfoProvider
{
public string Name => nameof(EnvironmentVariablesProvider);
public IDictionary<string, string> GetData()
{
var dict = new Dictionary<string, string>();
foreach (DictionaryEntry envVar in Environment.GetEnvironmentVariables())
{
dict.Add(envVar.Key.ToString(), envVar.Value.ToString());
}
return dict;
}
}
}
| 25.148148 | 85 | 0.65243 | [
"Apache-2.0"
] | salem84/AspNetCore.VersionInfo | src/AspNetCore.VersionInfo/Providers/EnvironmentVariablesProvider.cs | 681 | 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 Capture_Tool
{
public partial class AddCaption : Form
{
public AddCaption()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
public void setLabel(string text)
{
lbText.Text = text;
}
public void setSingleLine()
{
tbData.Multiline = false;
}
public string getData()
{
return tbData.Text;
}
}
}
| 19.609756 | 61 | 0.543532 | [
"MIT"
] | shaji007/Capture-Tool | Capture Tool/AddCaption.cs | 806 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Automatonymous.SubscriptionConnectors
{
using System;
using System.Collections.Generic;
using System.Linq;
using GreenPipes;
using MassTransit;
using MassTransit.Pipeline;
using MassTransit.Saga;
using MassTransit.Saga.Configuration;
using MassTransit.Saga.Connectors;
using MassTransit.Util;
public class StateMachineConnector<TInstance> :
ISagaConnector
where TInstance : class, ISaga, SagaStateMachineInstance
{
readonly List<ISagaMessageConnector<TInstance>> _connectors;
readonly SagaStateMachine<TInstance> _stateMachine;
public StateMachineConnector(SagaStateMachine<TInstance> stateMachine)
{
_stateMachine = stateMachine;
try
{
_connectors = StateMachineEvents().ToList();
}
catch (Exception ex)
{
throw new ConfigurationException($"Failed to create the state machine connector for {TypeMetadataCache<TInstance>.ShortName}", ex);
}
}
public ISagaSpecification<T> CreateSagaSpecification<T>() where T : class, ISaga
{
List<ISagaMessageSpecification<T>> messageSpecifications =
_connectors.Select(x => x.CreateSagaMessageSpecification())
.Cast<ISagaMessageSpecification<T>>()
.ToList();
return new SagaSpecification<T>(messageSpecifications);
}
public ConnectHandle ConnectSaga<T>(IConsumePipeConnector consumePipe, ISagaRepository<T> sagaRepository, ISagaSpecification<T> specification)
where T : class, ISaga
{
var handles = new List<ConnectHandle>();
try
{
foreach (var connector in _connectors.Cast<ISagaMessageConnector<T>>())
{
var handle = connector.ConnectSaga(consumePipe, sagaRepository, specification);
handles.Add(handle);
}
return new MultipleConnectHandle(handles);
}
catch (Exception)
{
foreach (var handle in handles)
handle.Dispose();
throw;
}
}
IEnumerable<ISagaMessageConnector<TInstance>> StateMachineEvents()
{
EventCorrelation[] correlations = _stateMachine.Correlations.ToArray();
StateMachineConfigurationResult.CompileResults(correlations.SelectMany(x => x.Validate()).ToArray());
foreach (var correlation in correlations)
{
if (correlation.DataType.IsValueType)
continue;
var genericType = typeof(StateMachineInterfaceType<,>).MakeGenericType(typeof(TInstance), correlation.DataType);
var interfaceType = (IStateMachineInterfaceType)Activator.CreateInstance(genericType,
_stateMachine, correlation);
yield return interfaceType.GetConnector<TInstance>();
}
}
}
} | 38.128713 | 151 | 0.612308 | [
"Apache-2.0"
] | andymac4182/MassTransit | src/MassTransit.AutomatonymousIntegration/Configuration/SubscriptionConnectors/StateMachineConnector.cs | 3,853 | C# |
/*
* MailSlurp API
*
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
*
* The version of the OpenAPI document: 6.5.2
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using mailslurp.Api;
using mailslurp.Model;
using mailslurp.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace mailslurp.Test
{
/// <summary>
/// Class for testing WebhookResultDto
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class WebhookResultDtoTests : IDisposable
{
// TODO uncomment below to declare an instance variable for WebhookResultDto
//private WebhookResultDto instance;
public WebhookResultDtoTests()
{
// TODO uncomment below to create an instance of WebhookResultDto
//instance = new WebhookResultDto();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of WebhookResultDto
/// </summary>
[Fact]
public void WebhookResultDtoInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" WebhookResultDto
//Assert.IsInstanceOfType<WebhookResultDto> (instance, "variable 'instance' is a WebhookResultDto");
}
/// <summary>
/// Test the property 'CreatedAt'
/// </summary>
[Fact]
public void CreatedAtTest()
{
// TODO unit test for the property 'CreatedAt'
}
/// <summary>
/// Test the property 'HttpMethod'
/// </summary>
[Fact]
public void HttpMethodTest()
{
// TODO unit test for the property 'HttpMethod'
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'InboxId'
/// </summary>
[Fact]
public void InboxIdTest()
{
// TODO unit test for the property 'InboxId'
}
/// <summary>
/// Test the property 'MessageId'
/// </summary>
[Fact]
public void MessageIdTest()
{
// TODO unit test for the property 'MessageId'
}
/// <summary>
/// Test the property 'RedriveId'
/// </summary>
[Fact]
public void RedriveIdTest()
{
// TODO unit test for the property 'RedriveId'
}
/// <summary>
/// Test the property 'ResponseBodyExtract'
/// </summary>
[Fact]
public void ResponseBodyExtractTest()
{
// TODO unit test for the property 'ResponseBodyExtract'
}
/// <summary>
/// Test the property 'ResponseStatus'
/// </summary>
[Fact]
public void ResponseStatusTest()
{
// TODO unit test for the property 'ResponseStatus'
}
/// <summary>
/// Test the property 'ResponseTimeMillis'
/// </summary>
[Fact]
public void ResponseTimeMillisTest()
{
// TODO unit test for the property 'ResponseTimeMillis'
}
/// <summary>
/// Test the property 'ResultType'
/// </summary>
[Fact]
public void ResultTypeTest()
{
// TODO unit test for the property 'ResultType'
}
/// <summary>
/// Test the property 'Seen'
/// </summary>
[Fact]
public void SeenTest()
{
// TODO unit test for the property 'Seen'
}
/// <summary>
/// Test the property 'UpdatedAt'
/// </summary>
[Fact]
public void UpdatedAtTest()
{
// TODO unit test for the property 'UpdatedAt'
}
/// <summary>
/// Test the property 'UserId'
/// </summary>
[Fact]
public void UserIdTest()
{
// TODO unit test for the property 'UserId'
}
/// <summary>
/// Test the property 'WebhookEvent'
/// </summary>
[Fact]
public void WebhookEventTest()
{
// TODO unit test for the property 'WebhookEvent'
}
/// <summary>
/// Test the property 'WebhookId'
/// </summary>
[Fact]
public void WebhookIdTest()
{
// TODO unit test for the property 'WebhookId'
}
/// <summary>
/// Test the property 'WebhookUrl'
/// </summary>
[Fact]
public void WebhookUrlTest()
{
// TODO unit test for the property 'WebhookUrl'
}
}
}
| 28.75 | 472 | 0.541848 | [
"MIT"
] | mailslurp/mailslurp-client-csharp | src/mailslurp.Test/Model/WebhookResultDtoTests.cs | 5,520 | C# |
//
// CalendarInfo.cs
//
// Author: responsive kaysta
//
// Copyright (c) 2017 responsive kaysta
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
namespace PowerUpDateTimeUtils
{
/// <summary>
/// Liefert Informationen zu Kalendern, die diese leider nicht
/// direkt zur Verfügung stellen
/// </summary>
public class CalendarInfo
{
#region Öffentliche Felder
/// <summary>
/// Der Basis-Kalender
/// </summary>
public readonly Calendar Calendar;
/// <summary>
/// Referenziert eine Kultur, die diesen Kalender verwendet (bzw. verwendet hat)
/// </summary>
public readonly CultureInfo SampleCulture;
/// <summary>
/// Der Name des Kalenders
/// </summary>
public readonly string CalendarName;
/// <summary>
/// Der Name des Algorithmus-Typs, auf dem der Kalender basiert
/// </summary>
public readonly string AlgorithmTypeName;
/// <summary>
/// Gibt an, wie viele Tage ein Monat minimal besitzt
/// </summary>
public readonly int MonthInYearMin;
/// <summary>
/// Gibt an, wie viele Tage ein Monat maximal besitzt
/// </summary>
public readonly int MonthInYearMax;
/// <summary>
/// Gibt an, wie viele Tage ein Monat minimal besitzt
/// </summary>
public readonly int DaysInMonthMin;
/// <summary>
/// Gibt an, wie viele Tage ein Monat maximal besitzt
/// </summary>
public readonly int DaysInMonthMax;
/// <summary>
/// Gibt die Schaltmonate an falls solche existieren
/// </summary>
public readonly ReadOnlyCollection<LeapMonthInfo> LeapMonths;
#endregion
#region Konstruktor
/// <summary>
/// Konstruktor
/// </summary>
/// <param name="paramCalendar">Der Kalender</param>
public CalendarInfo(Calendar paramCalendar)
{
// Kalender übergeben
Calendar = paramCalendar;
// Den Kalendernamen und die Beispielkultur ermitteln
if (paramCalendar is ChineseLunisolarCalendar)
{
CalendarName = "Chinese Lunisolar";
SampleCulture = CultureInfo.GetCultureInfo("zh-CN");
}
else if (paramCalendar is GregorianCalendar)
{
CalendarName = "Gregorian";
SampleCulture = CultureInfo.GetCultureInfo("en-US");
}
else if (paramCalendar is HebrewCalendar)
{
CalendarName = "Hebrew";
SampleCulture = CultureInfo.GetCultureInfo("he-IL");
}
else if (paramCalendar is HijriCalendar)
{
CalendarName = "Hijri";
SampleCulture = CultureInfo.GetCultureInfo("ar-SA");
}
else if (paramCalendar is JapaneseCalendar)
{
CalendarName = "Japanese";
SampleCulture = CultureInfo.GetCultureInfo("ja-JP");
}
else if (paramCalendar is JapaneseLunisolarCalendar)
{
CalendarName = "Japanese Lunisolar";
SampleCulture = CultureInfo.GetCultureInfo("ja-JP");
}
else if (paramCalendar is JulianCalendar)
{
CalendarName = "Julian";
SampleCulture = CultureInfo.GetCultureInfo("en-US");
}
else if (paramCalendar is KoreanCalendar)
{
CalendarName = "Korean";
SampleCulture = CultureInfo.GetCultureInfo("ko-KR");
}
else if (paramCalendar is KoreanLunisolarCalendar)
{
CalendarName = "Korean Lunisolar";
SampleCulture = CultureInfo.GetCultureInfo("ko-KR");
}
else if (paramCalendar is PersianCalendar)
{
CalendarName = "Persian";
SampleCulture = CultureInfo.GetCultureInfo("fa-IR");
}
else if (paramCalendar is TaiwanCalendar)
{
CalendarName = "Taiwan";
SampleCulture = CultureInfo.GetCultureInfo("zh-TW");
}
else if (paramCalendar is TaiwanLunisolarCalendar)
{
CalendarName = "Taiwan Lunisolar";
SampleCulture = CultureInfo.GetCultureInfo("zh-TW");
}
else if (paramCalendar is ThaiBuddhistCalendar)
{
CalendarName = "Thai Buddhist";
SampleCulture = CultureInfo.GetCultureInfo("th-TH");
}
else if (paramCalendar is UmAlQuraCalendar)
{
CalendarName = "Um Al Qura";
SampleCulture = CultureInfo.GetCultureInfo("ar-SA");
}
else
{
SampleCulture = CultureInfo.InvariantCulture;
CalendarName = "Unknown";
}
// Den Algorithmustyp-Namen ermitteln
switch (paramCalendar.AlgorithmType)
{
case CalendarAlgorithmType.LunarCalendar:
AlgorithmTypeName = "Lunar";
break;
case CalendarAlgorithmType.LunisolarCalendar:
AlgorithmTypeName = "Lunisolar";
break;
case CalendarAlgorithmType.SolarCalendar:
AlgorithmTypeName = "Solar";
break;
case CalendarAlgorithmType.Unknown:
AlgorithmTypeName = "Unknown";
break;
}
// Ermitteln der minimalen und maximalen Anzahl der Monate im Jahr
MonthInYearMin = int.MaxValue;
MonthInYearMax = 0;
DateTime date = paramCalendar.MinSupportedDateTime;
while (date < paramCalendar.MaxSupportedDateTime)
{
// Die Anzahl der Monate im Jahr ermitteln
int calendarYear = paramCalendar.GetYear(date);
try
{
int monthsInYear = paramCalendar.GetMonthsInYear(calendarYear);
if (monthsInYear == 0)
{
Debugger.Break();
}
MonthInYearMin = Math.Min(MonthInYearMin, monthsInYear);
MonthInYearMax = Math.Max(MonthInYearMax, monthsInYear);
}
catch (ArgumentOutOfRangeException)
{
// HACK: Der Japanese-Lunisolar-Kalender erzeugt bei Jahren ab
// 62 (Gregorianisches Jahr 1988) eine ArgumentOutOfRangeException
// bei Aufruf von GetMonthsInYear, obwohl GetYear dieses Jahr
// selbst zurückgegeben hat!?
break;
}
// Das Datum um ein (gregorianisches) Jahr erhöhen
try
{
date = date.AddYears(1);
}
catch
{
break;
}
}
// Die minimale und maximale Anzahl der Tage
// für die Monate des Kalenders ermitteln
date = paramCalendar.MinSupportedDateTime;
DaysInMonthMin = int.MaxValue;
DaysInMonthMax = 0;
while (date < paramCalendar.MaxSupportedDateTime)
{
// Die Anzahl der Tage im Monat
int calendarYear = paramCalendar.GetYear(date);
int calendarMonth = paramCalendar.GetMonth(date);
try
{
int daysInMonth = paramCalendar.GetDaysInMonth(calendarYear, calendarMonth);
DaysInMonthMin = Math.Min(DaysInMonthMin, daysInMonth);
DaysInMonthMax = Math.Max(DaysInMonthMax, daysInMonth);
}
catch (ArgumentOutOfRangeException)
{
// HACK: GetDaysInMonth liefert zumindest beim
// Japanese-Lunisolar-Kalender eine ArgumentOutOfRangeException
// wenn der Monat 13 angegeben wird, obwohl GetMonth diesen Monat selbst
// zurückgegeban hat!?
// Das Datum um einen (gregorianischen) Monat erhöhen
try
{
date = date.AddMonths(1);
}
catch
{
break;
}
continue;
}
// Das Datum um einen (gregorianischen) Monat erhöhen
try
{
date = date.AddMonths(1);
}
catch
{
break;
}
}
// Ermitteln der Schaltmonate
List<LeapMonthInfo> leapMonths = new List<LeapMonthInfo>();
date = paramCalendar.MinSupportedDateTime;
while (date < paramCalendar.MaxSupportedDateTime)
{
int calendarYear = paramCalendar.GetYear(date);
try
{
int leapMonthCount = paramCalendar.GetLeapMonth(calendarYear);
if (leapMonthCount > 0)
{
leapMonths.Add(new LeapMonthInfo() { LeapMonthCount = leapMonthCount, GregorianYear = date.Year });
}
}
catch (ArgumentOutOfRangeException)
{
// HACK: Der Japanese-Lunisolar-Kalender erzeugt bei Jahren ab
// 62 (Gregorianisches Jahr 1988) eine ArgumentOutOfRangeException
// bei Aufruf von GetLeapMonth, obwohl GetYear dieses Jahr
// selbst zurückgegeben hat!?
break;
}
// Das Datum um ein (gregorianisches) Jahr erhöhen
try
{
date = date.AddYears(1);
}
catch
{
break;
}
}
LeapMonths = new ReadOnlyCollection<LeapMonthInfo>(leapMonths);
}
#endregion
#region Instanzmethoden
/// <summary>
/// Liefert ein Datum als String in der Form des Kalenders
/// </summary>
/// <param name="date">Das Datum</param>
public string GetCalendarDateString(DateTime date)
{
return Calendar.GetDayOfMonth(DateTime.Now) + "." + Calendar.GetMonth(DateTime.Now) + "." + Calendar.GetYear(DateTime.Now);
}
#endregion
#region Statische Methoden
/// <summary>
/// Liefert die System-Kalender
/// </summary>
public static List<CalendarInfo> GetSystemCalendars()
{
List<CalendarInfo> calendarInfos = new List<CalendarInfo>();
calendarInfos.Add(new CalendarInfo(new ChineseLunisolarCalendar()));
calendarInfos.Add(new CalendarInfo(new GregorianCalendar()));
calendarInfos.Add(new CalendarInfo(new HebrewCalendar()));
calendarInfos.Add(new CalendarInfo(new HijriCalendar()));
calendarInfos.Add(new CalendarInfo(new JapaneseCalendar()));
calendarInfos.Add(new CalendarInfo(new JapaneseLunisolarCalendar()));
calendarInfos.Add(new CalendarInfo(new JulianCalendar()));
calendarInfos.Add(new CalendarInfo(new KoreanCalendar()));
calendarInfos.Add(new CalendarInfo(new KoreanLunisolarCalendar()));
calendarInfos.Add(new CalendarInfo(new PersianCalendar()));
calendarInfos.Add(new CalendarInfo(new ThaiBuddhistCalendar()));
calendarInfos.Add(new CalendarInfo(new TaiwanCalendar()));
calendarInfos.Add(new CalendarInfo(new TaiwanLunisolarCalendar()));
calendarInfos.Add(new CalendarInfo(new UmAlQuraCalendar()));
return calendarInfos;
}
#endregion
#region Überschriebene Methoden
/// <summary>
/// Gibt den Namen des Kalenders zurück
/// </summary>
public override string ToString()
{
return CalendarName;
}
#endregion
}
}
| 28.90027 | 126 | 0.69847 | [
"MIT"
] | injekt666/InMemoryLoaderCommon | Obsolete.PowerUpUtils/PowerUpDateTimeUtils/CalendarInfo.cs | 10,737 | C# |
using System.Collections.Concurrent;
using Microsoft.Extensions.Configuration;
using Abp.Extensions;
using Abp.Reflection.Extensions;
namespace HeProject.Configuration
{
public static class AppConfigurations
{
private static readonly ConcurrentDictionary<string, IConfigurationRoot> _configurationCache;
static AppConfigurations()
{
_configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
}
public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false)
{
var cacheKey = path + "#" + environmentName + "#" + addUserSecrets;
return _configurationCache.GetOrAdd(
cacheKey,
_ => BuildConfiguration(path, environmentName, addUserSecrets)
);
}
private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
{
var builder = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
if (!environmentName.IsNullOrWhiteSpace())
{
builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
}
builder = builder.AddEnvironmentVariables();
if (addUserSecrets)
{
builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly());
}
return builder.Build();
}
}
}
| 33.708333 | 133 | 0.630408 | [
"MIT"
] | hemiaoio/abp-alain | aspnet-core/src/HeProject.Core/Configuration/AppConfigurations.cs | 1,620 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace CryptoKitties.Net.Website.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.086364 | 122 | 0.502322 | [
"MIT"
] | seanmobrien/CryptoKitty.TraderServices | src/CryptoKitties.Net.Website/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,261 | 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 Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.Data.IO;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using System;
using System.IO;
using System.Text;
namespace Microsoft.ML.Transforms.Categorical
{
public sealed partial class TermTransform
{
/// <summary>
/// These are objects shared by both the scalar and vector implementations of <see cref="Trainer"/>
/// to accumulate individual scalar objects, and facilitate the creation of a <see cref="TermMap"/>.
/// </summary>
private abstract class Builder
{
/// <summary>
/// The item type we are building into a term map.
/// </summary>
public readonly PrimitiveType ItemType;
/// <summary>
/// The number of items that would be in the map if created right now.
/// </summary>
public abstract int Count { get; }
protected Builder(PrimitiveType type)
{
Contracts.AssertValue(type);
ItemType = type;
}
public static Builder Create(ColumnType type, SortOrder sortOrder)
{
Contracts.AssertValue(type);
Contracts.Assert(type.IsVector || type.IsPrimitive);
// Right now we have only two. This "public" interface externally looks like it might
// accept any value, but currently the internal implementations of Builder are split
// along this being a purely binary option, for now (though this can easily change
// with mot implementations of Builder).
Contracts.Assert(sortOrder == SortOrder.Occurrence || sortOrder == SortOrder.Value);
bool sorted = sortOrder == SortOrder.Value;
PrimitiveType itemType = type.ItemType.AsPrimitive;
Contracts.AssertValue(itemType);
if (itemType.IsText)
return new TextImpl(sorted);
return Utils.MarshalInvoke(CreateCore<int>, itemType.RawType, itemType, sorted);
}
private static Builder CreateCore<T>(PrimitiveType type, bool sorted)
where T : IEquatable<T>, IComparable<T>
{
Contracts.AssertValue(type);
Contracts.Assert(type.RawType == typeof(T));
// If this is a type with NA values, we should ignore those NA values for the purpose
// of building our term dictionary. For the other types (practically, only the UX types),
// we should ignore nothing.
InPredicate<T> mapsToMissing;
if (!Runtime.Data.Conversion.Conversions.Instance.TryGetIsNAPredicate(type, out mapsToMissing))
mapsToMissing = (in T val) => false;
return new Impl<T>(type, mapsToMissing, sorted);
}
/// <summary>
/// Called at the end of training, to get the final mapper object.
/// </summary>
public abstract TermMap Finish();
/// <summary>
/// Handling for the "terms" arg.
/// </summary>
/// <param name="terms">The input terms argument</param>
/// <param name="ch">The channel against which to report errors and warnings</param>
public abstract void ParseAddTermArg(ref ReadOnlyMemory<char> terms, IChannel ch);
/// <summary>
/// Handling for the "term" arg.
/// </summary>
/// <param name="terms">The input terms argument</param>
/// <param name="ch">The channel against which to report errors and warnings</param>
public abstract void ParseAddTermArg(string[] terms, IChannel ch);
private sealed class TextImpl : Builder<ReadOnlyMemory<char>>
{
private readonly NormStr.Pool _pool;
private readonly bool _sorted;
public override int Count
{
get { return _pool.Count; }
}
public TextImpl(bool sorted)
: base(TextType.Instance)
{
_pool = new NormStr.Pool();
_sorted = sorted;
}
public override bool TryAdd(in ReadOnlyMemory<char> val)
{
if (val.IsEmpty)
return false;
int count = _pool.Count;
return _pool.Add(val).Id == count;
}
public override TermMap Finish()
{
if (!_sorted || _pool.Count <= 1)
return new TermMap.TextImpl(_pool);
// REVIEW: Should write a Sort method in NormStr.Pool to make sorting more memory efficient.
var perm = Utils.GetIdentityPermutation(_pool.Count);
Comparison<int> comp = (i, j) => _pool.GetNormStrById(i).Value.Span.CompareTo(_pool.GetNormStrById(j).Value.Span, StringComparison.Ordinal);
Array.Sort(perm, comp);
var sortedPool = new NormStr.Pool();
for (int i = 0; i < perm.Length; ++i)
{
var nstr = sortedPool.Add(_pool.GetNormStrById(perm[i]).Value);
Contracts.Assert(nstr.Id == i);
Contracts.Assert(i == 0 || sortedPool.GetNormStrById(i - 1).Value.Span.CompareTo(sortedPool.GetNormStrById(i).Value.Span, StringComparison.Ordinal) < 0);
}
Contracts.Assert(sortedPool.Count == _pool.Count);
return new TermMap.TextImpl(sortedPool);
}
}
/// <summary>
/// The sorted builder outputs things so that the keys are in sorted order.
/// </summary>
private sealed class Impl<T> : Builder<T>
where T : IEquatable<T>, IComparable<T>
{
// Because we can't know the actual mapping till we finish.
private readonly HashArray<T> _values;
private readonly InPredicate<T> _mapsToMissing;
private readonly bool _sort;
public override int Count
{
get { return _values.Count; }
}
/// <summary>
/// Instantiates.
/// </summary>
/// <param name="type">The type we are mapping</param>
/// <param name="mapsToMissing">This indicates whether a given value will map
/// to the missing value. If this returns true for a value then we do not attempt
/// to store it in the map.</param>
/// <param name="sort">Indicates whether to sort mapping IDs by input values.</param>
public Impl(PrimitiveType type, InPredicate<T> mapsToMissing, bool sort)
: base(type)
{
Contracts.Assert(type.RawType == typeof(T));
Contracts.AssertValue(mapsToMissing);
_values = new HashArray<T>();
_mapsToMissing = mapsToMissing;
_sort = sort;
}
public override bool TryAdd(in T val)
{
return !_mapsToMissing(in val) && _values.TryAdd(val);
}
public override TermMap Finish()
{
if (_sort)
_values.Sort();
return new TermMap.HashArrayImpl<T>(ItemType, _values);
}
}
}
private abstract class Builder<T> : Builder
{
protected Builder(PrimitiveType type)
: base(type)
{
}
/// <summary>
/// Ensures that the item is in the set. Returns true iff it added the item.
/// </summary>
/// <param name="val">The value to consider</param>
public abstract bool TryAdd(in T val);
/// <summary>
/// Handling for the "terms" arg.
/// </summary>
/// <param name="terms">The input terms argument</param>
/// <param name="ch">The channel against which to report errors and warnings</param>
public override void ParseAddTermArg(ref ReadOnlyMemory<char> terms, IChannel ch)
{
T val;
var tryParse = Runtime.Data.Conversion.Conversions.Instance.GetTryParseConversion<T>(ItemType);
for (bool more = true; more;)
{
ReadOnlyMemory<char> term;
more = ReadOnlyMemoryUtils.SplitOne(terms, ',', out term, out terms);
term = ReadOnlyMemoryUtils.TrimSpaces(term);
if (term.IsEmpty)
ch.Warning("Empty strings ignored in 'terms' specification");
else if (!tryParse(in term, out val))
throw ch.Except($"Item '{term}' in 'terms' specification could not be parsed as '{ItemType}'");
else if (!TryAdd(in val))
ch.Warning($"Duplicate item '{term}' ignored in 'terms' specification", term);
}
if (Count == 0)
throw ch.ExceptUserArg(nameof(Arguments.Terms), "Nothing parsed as '{0}'", ItemType);
}
/// <summary>
/// Handling for the "term" arg.
/// </summary>
/// <param name="terms">The input terms argument</param>
/// <param name="ch">The channel against which to report errors and warnings</param>
public override void ParseAddTermArg(string[] terms, IChannel ch)
{
T val;
var tryParse = Runtime.Data.Conversion.Conversions.Instance.GetTryParseConversion<T>(ItemType);
foreach (var sterm in terms)
{
ReadOnlyMemory<char> term = sterm.AsMemory();
term = ReadOnlyMemoryUtils.TrimSpaces(term);
if (term.IsEmpty)
ch.Warning("Empty strings ignored in 'term' specification");
else if (!tryParse(in term, out val))
ch.Warning("Item '{0}' ignored in 'term' specification since it could not be parsed as '{1}'", term, ItemType);
else if (!TryAdd(in val))
ch.Warning("Duplicate item '{0}' ignored in 'term' specification", term);
}
if (Count == 0)
throw ch.ExceptUserArg(nameof(Arguments.Terms), "Nothing parsed as '{0}'", ItemType);
}
}
/// <summary>
/// The trainer is an object that given an <see cref="Builder"/> instance, maps a particular
/// input, whether it be scalar or vector, into this and allows us to continue training on it.
/// </summary>
private abstract class Trainer
{
private readonly Builder _bldr;
private int _remaining;
public int Count { get { return _bldr.Count; } }
private Trainer(Builder bldr, int max)
{
Contracts.AssertValue(bldr);
Contracts.Assert(max >= 0);
_bldr = bldr;
_remaining = max;
}
/// <summary>
/// Creates an instance of <see cref="Trainer"/> appropriate for the type at a given
/// row and column.
/// </summary>
/// <param name="row">The row to fetch from</param>
/// <param name="col">The column to get the getter from</param>
/// <param name="count">The maximum count of items to map</param>
/// <param name="autoConvert">Whether we attempt to automatically convert
/// the input type to the desired type</param>
/// <param name="bldr">The builder we add items to</param>
/// <returns>An associated training pipe</returns>
public static Trainer Create(IRow row, int col, bool autoConvert, int count, Builder bldr)
{
Contracts.AssertValue(row);
var schema = row.Schema;
Contracts.Assert(0 <= col && col < schema.ColumnCount);
Contracts.Assert(count > 0);
Contracts.AssertValue(bldr);
var type = schema.GetColumnType(col);
Contracts.Assert(autoConvert || bldr.ItemType == type.ItemType);
// Auto conversion should only be possible when the type is text.
Contracts.Assert(type.IsText || !autoConvert);
if (type.IsVector)
return Utils.MarshalInvoke(CreateVec<int>, bldr.ItemType.RawType, row, col, count, bldr);
return Utils.MarshalInvoke(CreateOne<int>, bldr.ItemType.RawType, row, col, autoConvert, count, bldr);
}
private static Trainer CreateOne<T>(IRow row, int col, bool autoConvert, int count, Builder bldr)
{
Contracts.AssertValue(row);
Contracts.AssertValue(bldr);
Contracts.Assert(bldr is Builder<T>);
var bldrT = (Builder<T>)bldr;
ValueGetter<T> inputGetter;
if (autoConvert)
inputGetter = RowCursorUtils.GetGetterAs<T>(bldr.ItemType, row, col);
else
inputGetter = row.GetGetter<T>(col);
return new ImplOne<T>(inputGetter, count, bldrT);
}
private static Trainer CreateVec<T>(IRow row, int col, int count, Builder bldr)
{
Contracts.AssertValue(row);
Contracts.AssertValue(bldr);
Contracts.Assert(bldr is Builder<T>);
var bldrT = (Builder<T>)bldr;
var inputGetter = row.GetGetter<VBuffer<T>>(col);
return new ImplVec<T>(inputGetter, count, bldrT);
}
/// <summary>
/// Indicates to the <see cref="Trainer"/> that we have reached a new row and should consider
/// what to do with these values. Returns false if we have determined that it is no longer necessary
/// to call this train, because we've already accumulated the maximum number of values.
/// </summary>
public abstract bool ProcessRow();
/// <summary>
/// Returns a <see cref="TermMap"/> over the items in this column. Note that even if this
/// was trained over a vector valued column, the particular implementation returned here
/// should be a mapper over the item type.
/// </summary>
public TermMap Finish()
{
return _bldr.Finish();
}
private sealed class ImplOne<T> : Trainer
{
private readonly ValueGetter<T> _getter;
private T _val;
private new readonly Builder<T> _bldr;
public ImplOne(ValueGetter<T> getter, int max, Builder<T> bldr)
: base(bldr, max)
{
Contracts.AssertValue(getter);
Contracts.AssertValue(bldr);
_getter = getter;
_bldr = bldr;
}
public sealed override bool ProcessRow()
{
Contracts.Assert(_remaining >= 0);
if (_remaining <= 0)
return false;
_getter(ref _val);
return !_bldr.TryAdd(in _val) || --_remaining > 0;
}
}
private sealed class ImplVec<T> : Trainer
{
private readonly ValueGetter<VBuffer<T>> _getter;
private VBuffer<T> _val;
private new readonly Builder<T> _bldr;
private bool _addedDefaultFromSparse;
public ImplVec(ValueGetter<VBuffer<T>> getter, int max, Builder<T> bldr)
: base(bldr, max)
{
Contracts.AssertValue(getter);
Contracts.AssertValue(bldr);
_getter = getter;
_bldr = bldr;
}
private bool AccumAndDecrement(in T val)
{
Contracts.Assert(_remaining > 0);
return !_bldr.TryAdd(in val) || --_remaining > 0;
}
public sealed override bool ProcessRow()
{
Contracts.Assert(_remaining >= 0);
if (_remaining <= 0)
return false;
_getter(ref _val);
var values = _val.GetValues();
if (_val.IsDense || _addedDefaultFromSparse)
{
for (int i = 0; i < values.Length; ++i)
{
if (!AccumAndDecrement(in values[i]))
return false;
}
return true;
}
// The vector is sparse, and we have not yet tried adding the implicit default value.
// Because sparse vectors are supposed to be functionally the same as dense vectors
// and also because the order in which we see items matters for the final mapping, we
// must first add the first explicit entries where indices[i]==i, then add the default
// immediately following that, then continue with the remainder of the items. Note
// that the builder is taking care of the case where default maps to missing. Also
// note that this code is called on at most one row per column, so we aren't terribly
// excited about the slight inefficiency of that first if check.
Contracts.Assert(!_val.IsDense && !_addedDefaultFromSparse);
T def = default(T);
var valIndices = _val.GetIndices();
for (int i = 0; i < values.Length; ++i)
{
if (!_addedDefaultFromSparse && valIndices[i] != i)
{
_addedDefaultFromSparse = true;
if (!AccumAndDecrement(in def))
return false;
}
if (!AccumAndDecrement(in values[i]))
return false;
}
if (!_addedDefaultFromSparse)
{
_addedDefaultFromSparse = true;
if (!AccumAndDecrement(in def))
return false;
}
return true;
}
}
}
private enum MapType : byte
{
Text = 0,
Codec = 1,
}
/// <summary>
/// Given this instance, bind it to a particular input column. This allows us to service
/// requests on the input dataset. This should throw an error if we attempt to bind this
/// to the wrong type of item.
/// </summary>
private static BoundTermMap Bind(IHostEnvironment env, Schema schema, TermMap unbound, ColInfo[] infos, bool[] textMetadata, int iinfo)
{
env.Assert(0 <= iinfo && iinfo < infos.Length);
var info = infos[iinfo];
var inType = info.TypeSrc.ItemType;
if (!inType.Equals(unbound.ItemType))
{
throw env.Except("Could not apply a map over type '{0}' to column '{1}' since it has type '{2}'",
unbound.ItemType, info.Name, inType);
}
return BoundTermMap.Create(env, schema, unbound, infos, textMetadata, iinfo);
}
/// <summary>
/// A map is an object capable of creating the association from an input type, to an output
/// type. The input type, whatever it is, must have <see cref="ItemType"/> as its input item
/// type, and will produce either <see cref="OutputType"/>, or a vector type with that output
/// type if the input was a vector.
///
/// Note that instances of this class can be shared among multiple <see cref="TermTransform"/>
/// instances. To associate this with a particular transform, use the <see cref="Bind"/> method.
///
/// These are the immutable and serializable analogs to the <see cref="Builder"/> used in
/// training.
/// </summary>
public abstract class TermMap
{
/// <summary>
/// The item type of the input type, that is, either the input type or,
/// if a vector, the item type of that type.
/// </summary>
public readonly PrimitiveType ItemType;
/// <summary>
/// The output item type. This will always be of known cardinality. Its count is always
/// equal to <see cref="Count"/>, unless <see cref="Count"/> is 0 in which case this has
/// key count of 1, since a count of 0 would indicate an unbound key. If we ever improve
/// key types so they are capable of distinguishing between the set they index being
/// empty vs. of unknown or unbound cardinality, this should change.
/// </summary>
public readonly KeyType OutputType;
/// <summary>
/// The number of items in the map.
/// </summary>
public readonly int Count;
protected TermMap(PrimitiveType type, int count)
{
Contracts.AssertValue(type);
Contracts.Assert(count >= 0);
ItemType = type;
Count = count;
OutputType = new KeyType(DataKind.U4, 0, Count == 0 ? 1 : Count);
}
internal abstract void Save(ModelSaveContext ctx, IHostEnvironment host, CodecFactory codecFactory);
internal static TermMap Load(ModelLoadContext ctx, IHostEnvironment ectx, CodecFactory codecFactory)
{
// *** Binary format ***
// byte: map type code
// <remainer> ...
MapType mtype = (MapType)ctx.Reader.ReadByte();
ectx.CheckDecode(Enum.IsDefined(typeof(MapType), mtype));
switch (mtype)
{
case MapType.Text:
// Binary format defined by this method.
return TextImpl.Create(ctx, ectx);
case MapType.Codec:
// *** Binary format ***
// codec parameterization: the codec
// int: number of terms
// value codec block: the terms written in the codec-defined binary format
IValueCodec codec;
if (!codecFactory.TryReadCodec(ctx.Reader.BaseStream, out codec))
throw ectx.Except("Unrecognized codec read");
ectx.CheckDecode(codec.Type.IsPrimitive);
int count = ctx.Reader.ReadInt32();
ectx.CheckDecode(count >= 0);
return Utils.MarshalInvoke(LoadCodecCore<int>, codec.Type.RawType, ctx, ectx, codec, count);
default:
ectx.Assert(false);
throw ectx.Except("Unrecognized type '{0}'", mtype);
}
}
private static TermMap LoadCodecCore<T>(ModelLoadContext ctx, IExceptionContext ectx, IValueCodec codec, int count)
where T : IEquatable<T>, IComparable<T>
{
Contracts.AssertValue(ectx);
ectx.AssertValue(ctx);
ectx.AssertValue(codec);
ectx.Assert(codec is IValueCodec<T>);
ectx.Assert(codec.Type.IsPrimitive);
ectx.Assert(count >= 0);
IValueCodec<T> codecT = (IValueCodec<T>)codec;
var values = new HashArray<T>();
if (count > 0)
{
using (var reader = codecT.OpenReader(ctx.Reader.BaseStream, count))
{
T item = default(T);
for (int i = 0; i < count; i++)
{
reader.MoveNext();
reader.Get(ref item);
int index = values.Add(item);
ectx.Assert(0 <= index && index <= i);
if (index != i)
throw ectx.Except("Duplicate items at positions {0} and {1}", index, i);
}
}
}
return new HashArrayImpl<T>(codec.Type.AsPrimitive, values);
}
internal abstract void WriteTextTerms(TextWriter writer);
internal sealed class TextImpl : TermMap<ReadOnlyMemory<char>>
{
private readonly NormStr.Pool _pool;
/// <summary>
/// A pool based text mapping implementation.
/// </summary>
/// <param name="pool">The string pool</param>
public TextImpl(NormStr.Pool pool)
: base(TextType.Instance, pool.Count)
{
Contracts.AssertValue(pool);
_pool = pool;
}
public static TextImpl Create(ModelLoadContext ctx, IExceptionContext ectx)
{
// *** Binary format ***
// int: number of terms
// int[]: term string ids
// Note that this binary format as read here diverges from the save format
// insofar that the save format contains the "I am text" code, which by the
// time we reach here, we have already read.
var pool = new NormStr.Pool();
int cstr = ctx.Reader.ReadInt32();
ectx.CheckDecode(cstr >= 0);
for (int istr = 0; istr < cstr; istr++)
{
var nstr = pool.Add(ctx.LoadNonEmptyString());
ectx.CheckDecode(nstr.Id == istr);
}
// The way we "train" the termMap, they shouldn't contain the empty string.
ectx.CheckDecode(pool.Get("") == null);
return new TextImpl(pool);
}
internal override void Save(ModelSaveContext ctx, IHostEnvironment host, CodecFactory codecFactory)
{
// *** Binary format ***
// byte: map type code, in this case 'Text' (0)
// int: number of terms
// int[]: term string ids
ctx.Writer.Write((byte)MapType.Text);
host.Assert(_pool.Count >= 0);
host.CheckDecode(_pool.Get("") == null);
ctx.Writer.Write(_pool.Count);
int id = 0;
foreach (var nstr in _pool)
{
host.Assert(nstr.Id == id);
ctx.SaveNonEmptyString(nstr.Value);
id++;
}
}
private void KeyMapper(in ReadOnlyMemory<char> src, ref uint dst)
{
var nstr = _pool.Get(src);
if (nstr == null)
dst = 0;
else
dst = (uint)nstr.Id + 1;
}
public override ValueMapper<ReadOnlyMemory<char>, uint> GetKeyMapper()
{
return KeyMapper;
}
public override void GetTerms(ref VBuffer<ReadOnlyMemory<char>> dst)
{
ReadOnlyMemory<char>[] values = dst.Values;
if (Utils.Size(values) < _pool.Count)
values = new ReadOnlyMemory<char>[_pool.Count];
int slot = 0;
foreach (var nstr in _pool)
{
Contracts.Assert(0 <= nstr.Id & nstr.Id < values.Length);
Contracts.Assert(nstr.Id == slot);
values[nstr.Id] = nstr.Value;
slot++;
}
dst = new VBuffer<ReadOnlyMemory<char>>(_pool.Count, values, dst.Indices);
}
internal override void WriteTextTerms(TextWriter writer)
{
writer.WriteLine("# Number of terms = {0}", Count);
foreach (var nstr in _pool)
writer.WriteLine("{0}\t{1}", nstr.Id, nstr.Value);
}
}
internal sealed class HashArrayImpl<T> : TermMap<T>
where T : IEquatable<T>, IComparable<T>
{
// One of the two must exist. If we need one we can initialize it
// from the other.
private readonly HashArray<T> _values;
public HashArrayImpl(PrimitiveType itemType, HashArray<T> values)
// Note: The caller shouldn't pass a null HashArray.
: base(itemType, values.Count)
{
Contracts.AssertValue(values);
_values = values;
}
internal override void Save(ModelSaveContext ctx, IHostEnvironment host, CodecFactory codecFactory)
{
// *** Binary format ***
// byte: map type code, in this case 'Codec'
// codec parameterization: the codec
// int: number of terms
// value codec block: the terms written in the codec-defined binary format
IValueCodec codec;
if (!codecFactory.TryGetCodec(ItemType, out codec))
throw host.Except("We do not know how to serialize terms of type '{0}'", ItemType);
ctx.Writer.Write((byte)MapType.Codec);
host.Assert(codec.Type.Equals(ItemType));
host.Assert(codec.Type.IsPrimitive);
codecFactory.WriteCodec(ctx.Writer.BaseStream, codec);
IValueCodec<T> codecT = (IValueCodec<T>)codec;
ctx.Writer.Write(_values.Count);
using (var writer = codecT.OpenWriter(ctx.Writer.BaseStream))
{
for (int i = 0; i < _values.Count; ++i)
{
T val = _values.GetItem(i);
writer.Write(in val);
}
writer.Commit();
}
}
public override ValueMapper<T, uint> GetKeyMapper()
{
return
(in T src, ref uint dst) =>
{
int val;
if (_values.TryGetIndex(src, out val))
dst = (uint)val + 1;
else
dst = 0;
};
}
public override void GetTerms(ref VBuffer<T> dst)
{
if (Count == 0)
{
dst = new VBuffer<T>(0, dst.Values, dst.Indices);
return;
}
T[] values = dst.Values;
if (Utils.Size(values) < Count)
values = new T[Count];
Contracts.AssertValue(_values);
Contracts.Assert(_values.Count == Count);
_values.CopyTo(values);
dst = new VBuffer<T>(Count, values, dst.Indices);
}
internal override void WriteTextTerms(TextWriter writer)
{
writer.WriteLine("# Number of terms of type '{0}' = {1}", ItemType, Count);
StringBuilder sb = null;
var stringMapper = Runtime.Data.Conversion.Conversions.Instance.GetStringConversion<T>(ItemType);
for (int i = 0; i < _values.Count; ++i)
{
T val = _values.GetItem(i);
stringMapper(in val, ref sb);
writer.WriteLine("{0}\t{1}", i, sb.ToString());
}
}
}
}
public abstract class TermMap<T> : TermMap
{
protected TermMap(PrimitiveType type, int count)
: base(type, count)
{
Contracts.Assert(ItemType.RawType == typeof(T));
}
public abstract ValueMapper<T, uint> GetKeyMapper();
public abstract void GetTerms(ref VBuffer<T> dst);
}
private static void GetTextTerms<T>(in VBuffer<T> src, ValueMapper<T, StringBuilder> stringMapper, ref VBuffer<ReadOnlyMemory<char>> dst)
{
// REVIEW: This convenience function is not optimized. For non-string
// types, creating a whole bunch of string objects on the heap is one that is
// fraught with risk. Ideally we'd have some sort of "copying" text buffer builder
// but for now we'll see if this implementation suffices.
// This utility function is not intended for use when we already have text!
Contracts.Assert(typeof(T) != typeof(ReadOnlyMemory<char>));
StringBuilder sb = null;
ReadOnlyMemory<char>[] values = dst.Values;
// We'd obviously have to adjust this a bit, if we ever had sparse metadata vectors.
// The way the term map metadata getters are structured right now, this is impossible.
Contracts.Assert(src.IsDense);
if (Utils.Size(values) < src.Length)
values = new ReadOnlyMemory<char>[src.Length];
for (int i = 0; i < src.Length; ++i)
{
stringMapper(in src.Values[i], ref sb);
values[i] = sb.ToString().AsMemory();
}
dst = new VBuffer<ReadOnlyMemory<char>>(src.Length, values, dst.Indices);
}
/// <summary>
/// A mapper bound to a particular transform, and a particular column. These wrap
/// a <see cref="TermMap"/>, and facilitate mapping that object to the inputs of
/// a particular column, providing both values and metadata.
/// </summary>
private abstract class BoundTermMap
{
public readonly TermMap Map;
private readonly int _iinfo;
private readonly bool _inputIsVector;
private readonly IHostEnvironment _host;
private readonly bool[] _textMetadata;
private readonly ColInfo[] _infos;
private readonly Schema _schema;
private bool IsTextMetadata { get { return _textMetadata[_iinfo]; } }
private BoundTermMap(IHostEnvironment env, Schema schema, TermMap map, ColInfo[] infos, bool[] textMetadata, int iinfo)
{
_host = env;
//assert me.
_textMetadata = textMetadata;
_infos = infos;
_schema = schema;
_host.AssertValue(map);
_host.Assert(0 <= iinfo && iinfo < infos.Length);
var info = infos[iinfo];
_host.Assert(info.TypeSrc.ItemType.Equals(map.ItemType));
Map = map;
_iinfo = iinfo;
_inputIsVector = info.TypeSrc.IsVector;
}
public static BoundTermMap Create(IHostEnvironment host, Schema schema, TermMap map, ColInfo[] infos, bool[] textMetadata, int iinfo)
{
host.AssertValue(map);
host.Assert(0 <= iinfo && iinfo < infos.Length);
var info = infos[iinfo];
host.Assert(info.TypeSrc.ItemType.Equals(map.ItemType));
return Utils.MarshalInvoke(CreateCore<int>, map.ItemType.RawType, host, schema, map, infos, textMetadata, iinfo);
}
public static BoundTermMap CreateCore<T>(IHostEnvironment env, Schema schema, TermMap map, ColInfo[] infos, bool[] textMetadata, int iinfo)
{
TermMap<T> mapT = (TermMap<T>)map;
if (mapT.ItemType.IsKey)
return new KeyImpl<T>(env, schema, mapT, infos, textMetadata, iinfo);
return new Impl<T>(env, schema, mapT, infos, textMetadata, iinfo);
}
public abstract Delegate GetMappingGetter(IRow row);
/// <summary>
/// Allows us to optionally register metadata. It is also perfectly legal for
/// this to do nothing, which corresponds to there being no metadata.
/// </summary>
public abstract void AddMetadata(Schema.Metadata.Builder builder);
/// <summary>
/// Writes out all terms we map to a text writer, with one line per mapped term.
/// The line should have the format mapped key value, then a tab, then the term
/// that is mapped. The writer should not be closed, as it will be used to write
/// all term maps. We should write <see cref="TermMap.Count"/> terms.
/// </summary>
/// <param name="writer">The writer to which we write terms</param>
public virtual void WriteTextTerms(TextWriter writer)
{
Map.WriteTextTerms(writer);
}
private abstract class Base<T> : BoundTermMap
{
protected readonly TermMap<T> TypedMap;
public Base(IHostEnvironment env, Schema schema, TermMap<T> map, ColInfo[] infos, bool[] textMetadata, int iinfo)
: base(env, schema, map, infos, textMetadata, iinfo)
{
TypedMap = map;
}
/// <summary>
/// Returns what the default value maps to.
/// </summary>
private static uint MapDefault(ValueMapper<T, uint> map)
{
T src = default(T);
uint dst = 0;
map(in src, ref dst);
return dst;
}
public override Delegate GetMappingGetter(IRow input)
{
// When constructing the getter, there are a few cases we have to consider:
// If scalar then it's just a straightforward mapping.
// If vector, then we have to detect whether the mapping happens to be
// sparsity preserving or not, that is, if the default value maps to the
// default (missing) key. For some types this will always be true, but it
// could also be true if we happened to never see the default value in
// training.
if (!_inputIsVector)
{
ValueMapper<T, uint> map = TypedMap.GetKeyMapper();
var info = _infos[_iinfo];
T src = default(T);
Contracts.Assert(!info.TypeSrc.IsVector);
input.Schema.TryGetColumnIndex(info.Source, out int colIndex);
_host.Assert(input.IsColumnActive(colIndex));
var getSrc = input.GetGetter<T>(colIndex);
ValueGetter<uint> retVal =
(ref uint dst) =>
{
getSrc(ref src);
map(in src, ref dst);
};
return retVal;
}
else
{
// It might be tempting to move "map" and "info" out of both blocks and into
// the main block of the function, but please don't do that. The implicit
// classes created by the compiler to hold the non-vector and vector lambdas
// will have an indirect wrapping class to hold "map" and "info". This is
// bad, especially since "map" is very frequently called.
ValueMapper<T, uint> map = TypedMap.GetKeyMapper();
var info = _infos[_iinfo];
// First test whether default maps to default. If so this is sparsity preserving.
input.Schema.TryGetColumnIndex(info.Source, out int colIndex);
_host.Assert(input.IsColumnActive(colIndex));
var getSrc = input.GetGetter<VBuffer<T>>(colIndex);
VBuffer<T> src = default(VBuffer<T>);
ValueGetter<VBuffer<uint>> retVal;
// REVIEW: Consider whether possible or reasonable to not use a builder here.
var bldr = new BufferBuilder<uint>(U4Adder.Instance);
int cv = info.TypeSrc.VectorSize;
uint defaultMapValue = MapDefault(map);
uint dstItem = default(uint);
if (defaultMapValue == 0)
{
// Sparsity preserving.
retVal =
(ref VBuffer<uint> dst) =>
{
getSrc(ref src);
int cval = src.Length;
if (cv != 0 && cval != cv)
throw _host.Except("Column '{0}': TermTransform expects {1} slots, but got {2}", info.Name, cv, cval);
if (cval == 0)
{
// REVIEW: Should the VBufferBuilder be changed so that it can
// build vectors of length zero?
dst = new VBuffer<uint>(cval, dst.Values, dst.Indices);
return;
}
bldr.Reset(cval, dense: false);
var values = src.GetValues();
var indices = src.GetIndices();
int count = values.Length;
for (int islot = 0; islot < count; islot++)
{
map(in values[islot], ref dstItem);
if (dstItem != 0)
{
int slot = !src.IsDense ? indices[islot] : islot;
bldr.AddFeature(slot, dstItem);
}
}
bldr.GetResult(ref dst);
};
}
else
{
retVal =
(ref VBuffer<uint> dst) =>
{
getSrc(ref src);
int cval = src.Length;
if (cv != 0 && cval != cv)
throw _host.Except("Column '{0}': TermTransform expects {1} slots, but got {2}", info.Name, cv, cval);
if (cval == 0)
{
// REVIEW: Should the VBufferBuilder be changed so that it can
// build vectors of length zero?
dst = new VBuffer<uint>(cval, dst.Values, dst.Indices);
return;
}
// Despite default not mapping to default, it's very possible the result
// might still be sparse, for example, the source vector could be full of
// unrecognized items.
bldr.Reset(cval, dense: false);
var values = src.GetValues();
if (src.IsDense)
{
for (int slot = 0; slot < src.Length; ++slot)
{
map(in values[slot], ref dstItem);
if (dstItem != 0)
bldr.AddFeature(slot, dstItem);
}
}
else
{
var indices = src.GetIndices();
int nextExplicitSlot = indices.Length == 0 ? src.Length : indices[0];
int islot = 0;
for (int slot = 0; slot < src.Length; ++slot)
{
if (nextExplicitSlot == slot)
{
// This was an explicitly defined value.
_host.Assert(islot < values.Length);
map(in values[islot], ref dstItem);
if (dstItem != 0)
bldr.AddFeature(slot, dstItem);
nextExplicitSlot = ++islot == indices.Length ? src.Length : indices[islot];
}
else
{
_host.Assert(slot < nextExplicitSlot);
// This is a non-defined implicit default value. No need to attempt a remap
// since we already have it.
bldr.AddFeature(slot, defaultMapValue);
}
}
}
bldr.GetResult(ref dst);
};
}
return retVal;
}
}
public override void AddMetadata(Schema.Metadata.Builder builder)
{
if (TypedMap.Count == 0)
return;
if (IsTextMetadata && !TypedMap.ItemType.IsText)
{
var conv = Runtime.Data.Conversion.Conversions.Instance;
var stringMapper = conv.GetStringConversion<T>(TypedMap.ItemType);
ValueGetter<VBuffer<ReadOnlyMemory<char>>> getter =
(ref VBuffer<ReadOnlyMemory<char>> dst) =>
{
// No buffer sharing convenient here.
VBuffer<T> dstT = default;
TypedMap.GetTerms(ref dstT);
GetTextTerms(in dstT, stringMapper, ref dst);
};
builder.AddKeyValues(TypedMap.OutputType.KeyCount, TextType.Instance, getter);
}
else
{
ValueGetter<VBuffer<T>> getter =
(ref VBuffer<T> dst) =>
{
TypedMap.GetTerms(ref dst);
};
builder.AddKeyValues(TypedMap.OutputType.KeyCount, TypedMap.ItemType, getter);
}
}
}
/// <summary>
/// The key-typed version is the same as <see cref="BoundTermMap.Impl{T}"/>, except the metadata
/// is based off a subset of the key values metadata.
/// </summary>
private sealed class KeyImpl<T> : Base<T>
{
public KeyImpl(IHostEnvironment env, Schema schema, TermMap<T> map, ColInfo[] infos, bool[] textMetadata, int iinfo)
: base(env, schema, map, infos, textMetadata, iinfo)
{
_host.Assert(TypedMap.ItemType.IsKey);
}
public override void AddMetadata(Schema.Metadata.Builder builder)
{
if (TypedMap.Count == 0)
return;
_schema.TryGetColumnIndex(_infos[_iinfo].Source, out int srcCol);
ColumnType srcMetaType = _schema.GetMetadataTypeOrNull(MetadataUtils.Kinds.KeyValues, srcCol);
if (srcMetaType == null || srcMetaType.VectorSize != TypedMap.ItemType.KeyCount ||
TypedMap.ItemType.KeyCount == 0 || !Utils.MarshalInvoke(AddMetadataCore<int>, srcMetaType.ItemType.RawType, srcMetaType.ItemType, builder))
{
// No valid input key-value metadata. Back off to the base implementation.
base.AddMetadata(builder);
}
}
private bool AddMetadataCore<TMeta>(ColumnType srcMetaType, Schema.Metadata.Builder builder)
{
_host.AssertValue(srcMetaType);
_host.Assert(srcMetaType.RawType == typeof(TMeta));
_host.AssertValue(builder);
var srcType = TypedMap.ItemType.AsKey;
_host.AssertValue(srcType);
var dstType = new KeyType(DataKind.U4, srcType.Min, srcType.Count);
var convInst = Runtime.Data.Conversion.Conversions.Instance;
ValueMapper<T, uint> conv;
bool identity;
// If we can't convert this type to U4, don't try to pass along the metadata.
if (!convInst.TryGetStandardConversion<T, uint>(srcType, dstType, out conv, out identity))
return false;
_schema.TryGetColumnIndex(_infos[_iinfo].Source, out int srcCol);
ValueGetter<VBuffer<TMeta>> getter =
(ref VBuffer<TMeta> dst) =>
{
VBuffer<TMeta> srcMeta = default(VBuffer<TMeta>);
_schema.GetMetadata(MetadataUtils.Kinds.KeyValues, srcCol, ref srcMeta);
_host.Assert(srcMeta.Length == srcType.Count);
VBuffer<T> keyVals = default(VBuffer<T>);
TypedMap.GetTerms(ref keyVals);
TMeta[] values = dst.Values;
if (Utils.Size(values) < TypedMap.OutputType.KeyCount)
values = new TMeta[TypedMap.OutputType.KeyCount];
uint convKeyVal = 0;
foreach (var pair in keyVals.Items(all: true))
{
T keyVal = pair.Value;
conv(in keyVal, ref convKeyVal);
// The builder for the key values should not have any missings.
_host.Assert(0 < convKeyVal && convKeyVal <= srcMeta.Length);
srcMeta.GetItemOrDefault((int)(convKeyVal - 1), ref values[pair.Key]);
}
dst = new VBuffer<TMeta>(TypedMap.OutputType.KeyCount, values, dst.Indices);
};
if (IsTextMetadata && !srcMetaType.IsText)
{
var stringMapper = convInst.GetStringConversion<TMeta>(srcMetaType);
ValueGetter<VBuffer<ReadOnlyMemory<char>>> mgetter =
(ref VBuffer<ReadOnlyMemory<char>> dst) =>
{
var tempMeta = default(VBuffer<TMeta>);
getter(ref tempMeta);
Contracts.Assert(tempMeta.IsDense);
GetTextTerms(in tempMeta, stringMapper, ref dst);
_host.Assert(dst.Length == TypedMap.OutputType.KeyCount);
};
builder.AddKeyValues(TypedMap.OutputType.KeyCount, TextType.Instance, mgetter);
}
else
{
ValueGetter<VBuffer<TMeta>> mgetter =
(ref VBuffer<TMeta> dst) =>
{
getter(ref dst);
_host.Assert(dst.Length == TypedMap.OutputType.KeyCount);
};
builder.AddKeyValues(TypedMap.OutputType.KeyCount, srcMetaType.ItemType.AsPrimitive, mgetter);
}
return true;
}
public override void WriteTextTerms(TextWriter writer)
{
if (TypedMap.Count == 0)
return;
_schema.TryGetColumnIndex(_infos[_iinfo].Source, out int srcCol);
ColumnType srcMetaType = _schema.GetMetadataTypeOrNull(MetadataUtils.Kinds.KeyValues, srcCol);
if (srcMetaType == null || srcMetaType.VectorSize != TypedMap.ItemType.KeyCount ||
TypedMap.ItemType.KeyCount == 0 || !Utils.MarshalInvoke(WriteTextTermsCore<int>, srcMetaType.ItemType.RawType, srcMetaType.AsVector.ItemType, writer))
{
// No valid input key-value metadata. Back off to the base implementation.
base.WriteTextTerms(writer);
}
}
private bool WriteTextTermsCore<TMeta>(PrimitiveType srcMetaType, TextWriter writer)
{
_host.AssertValue(srcMetaType);
_host.Assert(srcMetaType.RawType == typeof(TMeta));
var srcType = TypedMap.ItemType.AsKey;
_host.AssertValue(srcType);
var dstType = new KeyType(DataKind.U4, srcType.Min, srcType.Count);
var convInst = Runtime.Data.Conversion.Conversions.Instance;
ValueMapper<T, uint> conv;
bool identity;
// If we can't convert this type to U4, don't try.
if (!convInst.TryGetStandardConversion<T, uint>(srcType, dstType, out conv, out identity))
return false;
_schema.TryGetColumnIndex(_infos[_iinfo].Source, out int srcCol);
VBuffer<TMeta> srcMeta = default(VBuffer<TMeta>);
_schema.GetMetadata(MetadataUtils.Kinds.KeyValues, srcCol, ref srcMeta);
if (srcMeta.Length != srcType.Count)
return false;
VBuffer<T> keyVals = default(VBuffer<T>);
TypedMap.GetTerms(ref keyVals);
TMeta metaVal = default(TMeta);
uint convKeyVal = 0;
StringBuilder sb = null;
var keyStringMapper = convInst.GetStringConversion<T>(TypedMap.ItemType);
var metaStringMapper = convInst.GetStringConversion<TMeta>(srcMetaType);
writer.WriteLine("# Number of terms of key '{0}' indexing '{1}' value = {2}",
TypedMap.ItemType, srcMetaType, TypedMap.Count);
foreach (var pair in keyVals.Items(all: true))
{
T keyVal = pair.Value;
conv(in keyVal, ref convKeyVal);
// The key mapping will not have admitted missing keys.
_host.Assert(0 < convKeyVal && convKeyVal <= srcMeta.Length);
srcMeta.GetItemOrDefault((int)(convKeyVal - 1), ref metaVal);
keyStringMapper(in keyVal, ref sb);
writer.Write("{0}\t{1}", pair.Key, sb.ToString());
metaStringMapper(in metaVal, ref sb);
writer.WriteLine("\t{0}", sb.ToString());
}
return true;
}
}
private sealed class Impl<T> : Base<T>
{
public Impl(IHostEnvironment env, Schema schema, TermMap<T> map, ColInfo[] infos, bool[] textMetadata, int iinfo)
: base(env, schema, map, infos, textMetadata, iinfo)
{
}
}
}
}
}
| 47.753425 | 177 | 0.47506 | [
"MIT"
] | thomshib/machinelearning | src/Microsoft.ML.Data/Transforms/TermTransformImpl.cs | 59,264 | C# |
using HunterPie.Core.Monsters;
namespace HunterPie.Core
{
public class Part
{
private readonly MonsterInfo monsterInfo;
private readonly PartInfo partInfo;
private readonly int id; // Part index
private float health;
private float totalHealth;
private byte brokenCounter;
public Part(MonsterInfo monsterInfo, PartInfo partInfo, int index)
{
this.monsterInfo = monsterInfo;
this.partInfo = partInfo;
id = index;
}
public long PartAddress { get; set; } // So we don't need to re-scan the address everytime
public string Name => GStrings.GetMonsterPartByID(partInfo.Id);
public int[] BreakThresholds => partInfo.BreakThresholds;
public byte BrokenCounter
{
get => brokenCounter;
set
{
if (value != brokenCounter)
{
brokenCounter = value;
NotifyBrokenCounterChanged();
}
}
}
public float Health
{
get => health;
set
{
if (value != health)
{
health = value;
NotifyHealthChanged();
}
}
}
public float TotalHealth
{
get => totalHealth;
set
{
if (value != totalHealth)
{
totalHealth = value;
}
}
}
public bool IsRemovable { get; set; }
public string Group { get; set; }
#region Events
public delegate void MonsterPartEvents(object source, MonsterPartEventArgs args);
public event MonsterPartEvents OnHealthChange;
public event MonsterPartEvents OnBrokenCounterChange;
protected virtual void NotifyHealthChanged()
{
OnHealthChange?.Invoke(this, new MonsterPartEventArgs(this));
}
protected virtual void NotifyBrokenCounterChanged()
{
OnBrokenCounterChange?.Invoke(this, new MonsterPartEventArgs(this));
Logger.Debugger.Debug($"Broken {GStrings.GetMonsterNameByID(monsterInfo.Em)} ({monsterInfo.Id}) part {Name} ({id}), {TotalHealth} hp for {brokenCounter} time");
}
#endregion
public void SetPartInfo(byte breakCounter, float health, float totalHealth)
{
TotalHealth = totalHealth;
BrokenCounter = breakCounter;
Health = health;
}
public override string ToString()
{
return $"Name: {Name} | ID: {id} | HP: {Health}/{TotalHealth} | Counter: {BrokenCounter}";
}
}
}
| 27.588235 | 172 | 0.534826 | [
"MIT"
] | yonguelink/HunterPie | HunterPie/Core/Monsters/Part.cs | 2,816 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using AppKit;
using GameLoader.Mac.Model;
namespace GameLoader.Mac
{
public partial class HexArchiveItemController : NSCollectionViewItem
{
private HexArchive hexArchive;
#region Constructors
// Called when created from unmanaged code
public HexArchiveItemController(IntPtr handle) : base(handle)
{
Initialize();
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public HexArchiveItemController(NSCoder coder) : base(coder)
{
Initialize();
}
// Call to load from the XIB/NIB file
public HexArchiveItemController() : base("HexArchiveItem", NSBundle.MainBundle)
{
Initialize();
}
// Shared initialization code
void Initialize()
{
}
#endregion
//strongly typed view accessor
public new HexArchiveItem View
{
get
{
return (HexArchiveItem)base.View;
}
}
[Export("HexArchive")]
public HexArchive HexArchive
{
get { return hexArchive; }
set
{
WillChangeValue(nameof(HexArchive));
hexArchive = value;
DidChangeValue(nameof(HexArchive));
}
}
public NSColor BackgroundColor
{
get { return ItemBox.FillColor; }
set { ItemBox.FillColor = value; }
}
public override bool Selected
{
get
{
return base.Selected;
}
set
{
base.Selected = value;
BackgroundColor = value ? NSColor.FromRgb(200, 200, 200) : NSColor.Control;
}
}
}
}
| 22.27381 | 91 | 0.545163 | [
"MIT"
] | Team-ARG-Museum/GameLoaderMac | GameLoader.Mac/HexArchiveItemController.cs | 1,873 | C# |
using System.Collections;
using UnityEngine;
namespace AbyssMothGames.LawnMowerWorld
{
public sealed class OilAnimated : MonoBehaviour
{
[SerializeField] private GameObject oilPrefab;
[SerializeField] private float secondsDrop = 1.5f;
private void Start() => StartCoroutine(nameof(OilDrop));
private IEnumerator OilDrop()
{
while (true)
{
Instantiate(oilPrefab, transform.position, Quaternion.identity);
yield return new WaitForSeconds(secondsDrop);
}
}
}
} | 25.652174 | 80 | 0.622034 | [
"MIT"
] | RimuruDev/Low-poly-lawn | Lawn Mower World - Adventure/Assets/InternalAssets/Scripts/MonoBehaviour/AllOthers/OilAnimated.cs | 592 | C# |
using System;
namespace Newtonsoft_X.Json.Utilities
{
internal delegate TResult MethodCall<T, TResult>(T target, params object[] args);
}
| 20.571429 | 85 | 0.756944 | [
"MIT"
] | RedAWM/GDNet | GameDesigner/Serialize/Newtonsoft.Json/Utilities/MethodCall.cs | 146 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Arebis.Caching
{
/// <summary>
/// A generic EventArgs, containing a Value of type T.
/// </summary>
public class ValueEventArgs<T> : EventArgs
{
public ValueEventArgs(T item)
{
this.Item = item;
}
public T Item { get; private set; }
}
public class ResolveValueEventArgs<TKey, TValue> : EventArgs
{
private TValue _value;
public ResolveValueEventArgs(TKey key)
{
this.Key = key;
}
public TKey Key { get; private set; }
public bool IsResolved { get; private set; }
public TValue Value
{
get
{
return _value;
}
set
{
_value = value;
IsResolved = true;
}
}
}
}
| 20.729167 | 65 | 0.477387 | [
"MIT"
] | FingersCrossed/Arebis.Common | Arebis.Common/Arebis/Caching/ValueEventArgs.cs | 997 | C# |
using System;
using System.Numerics;
namespace DirectionalPathingLayers
{
/// <summary>
/// Individual node that contains directions as a boolean value.
/// </summary>
public struct DirectionalNode
{
/// <summary> Array of directions, in a forward, backward, left, right, up, down format. </summary>
public Matrix3x2 Directions { get => this.directions; }
Matrix3x2 directions;
public enum DirectionEnum
{
forward = 0, //M1,1
backward = 1,//M1,2
left = 2, //M2,1
right = 3, //M2,2
up = 4, //M3,1
down = 5 //M,2
};
//Faster operations to get a single retrieved.
public Single sForward { get => this.directions.M11; }
public Single sBackward { get => this.directions.M12; }
public Single sLeft { get => this.directions.M21; }
public Single sRight { get => this.directions.M22; }
public Single sUp { get => this.directions.M31; }
public Single sDown { get => this.directions.M32; }
public int Forward { get => (int)this.sForward; }
public int Backward { get => (int)this.sBackward; }
public int Left { get => (int)this.sLeft; }
public int Right { get => (int)this.sRight; }
public int Up { get => (int)this.sUp; }
public int Down { get => (int)this.sDown; }
public int DirectionByIndex(int index)
{
switch (index)
{
case (int)DirectionEnum.forward:
{
return this.Forward;
}
case (int)DirectionEnum.backward:
{
return this.Backward;
}
case (int)DirectionEnum.left:
{
return this.Left;
}
case (int)DirectionEnum.right:
{
return this.Right;
}
case (int)DirectionEnum.up:
{
return this.Up;
}
case (int)DirectionEnum.down:
{
return this.Down;
}
default:
{
throw new System.ArgumentException("Invalid index used");
return 0;
}
}
}
public DirectionalNode(int initialValue)
{
//this.directions = new Matrix3x2();
this.directions.M11 = initialValue;
this.directions.M12 = initialValue;
this.directions.M21 = initialValue;
this.directions.M22 = initialValue;
this.directions.M31 = initialValue;
this.directions.M32 = initialValue;
}
public DirectionalNode(in DirectionalNode initialNode)
{
this.directions = initialNode.directions;
//for (int i = 0; i < 6; ++i) { this.directions[i] = initialNode.directions[i]; }
}
public DirectionalNode(int forward, int backward, int left, int right, int up, int down)
{
this.directions.M11 = forward;
this.directions.M12 = backward;
this.directions.M21 = left;
this.directions.M22 = right;
this.directions.M31 = up;
this.directions.M32 = down;
//this.directions = new Matrix3x2(forward, backward, left, right, up, down);
}
DirectionalNode(Single forward, Single backward, Single left, Single right, Single up, Single down)
{
this.directions.M11 = forward;
this.directions.M12 = backward;
this.directions.M21 = left;
this.directions.M22 = right;
this.directions.M31 = up;
this.directions.M32 = down;
}
DirectionalNode(Matrix3x2 directionsMatrix)
{
this.directions = directionsMatrix;
}
//void Set(int setValue)
//{
// this.directions = new Matrix3x2(setValue, setValue, setValue, setValue, setValue, setValue);
//}
/// <summary>
/// Logical AND on each direction.
/// This returns output as '1' or '0'.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator &(DirectionalNode left, DirectionalNode right)
{
Single And(int leftValue, int rightValue)
{
return (leftValue != 0) && (rightValue != 0)? 1.0f : 0.0f;
}
return new DirectionalNode(And(left.Forward, right.Forward),
And(left.Backward, right.Backward),
And(left.Left, right.Left),
And(left.Right, right.Right),
And(left.Up, right.Up),
And(left.Down, right.Down)
);
//for (int i = 0; i < 6; ++i)
//{
// newNode.directions[i] = (SByte)((left.directions[i] != 0 && right.directions[i] != 0) ? 1 : 0);
//}
//return newNode;
}
/// <summary>
/// Logical OR on each direction.
/// This returns output as '1' or '0'.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator |(DirectionalNode left, DirectionalNode right)
{
Single Or(int leftValue, int rightValue)
{
return (leftValue != 0) || (rightValue != 0) ? 1.0f : 0.0f;
}
return new DirectionalNode(Or(left.Forward, right.Forward),
Or(left.Backward, right.Backward),
Or(left.Left, right.Left),
Or(left.Right, right.Right),
Or(left.Up, right.Up),
Or(left.Down, right.Down)
);
//DirectionalNode newNode = new DirectionalNode(0);
//for (int i = 0; i < left.directions.Length; ++i)
//{
// newNode.directions[i] = (SByte)((left.directions[i] != 0 || right.directions[i] != 0) ? 1 : 0);
//}
//return newNode;
}
/// <summary>
/// integer AND on each element.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator +(DirectionalNode left, DirectionalNode right)
{
return new DirectionalNode(left.directions + right.directions);
}
/// <summary>
/// integer SUB on each element.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator -(DirectionalNode left, DirectionalNode right)
{
return new DirectionalNode(left.directions - right.directions);
}
/// <summary>
/// integer MULT on each element.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator *(in DirectionalNode left, in DirectionalNode right)
{
//DirectionalNode newNode;
//newNode.directions = left.directions * right.directions;
//return newNode;
return new DirectionalNode(left.directions * right.directions);
}
public static DirectionalNode operator *(int left, DirectionalNode right)
{
Single singleLeft = (Single)left;
return new DirectionalNode(singleLeft * right.sForward,
singleLeft * right.sBackward,
singleLeft * right.sLeft,
singleLeft * right.sRight,
singleLeft * right.sUp,
singleLeft * right.sDown
);
}
/// <summary>
/// Logical XOR on each direction.
/// This returns output as '1' or '0'.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static DirectionalNode operator ^(DirectionalNode left, DirectionalNode right)
{
Single XOr(int leftValue, int rightValue)
{
return ((leftValue == 0) && (rightValue != 0) ||
(leftValue != 0) && (rightValue == 0)) ? 1.0f : 0.0f;
}
return new DirectionalNode(XOr(left.Forward, right.Forward),
XOr(left.Backward, right.Backward),
XOr(left.Left, right.Left),
XOr(left.Right, right.Right),
XOr(left.Up, right.Up),
XOr(left.Down, right.Down)
);
}
/// <summary>
/// Logical invert on each direction.
/// This returns output as '1' or '0'.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static DirectionalNode operator ~(DirectionalNode node)
{
Single Invert(int value)
{
return (value == 0 ) ? 1.0f : 0.0f;
}
return new DirectionalNode(Invert(node.Forward),
Invert(node.Backward),
Invert(node.Left),
Invert(node.Right),
Invert(node.Up),
Invert(node.Down)
);
}
public override string ToString()
{
return "[" + string.Join(",", this.directions) + "]";
}
public override bool Equals(object obj)
{
return this.Equals((DirectionalNode)obj);
}
public bool Equals(DirectionalNode other)
{
return this.directions.Equals(other.directions);
}
public override int GetHashCode()
{
return HashCode.Combine(this.directions);
}
}
} | 36.17377 | 113 | 0.467325 | [
"MIT"
] | GrahamMueller1992/DirectionalPathingLayers | Runtime/Layer/DirectionalNode.cs | 11,035 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbhsChinese.Domain.Entity
{
[Table("Yw_CoursePriceAudit")]
public class Yw_CoursePriceAudit : EntityBase
{
[Key]
public int Ypa_Id { get; set; }
private int ypa_CourseId;
public int Ypa_CourseId
{
set
{
AuditCheck("Ypa_CourseId", value);
ypa_CourseId = value;
}
get
{
return ypa_CourseId;
}
}
private int ypa_SchoolLevelId;
public int Ypa_SchoolLevelId
{
set
{
AuditCheck("Ypa_SchoolLevelId", value);
ypa_SchoolLevelId = value;
}
get
{
return ypa_SchoolLevelId;
}
}
private decimal ypa_OldPrice;
public decimal Ypa_OldPrice
{
set
{
AuditCheck("Ypa_OldPrice", value);
ypa_OldPrice = value;
}
get
{
return ypa_OldPrice;
}
}
private decimal ypa_NewPrice;
public decimal Ypa_NewPrice
{
set
{
AuditCheck("Ypa_NewPrice", value);
ypa_NewPrice = value;
}
get
{
return ypa_NewPrice;
}
}
private DateTime ypa_CreateTime;
public DateTime Ypa_CreateTime
{
set
{
AuditCheck("Ypa_CreateTime", value);
ypa_CreateTime = value;
}
get
{
return ypa_CreateTime;
}
}
private int ypa_Creator;
public int Ypa_Creator
{
set
{
AuditCheck("Ypa_Creator", value);
ypa_Creator = value;
}
get
{
return ypa_Creator;
}
}
}
}
| 21.71 | 55 | 0.431598 | [
"Apache-2.0"
] | GuoQqizz/SmartChinese | AbhsChinese.Domain/Entity/Yw_CoursePriceAudit.cs | 2,173 | C# |
namespace testproject.Authorization.Accounts.Dto
{
public class IsTenantAvailableOutput
{
public TenantAvailabilityState State { get; set; }
public int? TenantId { get; set; }
public IsTenantAvailableOutput()
{
}
public IsTenantAvailableOutput(TenantAvailabilityState state, int? tenantId = null)
{
State = state;
TenantId = tenantId;
}
}
}
| 22.2 | 91 | 0.603604 | [
"MIT"
] | akhiljosef/testproject | aspnet-core/src/testproject.Application/Authorization/Accounts/Dto/IsTenantAvailableOutput.cs | 444 | C# |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MLifter.DAL.Security;
using MLifter.DAL.Tools;
namespace MLifter.DAL.Interfaces
{
/// <summary>
/// Interface which defines dictionaries.
/// </summary>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
public interface IDictionaries : IParent, ISecurity
{
/// <summary>
/// Gets all learning modules.
/// </summary>
/// <value>The dictionaries.</value>
/// <remarks>Documented by Dev02, 2008-07-28</remarks>
IList<IDictionary> Dictionaries { get; }
/// <summary>
/// Gets the specified learning module.
/// </summary>
/// <param name="id">The id of the learning module.</param>
/// <returns></returns>
/// <remarks>Documented by Dev02, 2008-07-28</remarks>
IDictionary Get(int id);
/// <summary>
/// Deletes a specific LM.
/// </summary>
/// <param name="css">The connection string struct.</param>
/// <remarks>Documented by Dev02, 2008-07-28</remarks>
/// <remarks>Documented by Dev08, 2008-12-09</remarks>
void Delete(ConnectionStringStruct css);
/// <summary>
/// Adds a new learning module.
/// </summary>
/// <param name="categoryId">The category id.</param>
/// <param name="title">The title.</param>
/// <returns>The new learning module.</returns>
/// <remarks>Documented by Dev02, 2008-07-28</remarks>
IDictionary AddNew(int categoryId, string title);
/// <summary>
/// Adds a new learning module.
/// </summary>
/// <param name="categoryId">The category id.</param>
/// <param name="title">The title.</param>
/// <param name="licenceKey">The licence key.</param>
/// <param name="contentProtected">if set to <c>true</c> the content is protected.</param>
/// <param name="calCount">The cal count.</param>
/// <returns></returns>
/// <remarks>
/// Documented by CFI, 2009-02-12
/// </remarks>
IDictionary AddNew(int categoryId, string title, string licenceKey, bool contentProtected, int calCount);
/// <summary>
/// Gets the count of learning modules.
/// </summary>
/// <value>The count.</value>
/// <remarks>Documented by Dev02, 2008-07-28</remarks>
int Count { get; }
/// <summary>
/// Gets all extensions (independent of the LearningModule id).
/// </summary>
/// <value>The extensions.</value>
/// <remarks>Documented by Dev08, 2009-07-02</remarks>
IList<IExtension> Extensions { get; }
/// <summary>
/// Creates new extensions.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev02, 2009-07-06</remarks>
IExtension ExtensionFactory();
/// <summary>
/// Deletes the extension.
/// </summary>
/// <param name="extension">The extension.</param>
/// <remarks>Documented by Dev02, 2009-07-10</remarks>
void DeleteExtension(IExtension extension);
}
}
| 42.834951 | 137 | 0.56981 | [
"MIT"
] | hmehr/OSS | MemoryLifter/Development/Current/MLifter.DAL/Interfaces/IDictionaries.cs | 4,412 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using session.Models;
namespace session
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
| 39.272727 | 152 | 0.659259 | [
"MIT"
] | jesus9ias/csharppininous | session/App_Start/IdentityConfig.cs | 4,322 | C# |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. Inc.
*
* 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.
</FILE_LICENSE>*/
using System;
using System.Drawing;
using NFX.Graphics;
using NFX.Scripting;
namespace NFX.UTest.Graphics
{
[Runnable(TRUN.BASE)]
public class ColorXlatTests
{
[Run]
public void ToHTML()
{
var color = Color.Empty;
var html = ColorXlat.ToHTML(color);
Aver.AreEqual("#000", html);
color = Color.White;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#FFFFFF", html);
color = Color.Black;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#000000", html);
color = Color.Red;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#FF0000", html);
color = Color.Green;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#008000", html);
color = Color.Lime;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#00FF00", html);
color = Color.Blue;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#0000FF", html);
color = Color.Yellow;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#FFFF00", html);
color = Color.Magenta;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#FF00FF", html);
color = Color.Aqua;
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#00FFFF", html);
color = Color.FromArgb(128, 128, 128);
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#808080", html);
color = Color.FromArgb(42, 10, 8);
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#2A0A08", html);
color = Color.FromArgb(153, 153, 153);
html = ColorXlat.ToHTML(color);
Aver.AreEqual("#999999", html);
}
[Run]
public void FromHTML()
{
var html = string.Empty;
var color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Empty, color);
html = "#FFFFFF";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
html = "#FFF";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
html = "#ffF";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
html = "#fFFffF";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
html = "white";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
html = "#f00";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Red, color);
html = "#00Ff00";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Lime, color);
html = "green";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Green, color);
html = "#0000ff";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Blue, color);
html = "#Ff0";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Yellow, color);
html = "#888";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.FromArgb(136, 136, 136), color);
html = "#Ccc";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.FromArgb(204, 204, 204), color);
html = "#80Abe9";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.FromArgb(128, 171, 233), color);
}
[Run]
public void FromHTMLNegative()
{
var html = "FFFFFF";
var color = ColorXlat.FromHTML(html);
colorAreEqual(Color.Empty, color);
html = "#fffz";
color = ColorXlat.FromHTML(html);
colorAreEqual(Color.White, color);
try
{
html = "##fff";
color = ColorXlat.FromHTML(html);
Aver.Fail("ArgumentException is expected");
}
catch (Exception ex)
{
Aver.IsTrue(ex is ArgumentException);
}
}
private void colorAreEqual(Color c1, Color c2)
{
Aver.AreEqual(c1.R, c2.R);
Aver.AreEqual(c1.G, c2.G);
Aver.AreEqual(c1.B, c2.B);
}
}
}
| 25.931818 | 74 | 0.617003 | [
"Apache-2.0"
] | agnicore/nfx | src/testing/NFX.UTest/Graphics/ColorXlatTests.cs | 4,566 | 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.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Tests
{
public class EnumTests
{
public static IEnumerable<object[]> Parse_TestData()
{
// SByte
yield return new object[] { "Min", false, SByteEnum.Min };
yield return new object[] { "mAx", true, SByteEnum.Max };
yield return new object[] { "1", false, SByteEnum.One };
yield return new object[] { "5", false, (SByteEnum)5 };
yield return new object[] { sbyte.MinValue.ToString(), false, (SByteEnum)sbyte.MinValue };
yield return new object[] { sbyte.MaxValue.ToString(), false, (SByteEnum)sbyte.MaxValue };
// Byte
yield return new object[] { "Min", false, ByteEnum.Min };
yield return new object[] { "mAx", true, ByteEnum.Max };
yield return new object[] { "1", false, ByteEnum.One };
yield return new object[] { "5", false, (ByteEnum)5 };
yield return new object[] { byte.MinValue.ToString(), false, (ByteEnum)byte.MinValue };
yield return new object[] { byte.MaxValue.ToString(), false, (ByteEnum)byte.MaxValue };
// Int16
yield return new object[] { "Min", false, Int16Enum.Min };
yield return new object[] { "mAx", true, Int16Enum.Max };
yield return new object[] { "1", false, Int16Enum.One };
yield return new object[] { "5", false, (Int16Enum)5 };
yield return new object[] { short.MinValue.ToString(), false, (Int16Enum)short.MinValue };
yield return new object[] { short.MaxValue.ToString(), false, (Int16Enum)short.MaxValue };
// UInt16
yield return new object[] { "Min", false, UInt16Enum.Min };
yield return new object[] { "mAx", true, UInt16Enum.Max };
yield return new object[] { "1", false, UInt16Enum.One };
yield return new object[] { "5", false, (UInt16Enum)5 };
yield return new object[] { ushort.MinValue.ToString(), false, (UInt16Enum)ushort.MinValue };
yield return new object[] { ushort.MaxValue.ToString(), false, (UInt16Enum)ushort.MaxValue };
// Int32
yield return new object[] { "Min", false, Int32Enum.Min };
yield return new object[] { "mAx", true, Int32Enum.Max };
yield return new object[] { "1", false, Int32Enum.One };
yield return new object[] { "5", false, (Int32Enum)5 };
yield return new object[] { int.MinValue.ToString(), false, (Int32Enum)int.MinValue };
yield return new object[] { int.MaxValue.ToString(), false, (Int32Enum)int.MaxValue };
// UInt32
yield return new object[] { "Min", false, UInt32Enum.Min };
yield return new object[] { "mAx", true, UInt32Enum.Max };
yield return new object[] { "1", false, UInt32Enum.One };
yield return new object[] { "5", false, (UInt32Enum)5 };
yield return new object[] { uint.MinValue.ToString(), false, (UInt32Enum)uint.MinValue };
yield return new object[] { uint.MaxValue.ToString(), false, (UInt32Enum)uint.MaxValue };
// Int64
yield return new object[] { "Min", false, Int64Enum.Min };
yield return new object[] { "mAx", true, Int64Enum.Max };
yield return new object[] { "1", false, Int64Enum.One };
yield return new object[] { "5", false, (Int64Enum)5 };
yield return new object[] { long.MinValue.ToString(), false, (Int64Enum)long.MinValue };
yield return new object[] { long.MaxValue.ToString(), false, (Int64Enum)long.MaxValue };
// UInt64
yield return new object[] { "Min", false, UInt64Enum.Min };
yield return new object[] { "mAx", true, UInt64Enum.Max };
yield return new object[] { "1", false, UInt64Enum.One };
yield return new object[] { "5", false, (UInt64Enum)5 };
yield return new object[] { ulong.MinValue.ToString(), false, (UInt64Enum)ulong.MinValue };
yield return new object[] { ulong.MaxValue.ToString(), false, (UInt64Enum)ulong.MaxValue };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { "Value1", false, Enum.ToObject(s_charEnumType, (char)1) };
yield return new object[] { "vaLue2", true, Enum.ToObject(s_charEnumType, (char)2) };
yield return new object[] { "1", false, Enum.ToObject(s_charEnumType, '1') };
// Bool
yield return new object[] { "Value1", false, Enum.ToObject(s_boolEnumType, true) };
yield return new object[] { "vaLue2", true, Enum.ToObject(s_boolEnumType, false) };
if (!PlatformDetection.IsMonoRuntime) // [ActiveIssue("https://github.com/dotnet/runtime/issues/29266")]
{
// Single - parses successfully, but doesn't properly represent the underlying value
yield return new object[] { "Value1", false, Enum.GetValues(s_floatEnumType).GetValue(0) };
yield return new object[] { "vaLue2", true, Enum.GetValues(s_floatEnumType).GetValue(0) };
// Double - parses successfully, but doesn't properly represent the underlying value
yield return new object[] { "Value1", false, Enum.GetValues(s_doubleEnumType).GetValue(0) };
yield return new object[] { "vaLue2", true, Enum.GetValues(s_doubleEnumType).GetValue(0) };
}
}
// SimpleEnum
yield return new object[] { "Red", false, SimpleEnum.Red };
yield return new object[] { " Red", false, SimpleEnum.Red };
yield return new object[] { "Red ", false, SimpleEnum.Red };
yield return new object[] { " red ", true, SimpleEnum.Red };
yield return new object[] { "B", false, SimpleEnum.B };
yield return new object[] { "B,B", false, SimpleEnum.B };
yield return new object[] { " Red , Blue ", false, SimpleEnum.Red | SimpleEnum.Blue };
yield return new object[] { "Blue,Red,Green", false, SimpleEnum.Red | SimpleEnum.Blue | SimpleEnum.Green };
yield return new object[] { "Blue,Red,Red,Red,Green", false, SimpleEnum.Red | SimpleEnum.Blue | SimpleEnum.Green };
yield return new object[] { "Red,Blue, Green", false, SimpleEnum.Red | SimpleEnum.Blue | SimpleEnum.Green };
yield return new object[] { "1", false, SimpleEnum.Red };
yield return new object[] { " 1 ", false, SimpleEnum.Red };
yield return new object[] { "2", false, SimpleEnum.Blue };
yield return new object[] { "99", false, (SimpleEnum)99 };
yield return new object[] { "-42", false, (SimpleEnum)(-42) };
yield return new object[] { " -42", false, (SimpleEnum)(-42) };
yield return new object[] { " -42 ", false, (SimpleEnum)(-42) };
}
[Theory]
[MemberData(nameof(Parse_TestData))]
public static void Parse<T>(string value, bool ignoreCase, T expected) where T : struct
{
T result;
if (!ignoreCase)
{
Assert.True(Enum.TryParse(value.AsSpan(), out result));
Assert.Equal(expected, result);
Assert.True(Enum.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, Enum.Parse(expected.GetType(), value.AsSpan()));
Assert.Equal(expected, Enum.Parse(expected.GetType(), value));
Assert.Equal(expected, Enum.Parse<T>(value.AsSpan()));
Assert.Equal(expected, Enum.Parse<T>(value));
}
Assert.True(Enum.TryParse(value.AsSpan(), ignoreCase, out result));
Assert.Equal(expected, result);
Assert.True(Enum.TryParse(value, ignoreCase, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, Enum.Parse(expected.GetType(), value.AsSpan(), ignoreCase));
Assert.Equal(expected, Enum.Parse(expected.GetType(), value, ignoreCase));
Assert.Equal(expected, Enum.Parse<T>(value.AsSpan(), ignoreCase));
Assert.Equal(expected, Enum.Parse<T>(value, ignoreCase));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, "", false, typeof(ArgumentNullException) };
yield return new object[] { typeof(object), "", false, typeof(ArgumentException) };
yield return new object[] { typeof(int), "", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), null, false, typeof(ArgumentNullException) };
yield return new object[] { typeof(SimpleEnum), "", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), " \t", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), " red ", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Purple", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), ",Red", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Red,", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "B,", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), " , , ,", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Red,Blue,", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Red,,Blue", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Red,Blue, ", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Red Blue", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "1,Blue", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "1,1", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Blue,1", false, typeof(ArgumentException) };
yield return new object[] { typeof(SimpleEnum), "Blue, 1", false, typeof(ArgumentException) };
yield return new object[] { typeof(ByteEnum), "-1", false, typeof(OverflowException) };
yield return new object[] { typeof(ByteEnum), "256", false, typeof(OverflowException) };
yield return new object[] { typeof(SByteEnum), "-129", false, typeof(OverflowException) };
yield return new object[] { typeof(SByteEnum), "128", false, typeof(OverflowException) };
yield return new object[] { typeof(Int16Enum), "-32769", false, typeof(OverflowException) };
yield return new object[] { typeof(Int16Enum), "32768", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt16Enum), "-1", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt16Enum), "65536", false, typeof(OverflowException) };
yield return new object[] { typeof(Int32Enum), "-2147483649", false, typeof(OverflowException) };
yield return new object[] { typeof(Int32Enum), "2147483648", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt32Enum), "-1", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt32Enum), "4294967296", false, typeof(OverflowException) };
yield return new object[] { typeof(Int64Enum), "-9223372036854775809", false, typeof(OverflowException) };
yield return new object[] { typeof(Int64Enum), "9223372036854775808", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt64Enum), "-1", false, typeof(OverflowException) };
yield return new object[] { typeof(UInt64Enum), "18446744073709551616", false, typeof(OverflowException) };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { s_charEnumType, ((char)1).ToString(), false, typeof(ArgumentException) };
yield return new object[] { s_charEnumType, ((char)5).ToString(), false, typeof(ArgumentException) };
// Bool
yield return new object[] { s_boolEnumType, bool.TrueString, false, typeof(ArgumentException) };
yield return new object[] { s_boolEnumType, bool.FalseString, false, typeof(ArgumentException) };
// Single
yield return new object[] { s_floatEnumType, "1", false, typeof(ArgumentException) };
yield return new object[] { s_floatEnumType, "5", false, typeof(ArgumentException) };
yield return new object[] { s_floatEnumType, "1.0", false, typeof(ArgumentException) };
// Double
yield return new object[] { s_doubleEnumType, "1", false, typeof(ArgumentException) };
yield return new object[] { s_doubleEnumType, "5", false, typeof(ArgumentException) };
yield return new object[] { s_doubleEnumType, "1.0", false, typeof(ArgumentException) };
// IntPtr
yield return new object[] { s_intPtrEnumType, "1", false, typeof(InvalidCastException) };
yield return new object[] { s_intPtrEnumType, "5", false, typeof(InvalidCastException) };
// UIntPtr
yield return new object[] { s_uintPtrEnumType, "1", false, typeof(InvalidCastException) };
yield return new object[] { s_uintPtrEnumType, "5", false, typeof(InvalidCastException) };
}
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(Type enumType, string value, bool ignoreCase, Type exceptionType)
{
Type typeArgument = enumType == null || !enumType.GetTypeInfo().IsEnum ? typeof(SimpleEnum) : enumType;
MethodInfo parseMethod = typeof(EnumTests).GetTypeInfo().GetMethod(nameof(Parse_Generic_Invalid), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeArgument);
parseMethod.Invoke(null, new object[] { enumType, value, ignoreCase, exceptionType });
}
private static void Parse_Generic_Invalid<T>(Type enumType, string value, bool ignoreCase, Type exceptionType) where T : struct
{
object result = null;
if (!ignoreCase)
{
if (enumType != null && enumType.IsEnum)
{
Assert.False(Enum.TryParse(enumType, value, out result));
Assert.Equal(default(object), result);
if (value != null)
Assert.Throws(exceptionType, () => Enum.Parse<T>(value.AsSpan()));
Assert.Throws(exceptionType, () => Enum.Parse<T>(value));
}
else
{
if (value != null)
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value.AsSpan(), out result));
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, out result));
Assert.Equal(default(object), result);
}
}
if (enumType != null && enumType.IsEnum)
{
Assert.False(Enum.TryParse(enumType, value, ignoreCase, out result));
Assert.Equal(default(object), result);
if (value != null)
Assert.Throws(exceptionType, () => Enum.Parse<T>(value.AsSpan(), ignoreCase));
Assert.Throws(exceptionType, () => Enum.Parse<T>(value, ignoreCase));
}
else
{
if (value != null)
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value.AsSpan(), ignoreCase, out result));
Assert.Throws(exceptionType, () => Enum.TryParse(enumType, value, ignoreCase, out result));
Assert.Equal(default(object), result);
}
}
[Theory]
[InlineData(SByteEnum.Min, "Min")]
[InlineData(SByteEnum.One, "One")]
[InlineData(SByteEnum.Two, "Two")]
[InlineData(SByteEnum.Max, "Max")]
[InlineData(sbyte.MinValue, "Min")]
[InlineData((sbyte)1, "One")]
[InlineData((sbyte)2, "Two")]
[InlineData(sbyte.MaxValue, "Max")]
[InlineData((sbyte)3, null)]
public void GetName_InvokeSByteEnum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(SByteEnum), value, expected);
if (!(value is SByteEnum enumValue))
{
enumValue = (SByteEnum)(sbyte)value;
}
Assert.Equal(expected, Enum.GetName<SByteEnum>(enumValue));
}
[Theory]
[InlineData(ByteEnum.Min, "Min")]
[InlineData(ByteEnum.One, "One")]
[InlineData(ByteEnum.Two, "Two")]
[InlineData(ByteEnum.Max, "Max")]
[InlineData(byte.MinValue, "Min")]
[InlineData((byte)1, "One")]
[InlineData((byte)2, "Two")]
[InlineData(byte.MaxValue, "Max")]
[InlineData((byte)3, null)]
public void GetName_InvokeByteEnum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(ByteEnum), value, expected);
if (!(value is ByteEnum enumValue))
{
enumValue = (ByteEnum)(byte)value;
}
Assert.Equal(expected, Enum.GetName<ByteEnum>(enumValue));
}
[Theory]
[InlineData(Int16Enum.Min, "Min")]
[InlineData(Int16Enum.One, "One")]
[InlineData(Int16Enum.Two, "Two")]
[InlineData(Int16Enum.Max, "Max")]
[InlineData(short.MinValue, "Min")]
[InlineData((short)1, "One")]
[InlineData((short)2, "Two")]
[InlineData(short.MaxValue, "Max")]
[InlineData((short)3, null)]
public void GetName_InvokeInt16Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(Int16Enum), value, expected);
if (!(value is Int16Enum enumValue))
{
enumValue = (Int16Enum)(short)value;
}
Assert.Equal(expected, Enum.GetName<Int16Enum>(enumValue));
}
[Theory]
[InlineData(UInt16Enum.Min, "Min")]
[InlineData(UInt16Enum.One, "One")]
[InlineData(UInt16Enum.Two, "Two")]
[InlineData(UInt16Enum.Max, "Max")]
[InlineData(ushort.MinValue, "Min")]
[InlineData((ushort)1, "One")]
[InlineData((ushort)2, "Two")]
[InlineData(ushort.MaxValue, "Max")]
[InlineData((ushort)3, null)]
public void GetName_InvokeUInt16Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(UInt16Enum), value, expected);
if (!(value is UInt16Enum enumValue))
{
enumValue = (UInt16Enum)(ushort)value;
}
Assert.Equal(expected, Enum.GetName<UInt16Enum>(enumValue));
}
[Theory]
[InlineData(Int32Enum.Min, "Min")]
[InlineData(Int32Enum.One, "One")]
[InlineData(Int32Enum.Two, "Two")]
[InlineData(Int32Enum.Max, "Max")]
[InlineData(int.MinValue, "Min")]
[InlineData(1, "One")]
[InlineData(2, "Two")]
[InlineData(int.MaxValue, "Max")]
[InlineData(3, null)]
public void GetName_InvokeInt32Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(Int32Enum), value, expected);
if (!(value is Int32Enum enumValue))
{
enumValue = (Int32Enum)(int)value;
}
Assert.Equal(expected, Enum.GetName<Int32Enum>(enumValue));
}
[Theory]
[InlineData(UInt32Enum.Min, "Min")]
[InlineData(UInt32Enum.One, "One")]
[InlineData(UInt32Enum.Two, "Two")]
[InlineData(UInt32Enum.Max, "Max")]
[InlineData(uint.MinValue, "Min")]
[InlineData((uint)1, "One")]
[InlineData((uint)2, "Two")]
[InlineData(uint.MaxValue, "Max")]
[InlineData((uint)3, null)]
public void GetName_InvokeUInt32Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(UInt32Enum), value, expected);
if (!(value is UInt32Enum enumValue))
{
enumValue = (UInt32Enum)(uint)value;
}
Assert.Equal(expected, Enum.GetName<UInt32Enum>(enumValue));
}
[Theory]
[InlineData(Int64Enum.Min, "Min")]
[InlineData(Int64Enum.One, "One")]
[InlineData(Int64Enum.Two, "Two")]
[InlineData(Int64Enum.Max, "Max")]
[InlineData(long.MinValue, "Min")]
[InlineData((long)1, "One")]
[InlineData((long)2, "Two")]
[InlineData(long.MaxValue, "Max")]
[InlineData((long)3, null)]
public void GetName_InvokeInt64Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(Int64Enum), value, expected);
if (!(value is Int64Enum enumValue))
{
enumValue = (Int64Enum)(long)value;
}
Assert.Equal(expected, Enum.GetName<Int64Enum>(enumValue));
}
[Theory]
[InlineData(UInt64Enum.Min, "Min")]
[InlineData(UInt64Enum.One, "One")]
[InlineData(UInt64Enum.Two, "Two")]
[InlineData(UInt64Enum.Max, "Max")]
[InlineData(ulong.MinValue, "Min")]
[InlineData(1UL, "One")]
[InlineData(2UL, "Two")]
[InlineData(ulong.MaxValue, "Max")]
[InlineData(3UL, null)]
public void GetName_InvokeUInt64Enum_ReturnsExpected(object value, string expected)
{
TestGetName(typeof(UInt64Enum), value, expected);
if (!(value is UInt64Enum enumValue))
{
enumValue = (UInt64Enum)(ulong)value;
}
Assert.Equal(expected, Enum.GetName<UInt64Enum>(enumValue));
}
public static IEnumerable<object[]> GetName_CharEnum_TestData()
{
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), "Value1" };
yield return new object[] { Enum.Parse(s_charEnumType, "Value2"), "Value2" };
yield return new object[] { (char)1, "Value1" };
yield return new object[] { (char)2, "Value2" };
yield return new object[] { (char)4, null };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
[MemberData(nameof(GetName_CharEnum_TestData))]
public void GetName_InvokeCharEnum_ReturnsExpected(object value, string expected)
{
TestGetName(s_charEnumType, value, expected);
}
public static IEnumerable<object[]> GetName_BoolEnum_TestData()
{
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), "Value1" };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value2"), "Value2" };
yield return new object[] { true, "Value1" };
yield return new object[] { false, "Value2" };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
[MemberData(nameof(GetName_BoolEnum_TestData))]
public void GetName_InvokeBoolEnum_ReturnsExpected(object value, string expected)
{
TestGetName(s_boolEnumType, value, expected);
}
private void TestGetName(Type enumType, object value, string expected)
{
Assert.Equal(expected, Enum.GetName(enumType, value));
// The format "G" should return the name of the enum case
if (value.GetType() == enumType)
{
ToString_Format((Enum)value, "G", expected);
}
else
{
Format(enumType, value, "G", expected ?? value.ToString());
}
}
[Fact]
public static void GetName_MultipleMatches()
{
// In the case of multiple matches, GetName returns one of them (which one is an implementation detail.)
string s = Enum.GetName(typeof(SimpleEnum), 3);
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
}
[Fact]
public void GetName_NullEnumType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.GetName(null, 1));
}
[Theory]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
[InlineData(typeof(ValueType))]
[InlineData(typeof(Enum))]
public void GetName_EnumTypeNotEnum_ThrowsArgumentException(Type enumType)
{
AssertExtensions.Throws<ArgumentException>(null, () => Enum.GetName(enumType, 1));
}
[Fact]
public void GetName_NullValue_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Enum.GetName(typeof(SimpleEnum), null));
}
public static IEnumerable<object[]> GetName_InvalidValue_TestData()
{
yield return new object[] { "Red" };
yield return new object[] { IntPtr.Zero };
}
[Theory]
[MemberData(nameof(GetName_InvalidValue_TestData))]
public void GetName_InvalidValue_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>("value", () => Enum.GetName(typeof(SimpleEnum), value));
}
[Theory]
[InlineData(typeof(SByteEnum), 0xffffffffffffff80LU, "Min")]
[InlineData(typeof(SByteEnum), 0xffffff80u, null)]
[InlineData(typeof(SByteEnum), unchecked((int)(0xffffff80u)), "Min")]
[InlineData(typeof(SByteEnum), true, "One")]
[InlineData(typeof(SByteEnum), (char)1, "One")]
[InlineData(typeof(SByteEnum), SimpleEnum.Red, "One")] // API doesn't care if you pass in a completely different enum
public static void GetName_NonIntegralTypes_ReturnsExpected(Type enumType, object value, string expected)
{
// Despite what MSDN says, GetName() does not require passing in the exact integral type.
// For the purposes of comparison:
// - The enum member value are normalized as follows:
// - unsigned ints zero-extended to 64-bits
// - signed ints sign-extended to 64-bits
// - The value passed in as an argument to GetNames() is normalized as follows:
// - unsigned ints zero-extended to 64-bits
// - signed ints sign-extended to 64-bits
// Then comparison is done on all 64 bits.
Assert.Equal(expected, Enum.GetName(enumType, value));
}
[Theory]
[InlineData(SimpleEnum.Blue, TypeCode.Int32)]
[InlineData(ByteEnum.Max, TypeCode.Byte)]
[InlineData(SByteEnum.Min, TypeCode.SByte)]
[InlineData(UInt16Enum.Max, TypeCode.UInt16)]
[InlineData(Int16Enum.Min, TypeCode.Int16)]
[InlineData(UInt32Enum.Max, TypeCode.UInt32)]
[InlineData(Int32Enum.Min, TypeCode.Int32)]
[InlineData(UInt64Enum.Max, TypeCode.UInt64)]
[InlineData(Int64Enum.Min, TypeCode.Int64)]
public static void GetTypeCode_Enum_ReturnsExpected(Enum e, TypeCode expected)
{
Assert.Equal(expected, e.GetTypeCode());
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(SByteEnum.One, true)]
[InlineData((SByteEnum)99, false)]
[InlineData((sbyte)1, true)]
[InlineData((sbyte)99, false)]
public static void IsDefined_InvokeSByteEnum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(SByteEnum), value));
if (value is SByteEnum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<SByteEnum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(ByteEnum.One, true)]
[InlineData((ByteEnum)99, false)]
[InlineData((byte)1, true)]
[InlineData((byte)99, false)]
public static void IsDefined_InvokeByteEnum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(ByteEnum), value));
if (value is ByteEnum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<ByteEnum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(Int16Enum.One, true)]
[InlineData((Int16Enum)99, false)]
[InlineData((short)1, true)]
[InlineData((short)99, false)]
public static void IsDefined_InvokeInt16Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(Int16Enum), value));
if (value is Int16Enum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<Int16Enum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(UInt16Enum.One, true)]
[InlineData((UInt16Enum)99, false)]
[InlineData((ushort)1, true)]
[InlineData((ushort)99, false)]
public static void IsDefined_InvokeUInt16Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(UInt16Enum), value));
if (value is UInt16Enum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<UInt16Enum>(enumValue));
}
}
[Theory]
[InlineData("Red", true)]
[InlineData("Green", true)]
[InlineData("Blue", true)]
[InlineData(" Blue ", false)]
[InlineData(" blue ", false)]
[InlineData(SimpleEnum.Red, true)]
[InlineData((SimpleEnum)99, false)]
[InlineData(1, true)]
[InlineData(99, false)]
public static void IsDefined_InvokeInt32Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(SimpleEnum), value));
if (value is SimpleEnum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<SimpleEnum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(UInt32Enum.One, true)]
[InlineData((UInt32Enum)99, false)]
[InlineData((uint)1, true)]
[InlineData((uint)99, false)]
public static void IsDefined_InvokeUInt32Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(UInt32Enum), value));
if (value is UInt32Enum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<UInt32Enum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(Int64Enum.One, true)]
[InlineData((Int64Enum)99, false)]
[InlineData((long)1, true)]
[InlineData((long)99, false)]
public static void IsDefined_InvokeInt64Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(Int64Enum), value));
if (value is Int64Enum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<Int64Enum>(enumValue));
}
}
[Theory]
[InlineData("One", true)]
[InlineData("None", false)]
[InlineData(UInt64Enum.One, true)]
[InlineData((UInt64Enum)99, false)]
[InlineData((ulong)1, true)]
[InlineData((ulong)99, false)]
public static void IsDefined_InvokeUInt64Enum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(typeof(UInt64Enum), value));
if (value is UInt64Enum enumValue)
{
Assert.Equal(expected, Enum.IsDefined<UInt64Enum>(enumValue));
}
}
public static IEnumerable<object[]> IsDefined_CharEnum_TestData()
{
yield return new object[] { "Value1", true };
yield return new object[] { "None", false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), true };
yield return new object[] { (char)1, true };
yield return new object[] { (char)99, false };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
[MemberData(nameof(IsDefined_CharEnum_TestData))]
public void IsDefined_InvokeCharEnum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(s_charEnumType, value));
}
public static IEnumerable<object[]> IsDefined_BoolEnum_TestData()
{
yield return new object[] { "Value1", true };
yield return new object[] { "None", false };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), true };
yield return new object[] { "Value1", true };
yield return new object[] { true, true };
yield return new object[] { false, true };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
[MemberData(nameof(IsDefined_BoolEnum_TestData))]
public void IsDefined_InvokeBoolEnum_ReturnsExpected(object value, bool expected)
{
Assert.Equal(expected, Enum.IsDefined(s_boolEnumType, value));
}
[Fact]
public void IsDefined_NullEnumType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.IsDefined(null, 1));
}
[Fact]
public void IsDefined_NullValue_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Enum.IsDefined(typeof(SimpleEnum), null));
}
[Theory]
[InlineData(Int32Enum.One)]
[InlineData(true)]
[InlineData('a')]
public void IsDefined_InvalidValue_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => Enum.IsDefined(typeof(SimpleEnum), value));
}
public static IEnumerable<object[]> IsDefined_NonIntegerValue_TestData()
{
yield return new object[] { IntPtr.Zero };
yield return new object[] { 5.5 };
yield return new object[] { 5.5f };
}
[Theory]
[MemberData(nameof(IsDefined_NonIntegerValue_TestData))]
public void IsDefined_NonIntegerValue_ThrowsThrowsInvalidOperationException(object value)
{
Assert.Throws<InvalidOperationException>(() => Enum.IsDefined(typeof(SimpleEnum), value));
}
public static IEnumerable<object[]> HasFlag_TestData()
{
// SByte
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x30, true };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x06, true };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x10, true };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x00, true };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x36, true };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x05, false };
yield return new object[] { (SByteEnum)0x36, (SByteEnum)0x46, false };
// Byte
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x30, true };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x06, true };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x10, true };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x00, true };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x36, true };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x05, false };
yield return new object[] { (ByteEnum)0x36, (ByteEnum)0x46, false };
// Int16
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x3000, true };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x0f06, true };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x1000, true };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x0000, true };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x3f06, true };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x0010, false };
yield return new object[] { (Int16Enum)0x3f06, (Int16Enum)0x3f16, false };
// UInt16
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x3000, true };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x0f06, true };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x1000, true };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x0000, true };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x3f06, true };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x0010, false };
yield return new object[] { (UInt16Enum)0x3f06, (UInt16Enum)0x3f16, false };
// Int32
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x3000, true };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x0f06, true };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x1000, true };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x0000, true };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x3f06, true };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x0010, false };
yield return new object[] { (Int32Enum)0x3f06, (Int32Enum)0x3f16, false };
// UInt32
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x3000, true };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x0f06, true };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x1000, true };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x0000, true };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x3f06, true };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x0010, false };
yield return new object[] { (UInt32Enum)0x3f06, (UInt32Enum)0x3f16, false };
// Int64
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x3000, true };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x0f06, true };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x1000, true };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x0000, true };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x3f06, true };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x0010, false };
yield return new object[] { (Int64Enum)0x3f06, (Int64Enum)0x3f16, false };
// UInt64
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x3000, true };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x0f06, true };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x1000, true };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x0000, true };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x3f06, true };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x0010, false };
yield return new object[] { (UInt64Enum)0x3f06, (UInt64Enum)0x3f16, false };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x3000"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x0f06"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x1000"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x0000"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x3f06"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x0010"), false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x3f16"), false };
// Bool
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value1"), true };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value2"), true };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value2"), Enum.Parse(s_boolEnumType, "Value2"), true };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value2"), Enum.Parse(s_boolEnumType, "Value1"), false };
// Single
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x0f06), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x1000), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x3f06), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x0010), false };
yield return new object[] { Enum.ToObject(s_floatEnumType, 0x3f06), Enum.ToObject(s_floatEnumType, 0x3f16), false };
// Double
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x0f06), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x1000), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x3f06), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x0010), false };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0x3f06), Enum.ToObject(s_doubleEnumType, 0x3f16), false };
// IntPtr
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x0f06), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x1000), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x3f06), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x0010), false };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 0x3f06), Enum.ToObject(s_intPtrEnumType, 0x3f16), false };
// UIntPtr
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x0f06), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x1000), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x0000), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x3f06), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x0010), false };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 0x3f06), Enum.ToObject(s_uintPtrEnumType, 0x3f16), false };
}
}
[Theory]
[MemberData(nameof(HasFlag_TestData))]
public static void HasFlag(Enum e, Enum flag, bool expected)
{
Assert.Equal(expected, e.HasFlag(flag));
}
[Fact]
public static void HasFlag_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("flag", () => Int32Enum.One.HasFlag(null)); // Flag is null
AssertExtensions.Throws<ArgumentException>(null, () => Int32Enum.One.HasFlag((SimpleEnum)0x3000)); // Enum is not the same type as the instance
}
public static IEnumerable<object[]> ToObject_TestData()
{
// SByte
yield return new object[] { typeof(SByteEnum), (SByteEnum)0x42, (SByteEnum)0x42 };
yield return new object[] { typeof(SByteEnum), sbyte.MinValue, SByteEnum.Min };
yield return new object[] { typeof(SByteEnum), (sbyte)2, SByteEnum.Two };
yield return new object[] { typeof(SByteEnum), (sbyte)22, (SByteEnum)22 };
// Byte
yield return new object[] { typeof(ByteEnum), byte.MaxValue, ByteEnum.Max };
yield return new object[] { typeof(ByteEnum), (byte)1, ByteEnum.One };
yield return new object[] { typeof(ByteEnum), (byte)11, (ByteEnum)11 };
yield return new object[] { typeof(ByteEnum), (ulong)0x0ccccccccccccc2aL, (ByteEnum)0x2a };
// Int16
yield return new object[] { typeof(Int16Enum), short.MinValue, Int16Enum.Min };
yield return new object[] { typeof(Int16Enum), (short)2, Int16Enum.Two };
yield return new object[] { typeof(Int16Enum), (short)44, (Int16Enum)44 };
// UInt16
yield return new object[] { typeof(UInt16Enum), ushort.MaxValue, UInt16Enum.Max };
yield return new object[] { typeof(UInt16Enum), (ushort)1, UInt16Enum.One };
yield return new object[] { typeof(UInt16Enum), (ushort)33, (UInt16Enum)33 };
// Int32
yield return new object[] { typeof(Int32Enum), int.MinValue, Int32Enum.Min };
yield return new object[] { typeof(Int32Enum), 2, Int32Enum.Two };
yield return new object[] { typeof(Int32Enum), 66, (Int32Enum)66 };
yield return new object[] { typeof(Int32Enum), 'a', (Int32Enum)97 };
yield return new object[] { typeof(Int32Enum), 'b', (Int32Enum)98 };
yield return new object[] { typeof(Int32Enum), true, (Int32Enum)1 };
// UInt32
yield return new object[] { typeof(UInt32Enum), uint.MaxValue, UInt32Enum.Max };
yield return new object[] { typeof(UInt32Enum), (uint)1, UInt32Enum.One };
yield return new object[] { typeof(UInt32Enum), (uint)55, (UInt32Enum)55 };
// Int64
yield return new object[] { typeof(Int64Enum), long.MinValue, Int64Enum.Min };
yield return new object[] { typeof(Int64Enum), (long)2, Int64Enum.Two };
yield return new object[] { typeof(Int64Enum), (long)88, (Int64Enum)88 };
// UInt64
yield return new object[] { typeof(UInt64Enum), ulong.MaxValue, UInt64Enum.Max };
yield return new object[] { typeof(UInt64Enum), (ulong)1, UInt64Enum.One };
yield return new object[] { typeof(UInt64Enum), (ulong)77, (UInt64Enum)77 };
yield return new object[] { typeof(UInt64Enum), (ulong)0x0123456789abcdefL, (UInt64Enum)0x0123456789abcdefL };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { s_charEnumType, (char)1, Enum.Parse(s_charEnumType, "Value1") };
yield return new object[] { s_charEnumType, (char)2, Enum.Parse(s_charEnumType, "Value2") };
// Bool
yield return new object[] { s_boolEnumType, true, Enum.Parse(s_boolEnumType, "Value1") };
yield return new object[] { s_boolEnumType, false, Enum.Parse(s_boolEnumType, "Value2") };
}
}
[Theory]
[MemberData(nameof(ToObject_TestData))]
public static void ToObject(Type enumType, object value, Enum expected)
{
Assert.Equal(expected, Enum.ToObject(enumType, value));
}
public static IEnumerable<object[]> ToObject_InvalidEnumType_TestData()
{
yield return new object[] { null, typeof(ArgumentNullException) };
yield return new object[] { typeof(Enum), typeof(ArgumentException) };
yield return new object[] { typeof(object), typeof(ArgumentException) };
if (PlatformDetection.IsReflectionEmitSupported)
yield return new object[] { GetNonRuntimeEnumTypeBuilder(typeof(int)), typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(ToObject_InvalidEnumType_TestData))]
public static void ToObject_InvalidEnumType_ThrowsException(Type enumType, Type exceptionType)
{
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, 5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (sbyte)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (short)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (long)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (uint)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (byte)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (ushort)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, (ulong)5));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, 'a'));
Assert.Throws(exceptionType, () => Enum.ToObject(enumType, true));
}
public static IEnumerable<object[]> ToObject_InvalidValue_TestData()
{
yield return new object[] { typeof(SimpleEnum), null, typeof(ArgumentNullException) };
yield return new object[] { typeof(SimpleEnum), "Hello", typeof(ArgumentException) };
if (PlatformDetection.IsReflectionEmitSupported)
{
yield return new object[] { s_floatEnumType, 1.0f, typeof(ArgumentException) };
yield return new object[] { s_doubleEnumType, 1.0, typeof(ArgumentException) };
yield return new object[] { s_intPtrEnumType, (IntPtr)1, typeof(ArgumentException) };
yield return new object[] { s_uintPtrEnumType, (UIntPtr)1, typeof(ArgumentException) };
}
}
[Theory]
[MemberData(nameof(ToObject_InvalidValue_TestData))]
public static void ToObject_InvalidValue_ThrowsException(Type enumType, object value, Type exceptionType)
{
if (exceptionType == typeof(ArgumentNullException))
AssertExtensions.Throws<ArgumentNullException>("value", () => Enum.ToObject(enumType, value));
else if (exceptionType == typeof(ArgumentException))
AssertExtensions.Throws<ArgumentException>("value", () => Enum.ToObject(enumType, value));
else
throw new Exception($"Unexpected exception type in {nameof(ToObject_InvalidValue_TestData)} : {exceptionType}");
}
public static IEnumerable<object[]> Equals_TestData()
{
// SByte
yield return new object[] { SByteEnum.One, SByteEnum.One, true };
yield return new object[] { SByteEnum.One, SByteEnum.Two, false };
yield return new object[] { SByteEnum.One, ByteEnum.One, false };
yield return new object[] { SByteEnum.One, (sbyte)1, false };
yield return new object[] { SByteEnum.One, new object(), false };
yield return new object[] { SByteEnum.One, null, false };
// Byte
yield return new object[] { ByteEnum.One, ByteEnum.One, true };
yield return new object[] { ByteEnum.One, ByteEnum.Two, false };
yield return new object[] { ByteEnum.One, SByteEnum.One, false };
yield return new object[] { ByteEnum.One, (byte)1, false };
yield return new object[] { ByteEnum.One, new object(), false };
yield return new object[] { ByteEnum.One, null, false };
// Int16
yield return new object[] { Int16Enum.One, Int16Enum.One, true };
yield return new object[] { Int16Enum.One, Int16Enum.Two, false };
yield return new object[] { Int16Enum.One, UInt16Enum.One, false };
yield return new object[] { Int16Enum.One, (short)1, false };
yield return new object[] { Int16Enum.One, new object(), false };
yield return new object[] { Int16Enum.One, null, false };
// UInt16
yield return new object[] { UInt16Enum.One, UInt16Enum.One, true };
yield return new object[] { UInt16Enum.One, UInt16Enum.Two, false };
yield return new object[] { UInt16Enum.One, Int16Enum.One, false };
yield return new object[] { UInt16Enum.One, (ushort)1, false };
yield return new object[] { UInt16Enum.One, new object(), false };
yield return new object[] { UInt16Enum.One, null, false };
// Int32
yield return new object[] { Int32Enum.One, Int32Enum.One, true };
yield return new object[] { Int32Enum.One, Int32Enum.Two, false };
yield return new object[] { Int32Enum.One, UInt32Enum.One, false };
yield return new object[] { Int32Enum.One, (short)1, false };
yield return new object[] { Int32Enum.One, new object(), false };
yield return new object[] { Int32Enum.One, null, false };
// UInt32
yield return new object[] { UInt32Enum.One, UInt32Enum.One, true };
yield return new object[] { UInt32Enum.One, UInt32Enum.Two, false };
yield return new object[] { UInt32Enum.One, Int32Enum.One, false };
yield return new object[] { UInt32Enum.One, (ushort)1, false };
yield return new object[] { UInt32Enum.One, new object(), false };
yield return new object[] { UInt32Enum.One, null, false };
// Int64
yield return new object[] { Int64Enum.One, Int64Enum.One, true };
yield return new object[] { Int64Enum.One, Int64Enum.Two, false };
yield return new object[] { Int64Enum.One, UInt64Enum.One, false };
yield return new object[] { Int64Enum.One, (long)1, false };
yield return new object[] { Int64Enum.One, new object(), false };
yield return new object[] { Int64Enum.One, null, false };
// UInt64
yield return new object[] { UInt64Enum.One, UInt64Enum.One, true };
yield return new object[] { UInt64Enum.One, UInt64Enum.Two, false };
yield return new object[] { UInt64Enum.One, Int64Enum.One, false };
yield return new object[] { UInt64Enum.One, (ulong)1, false };
yield return new object[] { UInt64Enum.One, new object(), false };
yield return new object[] { UInt64Enum.One, null, false };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), Enum.Parse(s_charEnumType, "Value1"), true };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), Enum.Parse(s_charEnumType, "Value2"), false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), UInt16Enum.One, false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), (char)1, false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), new object(), false };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), null, false };
// Bool
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value1"), true };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value2"), false };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), UInt16Enum.One, false };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), true, false };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), new object(), false };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), null, false };
// Single
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), Enum.ToObject(s_floatEnumType, 1), true };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), Enum.ToObject(s_floatEnumType, 2), false };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), Enum.ToObject(s_doubleEnumType, 1), false };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), 1.0f, false };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), new object(), false };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), null, false };
// Double
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), Enum.ToObject(s_doubleEnumType, 1), true };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), Enum.ToObject(s_doubleEnumType, 2), false };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), Enum.ToObject(s_floatEnumType, 1), false };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), 1.0, false };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), new object(), false };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), null, false };
// IntPtr
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), Enum.ToObject(s_intPtrEnumType, 1), true };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), Enum.ToObject(s_intPtrEnumType, 2), false };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), Enum.ToObject(s_uintPtrEnumType, 1), false };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), (IntPtr)1, false };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), new object(), false };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), null, false };
// UIntPtr
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), Enum.ToObject(s_uintPtrEnumType, 1), true };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), Enum.ToObject(s_uintPtrEnumType, 2), false };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), Enum.ToObject(s_intPtrEnumType, 1), false };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), (UIntPtr)1, false };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), new object(), false };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), null, false };
}
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public static void EqualsTest(Enum e, object obj, bool expected)
{
Assert.Equal(expected, e.Equals(obj));
Assert.Equal(e.GetHashCode(), e.GetHashCode());
}
public static IEnumerable<object[]> CompareTo_TestData()
{
// SByte
yield return new object[] { SByteEnum.One, SByteEnum.One, 0 };
yield return new object[] { SByteEnum.One, SByteEnum.Min, 1 };
yield return new object[] { SByteEnum.One, SByteEnum.Max, -1 };
yield return new object[] { SByteEnum.One, null, 1 };
// Byte
yield return new object[] { ByteEnum.One, ByteEnum.One, 0 };
yield return new object[] { ByteEnum.One, ByteEnum.Min, 1 };
yield return new object[] { ByteEnum.One, ByteEnum.Max, -1 };
yield return new object[] { ByteEnum.One, null, 1 };
// Int16
yield return new object[] { Int16Enum.One, Int16Enum.One, 0 };
yield return new object[] { Int16Enum.One, Int16Enum.Min, 1 };
yield return new object[] { Int16Enum.One, Int16Enum.Max, -1 };
yield return new object[] { Int16Enum.One, null, 1 };
// UInt16
yield return new object[] { UInt16Enum.One, UInt16Enum.One, 0 };
yield return new object[] { UInt16Enum.One, UInt16Enum.Min, 1 };
yield return new object[] { UInt16Enum.One, UInt16Enum.Max, -1 };
yield return new object[] { UInt16Enum.One, null, 1 };
// Int32
yield return new object[] { SimpleEnum.Red, SimpleEnum.Red, 0 };
yield return new object[] { SimpleEnum.Red, (SimpleEnum)0, 1 };
yield return new object[] { SimpleEnum.Red, (SimpleEnum)2, -1 };
yield return new object[] { SimpleEnum.Green, SimpleEnum.Green_a, 0 };
yield return new object[] { SimpleEnum.Green, null, 1 };
// UInt32
yield return new object[] { UInt32Enum.One, UInt32Enum.One, 0 };
yield return new object[] { UInt32Enum.One, UInt32Enum.Min, 1 };
yield return new object[] { UInt32Enum.One, UInt32Enum.Max, -1 };
yield return new object[] { UInt32Enum.One, null, 1 };
// Int64
yield return new object[] { Int64Enum.One, Int64Enum.One, 0 };
yield return new object[] { Int64Enum.One, Int64Enum.Min, 1 };
yield return new object[] { Int64Enum.One, Int64Enum.Max, -1 };
yield return new object[] { Int64Enum.One, null, 1 };
// UInt64
yield return new object[] { UInt64Enum.One, UInt64Enum.One, 0 };
yield return new object[] { UInt64Enum.One, UInt64Enum.Min, 1 };
yield return new object[] { UInt64Enum.One, UInt64Enum.Max, -1 };
yield return new object[] { UInt64Enum.One, null, 1 };
if (PlatformDetection.IsReflectionEmitSupported)
{
// Char
yield return new object[] { Enum.Parse(s_charEnumType, "Value2"), Enum.Parse(s_charEnumType, "Value2"), 0 };
yield return new object[] { Enum.Parse(s_charEnumType, "Value2"), Enum.Parse(s_charEnumType, "Value1"), 1 };
yield return new object[] { Enum.Parse(s_charEnumType, "Value1"), Enum.Parse(s_charEnumType, "Value2"), -1 };
yield return new object[] { Enum.Parse(s_charEnumType, "Value2"), null, 1 };
// Bool
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value1"), 0 };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), Enum.Parse(s_boolEnumType, "Value2"), 1 };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value2"), Enum.Parse(s_boolEnumType, "Value1"), -1 };
yield return new object[] { Enum.Parse(s_boolEnumType, "Value1"), null, 1 };
// Single
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), Enum.ToObject(s_floatEnumType, 1), 0 };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), Enum.ToObject(s_floatEnumType, 2), -1 };
yield return new object[] { Enum.ToObject(s_floatEnumType, 3), Enum.ToObject(s_floatEnumType, 2), 1 };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), null, 1 };
// Double
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), Enum.ToObject(s_doubleEnumType, 1), 0 };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), Enum.ToObject(s_doubleEnumType, 2), -1 };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 3), Enum.ToObject(s_doubleEnumType, 2), 1 };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), null, 1 };
// IntPtr
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), Enum.ToObject(s_intPtrEnumType, 1), 0 };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), Enum.ToObject(s_intPtrEnumType, 2), -1 };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 3), Enum.ToObject(s_intPtrEnumType, 2), 1 };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1), null, 1 };
// UIntPtr
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), Enum.ToObject(s_uintPtrEnumType, 1), 0 };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), Enum.ToObject(s_uintPtrEnumType, 2), -1 };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 3), Enum.ToObject(s_uintPtrEnumType, 2), 1 };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 1), null, 1 };
}
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public static void CompareTo(Enum e, object target, int expected)
{
Assert.Equal(expected, Math.Sign(e.CompareTo(target)));
}
[Fact]
public static void CompareTo_ObjectNotEnum_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => SimpleEnum.Red.CompareTo((sbyte)1)); // Target is not an enum type
AssertExtensions.Throws<ArgumentException>(null, () => SimpleEnum.Red.CompareTo(Int32Enum.One)); // Target is a different enum type
}
public static IEnumerable<object[]> GetUnderlyingType_TestData()
{
yield return new object[] { typeof(SByteEnum), typeof(sbyte) };
yield return new object[] { typeof(ByteEnum), typeof(byte) };
yield return new object[] { typeof(Int16Enum), typeof(short) };
yield return new object[] { typeof(UInt16Enum), typeof(ushort) };
yield return new object[] { typeof(Int32Enum), typeof(int) };
yield return new object[] { typeof(UInt32Enum), typeof(uint) };
yield return new object[] { typeof(Int64Enum), typeof(long) };
yield return new object[] { typeof(UInt64Enum), typeof(ulong) };
if (PlatformDetection.IsReflectionEmitSupported)
{
yield return new object[] { s_charEnumType, typeof(char) };
yield return new object[] { s_boolEnumType, typeof(bool) };
yield return new object[] { s_floatEnumType, typeof(float) };
yield return new object[] { s_doubleEnumType, typeof(double) };
yield return new object[] { s_intPtrEnumType, typeof(IntPtr) };
yield return new object[] { s_uintPtrEnumType, typeof(UIntPtr) };
}
}
[Theory]
[MemberData(nameof(GetUnderlyingType_TestData))]
public static void GetUnderlyingType(Type enumType, Type expected)
{
Assert.Equal(expected, Enum.GetUnderlyingType(enumType));
}
[Fact]
public static void GetUnderlyingType_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.GetUnderlyingType(null)); // Enum type is null
AssertExtensions.Throws<ArgumentException>("enumType", () => Enum.GetUnderlyingType(typeof(Enum))); // Enum type is simply an enum
}
[Fact]
public void GetNames_InvokeSimpleEnum_ReturnsExpected()
{
var expected = new string[] { "Red", "Blue", "Green", "Green_a", "Green_b", "B" };
Assert.Equal(expected, Enum.GetNames(typeof(SimpleEnum)));
Assert.NotSame(Enum.GetNames(typeof(SimpleEnum)), Enum.GetNames(typeof(SimpleEnum)));
Assert.Equal(expected, Enum.GetNames<SimpleEnum>());
}
[Fact]
public void GetNames_InvokeSByteEnum_ReturnsExpected()
{
var expected = new string[] { "One", "Two", "Max", "Min" };
Assert.Equal(expected, Enum.GetNames(typeof(SByteEnum)));
Assert.NotSame(Enum.GetNames(typeof(SByteEnum)), Enum.GetNames(typeof(SByteEnum)));
Assert.Equal(expected, Enum.GetNames<SByteEnum>());
}
[Fact]
public void GetNames_InvokeByteEnum_ReturnsExpected()
{
var expected = new string[] { "Min", "One", "Two", "Max" };
Assert.Equal(expected, Enum.GetNames(typeof(ByteEnum)));
Assert.NotSame(Enum.GetNames(typeof(ByteEnum)), Enum.GetNames(typeof(ByteEnum)));
Assert.Equal(expected, Enum.GetNames<ByteEnum>());
}
[Fact]
public void GetNames_InvokeInt16Enum_ReturnsExpected()
{
var expected = new string[] { "One", "Two", "Max", "Min" };
Assert.Equal(expected, Enum.GetNames(typeof(Int16Enum)));
Assert.NotSame(Enum.GetNames(typeof(Int16Enum)), Enum.GetNames(typeof(Int16Enum)));
Assert.Equal(expected, Enum.GetNames<Int16Enum>());
}
[Fact]
public void GetNames_InvokeUInt16Enum_ReturnsExpected()
{
var expected = new string[] { "Min", "One", "Two", "Max" };
Assert.Equal(expected, Enum.GetNames(typeof(UInt16Enum)));
Assert.NotSame(Enum.GetNames(typeof(UInt16Enum)), Enum.GetNames(typeof(UInt16Enum)));
Assert.Equal(expected, Enum.GetNames<UInt16Enum>());
}
[Fact]
public void GetNames_InvokeInt32Enum_ReturnsExpected()
{
var expected = new string[] { "One", "Two", "Max", "Min" };
Assert.Equal(expected, Enum.GetNames(typeof(Int32Enum)));
Assert.NotSame(Enum.GetNames(typeof(Int32Enum)), Enum.GetNames(typeof(Int32Enum)));
Assert.Equal(expected, Enum.GetNames<Int32Enum>());
}
[Fact]
public void GetNames_InvokeUInt32Enum_ReturnsExpected()
{
var expected = new string[] { "Min", "One", "Two", "Max" };
Assert.Equal(expected, Enum.GetNames(typeof(UInt32Enum)));
Assert.NotSame(Enum.GetNames(typeof(UInt32Enum)), Enum.GetNames(typeof(UInt32Enum)));
Assert.Equal(expected, Enum.GetNames<UInt32Enum>());
}
[Fact]
public void GetNames_InvokeInt64Enum_ReturnsExpected()
{
var expected = new string[] { "One", "Two", "Max", "Min" };
Assert.Equal(expected, Enum.GetNames(typeof(Int64Enum)));
Assert.NotSame(Enum.GetNames(typeof(Int64Enum)), Enum.GetNames(typeof(Int64Enum)));
Assert.Equal(expected, Enum.GetNames<Int64Enum>());
}
[Fact]
public void GetNames_InvokeUInt64Enum_ReturnsExpected()
{
var expected = new string[] { "Min", "One", "Two", "Max" };
Assert.Equal(expected, Enum.GetNames(typeof(UInt64Enum)));
Assert.NotSame(Enum.GetNames(typeof(UInt64Enum)), Enum.GetNames(typeof(UInt64Enum)));
Assert.Equal(expected, Enum.GetNames<UInt64Enum>());
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeCharEnum_ReturnsExpected()
{
var expected = new string[] { "Value0x0000", "Value1", "Value2", "Value0x0010", "Value0x0f06", "Value0x1000", "Value0x3000", "Value0x3f06", "Value0x3f16" };
Assert.Equal(expected, Enum.GetNames(s_charEnumType));
Assert.NotSame(Enum.GetNames(s_charEnumType), Enum.GetNames(s_charEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeBoolEnum_ReturnsExpected()
{
var expected = new string[] { "Value2", "Value1" };
Assert.Equal(expected, Enum.GetNames(s_boolEnumType));
Assert.NotSame(Enum.GetNames(s_boolEnumType), Enum.GetNames(s_boolEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeSingleEnum_ReturnsExpected()
{
var expected = new string[] { "Value1", "Value2", "Value0x3f06", "Value0x3000", "Value0x0f06", "Value0x1000", "Value0x0000", "Value0x0010", "Value0x3f16" };
Assert.Equal(expected, Enum.GetNames(s_floatEnumType));
Assert.NotSame(Enum.GetNames(s_floatEnumType), Enum.GetNames(s_floatEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeDoubleEnum_ReturnsExpected()
{
var expected = new string[] { "Value1", "Value2", "Value0x3f06", "Value0x3000", "Value0x0f06", "Value0x1000", "Value0x0000", "Value0x0010", "Value0x3f16" };
Assert.Equal(expected, Enum.GetNames(s_doubleEnumType));
Assert.NotSame(Enum.GetNames(s_doubleEnumType), Enum.GetNames(s_doubleEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeIntPtrEnum_ReturnsExpected()
{
var expected = new string[0];
Assert.Equal(expected, Enum.GetNames(s_intPtrEnumType));
Assert.Same(Enum.GetNames(s_intPtrEnumType), Enum.GetNames(s_intPtrEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetNames_InvokeUIntPtrEnum_ReturnsExpected()
{
var expected = new string[0];
Assert.Equal(expected, Enum.GetNames(s_uintPtrEnumType));
Assert.Same(Enum.GetNames(s_uintPtrEnumType), Enum.GetNames(s_uintPtrEnumType));
}
[Fact]
public static void GetNames_NullEnumType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.GetNames(null));
}
[Theory]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
[InlineData(typeof(ValueType))]
[InlineData(typeof(Enum))]
public void GetNames_EnumTypeNotEnum_ThrowsArgumentException(Type enumType)
{
AssertExtensions.Throws<ArgumentException>("enumType", () => Enum.GetNames(enumType));
}
[Fact]
public void GetValues_InvokeSimpleEnumEnum_ReturnsExpected()
{
var expected = new SimpleEnum[] { SimpleEnum.Red, SimpleEnum.Blue, SimpleEnum.Green, SimpleEnum.Green_a, SimpleEnum.Green_b, SimpleEnum.B };
Assert.Equal(expected, Enum.GetValues(typeof(SimpleEnum)));
Assert.NotSame(Enum.GetValues(typeof(SimpleEnum)), Enum.GetValues(typeof(SimpleEnum)));
Assert.Equal(expected, Enum.GetValues<SimpleEnum>());
}
[Fact]
public void GetValues_InvokeSByteEnum_ReturnsExpected()
{
var expected = new SByteEnum[] { SByteEnum.One, SByteEnum.Two, SByteEnum.Max, SByteEnum.Min };
Assert.Equal(expected, Enum.GetValues(typeof(SByteEnum)));
Assert.NotSame(Enum.GetValues(typeof(SByteEnum)), Enum.GetValues(typeof(SByteEnum)));
Assert.Equal(expected, Enum.GetValues<SByteEnum>());
}
[Fact]
public void GetValues_InvokeByteEnum_ReturnsExpected()
{
var expected = new ByteEnum[] { ByteEnum.Min, ByteEnum.One, ByteEnum.Two, ByteEnum.Max };
Assert.Equal(expected, Enum.GetValues(typeof(ByteEnum)));
Assert.NotSame(Enum.GetValues(typeof(ByteEnum)), Enum.GetValues(typeof(ByteEnum)));
Assert.Equal(expected, Enum.GetValues<ByteEnum>());
}
[Fact]
public void GetValues_InvokeInt16Enum_ReturnsExpected()
{
var expected = new Int16Enum[] { Int16Enum.One, Int16Enum.Two, Int16Enum.Max, Int16Enum.Min };
Assert.Equal(expected, Enum.GetValues(typeof(Int16Enum)));
Assert.NotSame(Enum.GetValues(typeof(Int16Enum)), Enum.GetValues(typeof(Int16Enum)));
Assert.Equal(expected, Enum.GetValues<Int16Enum>());
}
[Fact]
public void GetValues_InvokeUInt16Enum_ReturnsExpected()
{
var expected = new UInt16Enum[] { UInt16Enum.Min, UInt16Enum.One, UInt16Enum.Two, UInt16Enum.Max };
Assert.Equal(expected, Enum.GetValues(typeof(UInt16Enum)));
Assert.NotSame(Enum.GetValues(typeof(UInt16Enum)), Enum.GetValues(typeof(UInt16Enum)));
Assert.Equal(expected, Enum.GetValues<UInt16Enum>());
}
[Fact]
public void GetValues_InvokeInt32Enum_ReturnsExpected()
{
var expected = new Int32Enum[] { Int32Enum.One, Int32Enum.Two, Int32Enum.Max, Int32Enum.Min };
Assert.Equal(expected, Enum.GetValues(typeof(Int32Enum)));
Assert.NotSame(Enum.GetValues(typeof(Int32Enum)), Enum.GetValues(typeof(Int32Enum)));
Assert.Equal(expected, Enum.GetValues<Int32Enum>());
}
[Fact]
public void GetValues_InvokeUInt32Enum_ReturnsExpected()
{
var expected = new UInt32Enum[] { UInt32Enum.Min, UInt32Enum.One, UInt32Enum.Two, UInt32Enum.Max };
Assert.Equal(expected, Enum.GetValues(typeof(UInt32Enum)));
Assert.NotSame(Enum.GetValues(typeof(UInt32Enum)), Enum.GetValues(typeof(UInt32Enum)));
Assert.Equal(expected, Enum.GetValues<UInt32Enum>());
}
[Fact]
public void GetValues_InvokeInt64Enum_ReturnsExpected()
{
var expected = new Int64Enum[] { Int64Enum.One, Int64Enum.Two, Int64Enum.Max, Int64Enum.Min };
Assert.Equal(expected, Enum.GetValues(typeof(Int64Enum)));
Assert.NotSame(Enum.GetValues(typeof(Int64Enum)), Enum.GetValues(typeof(Int64Enum)));
Assert.Equal(expected, Enum.GetValues<Int64Enum>());
}
[Fact]
public void GetValues_InvokeUInt64Enum_ReturnsExpected()
{
var expected = new UInt64Enum[] { UInt64Enum.Min, UInt64Enum.One, UInt64Enum.Two, UInt64Enum.Max };
Assert.Equal(expected, Enum.GetValues(typeof(UInt64Enum)));
Assert.NotSame(Enum.GetValues(typeof(UInt64Enum)), Enum.GetValues(typeof(UInt64Enum)));
Assert.Equal(expected, Enum.GetValues<UInt64Enum>());
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeCharEnum_ReturnsExpected()
{
var expected = new object[] { Enum.Parse(s_charEnumType, "Value0x0000"), Enum.Parse(s_charEnumType, "Value1"), Enum.Parse(s_charEnumType, "Value2"), Enum.Parse(s_charEnumType, "Value0x0010"), Enum.Parse(s_charEnumType, "Value0x0f06"), Enum.Parse(s_charEnumType, "Value0x1000"), Enum.Parse(s_charEnumType, "Value0x3000"), Enum.Parse(s_charEnumType, "Value0x3f06"), Enum.Parse(s_charEnumType, "Value0x3f16") };
Assert.Equal(expected, Enum.GetValues(s_charEnumType));
Assert.NotSame(Enum.GetValues(s_charEnumType), Enum.GetValues(s_charEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeBoolEnum_ReturnsExpected()
{
var expected = new object[] { Enum.Parse(s_boolEnumType, "Value2"), Enum.Parse(s_boolEnumType, "Value1") };
Assert.Equal(expected, Enum.GetValues(s_boolEnumType));
Assert.NotSame(Enum.GetValues(s_boolEnumType), Enum.GetValues(s_boolEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeSingleEnum_ReturnsExpected()
{
var expected = new object[] { Enum.Parse(s_floatEnumType, "Value1"), Enum.Parse(s_floatEnumType, "Value2"), Enum.Parse(s_floatEnumType, "Value0x3f06"), Enum.Parse(s_floatEnumType, "Value0x3000"), Enum.Parse(s_floatEnumType, "Value0x0f06"), Enum.Parse(s_floatEnumType, "Value0x1000"), Enum.Parse(s_floatEnumType, "Value0x0000"), Enum.Parse(s_floatEnumType, "Value0x0010"), Enum.Parse(s_floatEnumType, "Value0x3f16") };
Assert.Equal(expected, Enum.GetValues(s_floatEnumType));
Assert.NotSame(Enum.GetValues(s_floatEnumType), Enum.GetValues(s_floatEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeDoubleEnum_ReturnsExpected()
{
var expected = new object[] { Enum.Parse(s_doubleEnumType, "Value1"), Enum.Parse(s_doubleEnumType, "Value2"), Enum.Parse(s_doubleEnumType, "Value0x3f06"), Enum.Parse(s_doubleEnumType, "Value0x3000"), Enum.Parse(s_doubleEnumType, "Value0x0f06"), Enum.Parse(s_doubleEnumType, "Value0x1000"), Enum.Parse(s_doubleEnumType, "Value0x0000"), Enum.Parse(s_doubleEnumType, "Value0x0010"), Enum.Parse(s_doubleEnumType, "Value0x3f16") };
Assert.Equal(expected, Enum.GetValues(s_doubleEnumType));
Assert.NotSame(Enum.GetValues(s_doubleEnumType), Enum.GetValues(s_doubleEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeIntPtrEnum_ReturnsExpected()
{
var expected = new object[0];
Assert.Equal(expected, Enum.GetValues(s_intPtrEnumType));
Assert.NotSame(Enum.GetValues(s_intPtrEnumType), Enum.GetValues(s_intPtrEnumType));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public void GetValues_InvokeUIntPtrEnum_ReturnsExpected()
{
var expected = new object[0];
Assert.Equal(expected, Enum.GetValues(s_uintPtrEnumType));
Assert.NotSame(Enum.GetValues(s_uintPtrEnumType), Enum.GetValues(s_uintPtrEnumType));
}
[Fact]
public static void GetValues_NullEnumType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.GetValues(null));
}
[Theory]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
[InlineData(typeof(ValueType))]
[InlineData(typeof(Enum))]
public void GetValues_EnumTypeNotEnum_ThrowsArgumentException(Type enumType)
{
AssertExtensions.Throws<ArgumentException>("enumType", () => Enum.GetValues(enumType));
}
public static IEnumerable<object[]> ToString_Format_TestData()
{
// Format "D": the decimal equivalent of the value is returned.
// Format "X": value in hex form without a leading "0x"
// Format "F": value is treated as a bit field that contains one or more flags that consist of one or more bits.
// If value is equal to a combination of named enumerated constants, a delimiter-separated list of the names
// of those constants is returned. value is searched for flags, going from the flag with the largest value
// to the smallest value. For each flag that corresponds to a bit field in value, the name of the constant
// is concatenated to the delimiter-separated list. The value of that flag is then excluded from further
// consideration, and the search continues for the next flag.
// If value is not equal to a combination of named enumerated constants, the decimal equivalent of value is returned.
// Format "G": if value is equal to a named enumerated constant, the name of that constant is returned.
// Otherwise, if "[Flags]" present, do as Format "F" - else return the decimal value of "value".
// "D": SByte
yield return new object[] { SByteEnum.Min, "D", "-128" };
yield return new object[] { SByteEnum.One, "D", "1" };
yield return new object[] { SByteEnum.Two, "D", "2" };
yield return new object[] { (SByteEnum)99, "D", "99" };
yield return new object[] { SByteEnum.Max, "D", "127" };
// "D": Byte
yield return new object[] { ByteEnum.Min, "D", "0" };
yield return new object[] { ByteEnum.One, "D", "1" };
yield return new object[] { ByteEnum.Two, "D", "2" };
yield return new object[] { (ByteEnum)99, "D", "99" };
yield return new object[] { ByteEnum.Max, "D", "255" };
// "D": Int16
yield return new object[] { Int16Enum.Min, "D", "-32768" };
yield return new object[] { Int16Enum.One, "D", "1" };
yield return new object[] { Int16Enum.Two, "D", "2" };
yield return new object[] { (Int16Enum)99, "D", "99" };
yield return new object[] { Int16Enum.Max, "D", "32767" };
// "D": UInt16
yield return new object[] { UInt16Enum.Min, "D", "0" };
yield return new object[] { UInt16Enum.One, "D", "1" };
yield return new object[] { UInt16Enum.Two, "D", "2" };
yield return new object[] { (UInt16Enum)99, "D", "99" };
yield return new object[] { UInt16Enum.Max, "D", "65535" };
// "D": Int32
yield return new object[] { Int32Enum.Min, "D", "-2147483648" };
yield return new object[] { Int32Enum.One, "D", "1" };
yield return new object[] { Int32Enum.Two, "D", "2" };
yield return new object[] { (Int32Enum)99, "D", "99" };
yield return new object[] { Int32Enum.Max, "D", "2147483647" };
// "D": UInt32
yield return new object[] { UInt32Enum.Min, "D", "0" };
yield return new object[] { UInt32Enum.One, "D", "1" };
yield return new object[] { UInt32Enum.Two, "D", "2" };
yield return new object[] { (UInt32Enum)99, "D", "99" };
yield return new object[] { UInt32Enum.Max, "D", "4294967295" };
// "D": Int64
yield return new object[] { Int64Enum.Min, "D", "-9223372036854775808" };
yield return new object[] { Int64Enum.One, "D", "1" };
yield return new object[] { Int64Enum.Two, "D", "2" };
yield return new object[] { (Int64Enum)99, "D", "99" };
yield return new object[] { Int64Enum.Max, "D", "9223372036854775807" };
// "D": UInt64
yield return new object[] { UInt64Enum.Min, "D", "0" };
yield return new object[] { UInt64Enum.One, "D", "1" };
yield return new object[] { UInt64Enum.Two, "D", "2" };
yield return new object[] { (UInt64Enum)99, "D", "99" };
yield return new object[] { UInt64Enum.Max, "D", "18446744073709551615" };
if (PlatformDetection.IsReflectionEmitSupported)
{
// "D": Char
yield return new object[] { Enum.ToObject(s_charEnumType, (char)0), "D", ((char)0).ToString() };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)1), "D", ((char)1).ToString() };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)2), "D", ((char)2).ToString() };
yield return new object[] { Enum.ToObject(s_charEnumType, char.MaxValue), "D", char.MaxValue.ToString() };
// "D:" Bool
yield return new object[] { Enum.ToObject(s_boolEnumType, true), "D", bool.TrueString };
yield return new object[] { Enum.ToObject(s_boolEnumType, false), "D", bool.FalseString };
yield return new object[] { Enum.ToObject(s_boolEnumType, 123), "D", bool.TrueString };
// "D": Single
yield return new object[] { Enum.ToObject(s_floatEnumType, 0), "D", "0" };
yield return new object[] { Enum.ToObject(s_floatEnumType, 1), "D", float.Epsilon.ToString() };
yield return new object[] { Enum.ToObject(s_floatEnumType, int.MaxValue), "D", float.NaN.ToString() };
// "D": Double
yield return new object[] { Enum.ToObject(s_doubleEnumType, 0), "D", "0" };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 1), "D", double.Epsilon.ToString() };
yield return new object[] { Enum.ToObject(s_doubleEnumType, long.MaxValue), "D", double.NaN.ToString() };
}
// "D": SimpleEnum
yield return new object[] { SimpleEnum.Red, "D", "1" };
// "X": SByte
yield return new object[] { SByteEnum.Min, "X", "80" };
yield return new object[] { SByteEnum.One, "X", "01" };
yield return new object[] { SByteEnum.Two, "X", "02" };
yield return new object[] { (SByteEnum)99, "X", "63" };
yield return new object[] { SByteEnum.Max, "X", "7F" };
// "X": Byte
yield return new object[] { ByteEnum.Min, "X", "00" };
yield return new object[] { ByteEnum.One, "X", "01" };
yield return new object[] { ByteEnum.Two, "X", "02" };
yield return new object[] { (ByteEnum)99, "X", "63" };
yield return new object[] { ByteEnum.Max, "X", "FF" };
// "X": Int16
yield return new object[] { Int16Enum.Min, "X", "8000" };
yield return new object[] { Int16Enum.One, "X", "0001" };
yield return new object[] { Int16Enum.Two, "X", "0002" };
yield return new object[] { (Int16Enum)99, "X", "0063" };
yield return new object[] { Int16Enum.Max, "X", "7FFF" };
// "X": UInt16
yield return new object[] { UInt16Enum.Min, "X", "0000" };
yield return new object[] { UInt16Enum.One, "X", "0001" };
yield return new object[] { UInt16Enum.Two, "X", "0002" };
yield return new object[] { (UInt16Enum)99, "X", "0063" };
yield return new object[] { UInt16Enum.Max, "X", "FFFF" };
// "X": UInt32
yield return new object[] { UInt32Enum.Min, "X", "00000000" };
yield return new object[] { UInt32Enum.One, "X", "00000001" };
yield return new object[] { UInt32Enum.Two, "X", "00000002" };
yield return new object[] { (UInt32Enum)99, "X", "00000063" };
yield return new object[] { UInt32Enum.Max, "X", "FFFFFFFF" };
// "X": Int32
yield return new object[] { Int32Enum.Min, "X", "80000000" };
yield return new object[] { Int32Enum.One, "X", "00000001" };
yield return new object[] { Int32Enum.Two, "X", "00000002" };
yield return new object[] { (Int32Enum)99, "X", "00000063" };
yield return new object[] { Int32Enum.Max, "X", "7FFFFFFF" };
// "X:" Int64
yield return new object[] { Int64Enum.Min, "X", "8000000000000000" };
yield return new object[] { Int64Enum.One, "X", "0000000000000001" };
yield return new object[] { Int64Enum.Two, "X", "0000000000000002" };
yield return new object[] { (Int64Enum)99, "X", "0000000000000063" };
yield return new object[] { Int64Enum.Max, "X", "7FFFFFFFFFFFFFFF" };
// "X": UInt64
yield return new object[] { UInt64Enum.Min, "X", "0000000000000000" };
yield return new object[] { UInt64Enum.One, "X", "0000000000000001" };
yield return new object[] { UInt64Enum.Two, "X", "0000000000000002" };
yield return new object[] { (UInt64Enum)99, "X", "0000000000000063" };
yield return new object[] { UInt64Enum.Max, "X", "FFFFFFFFFFFFFFFF" };
if (PlatformDetection.IsReflectionEmitSupported)
{
// "X": Char
yield return new object[] { Enum.ToObject(s_charEnumType, (char)0), "X", "0000" };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)1), "X", "0001" };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)2), "X", "0002" };
yield return new object[] { Enum.ToObject(s_charEnumType, char.MaxValue), "X", "FFFF" };
// "X": Bool
yield return new object[] { Enum.ToObject(s_boolEnumType, false), "X", "00" };
yield return new object[] { Enum.ToObject(s_boolEnumType, true), "X", "01" };
yield return new object[] { Enum.ToObject(s_boolEnumType, 123), "X", "01" };
}
// "X": SimpleEnum
yield return new object[] { SimpleEnum.Red, "X", "00000001" };
// "F": SByte
yield return new object[] { SByteEnum.Min, "F", "Min" };
yield return new object[] { SByteEnum.One | SByteEnum.Two, "F", "One, Two" };
yield return new object[] { (SByteEnum)5, "F", "5" };
yield return new object[] { SByteEnum.Max, "F", "Max" };
// "F": Byte
yield return new object[] { ByteEnum.Min, "F", "Min" };
yield return new object[] { ByteEnum.One | ByteEnum.Two, "F", "One, Two" };
yield return new object[] { (ByteEnum)5, "F", "5" };
yield return new object[] { ByteEnum.Max, "F", "Max" };
// "F": Int16
yield return new object[] { Int16Enum.Min, "F", "Min" };
yield return new object[] { Int16Enum.One | Int16Enum.Two, "F", "One, Two" };
yield return new object[] { (Int16Enum)5, "F", "5" };
yield return new object[] { Int16Enum.Max, "F", "Max" };
// "F": UInt16
yield return new object[] { UInt16Enum.Min, "F", "Min" };
yield return new object[] { UInt16Enum.One | UInt16Enum.Two, "F", "One, Two" };
yield return new object[] { (UInt16Enum)5, "F", "5" };
yield return new object[] { UInt16Enum.Max, "F", "Max" };
// "F": Int32
yield return new object[] { Int32Enum.Min, "F", "Min" };
yield return new object[] { Int32Enum.One | Int32Enum.Two, "F", "One, Two" };
yield return new object[] { (Int32Enum)5, "F", "5" };
yield return new object[] { Int32Enum.Max, "F", "Max" };
// "F": UInt32
yield return new object[] { UInt32Enum.Min, "F", "Min" };
yield return new object[] { UInt32Enum.One | UInt32Enum.Two, "F", "One, Two" };
yield return new object[] { (UInt32Enum)5, "F", "5" };
yield return new object[] { UInt32Enum.Max, "F", "Max" };
// "F": Int64
yield return new object[] { Int64Enum.Min, "F", "Min" };
yield return new object[] { Int64Enum.One | Int64Enum.Two, "F", "One, Two" };
yield return new object[] { (Int64Enum)5, "F", "5" };
yield return new object[] { Int64Enum.Max, "F", "Max" };
// "F": UInt64
yield return new object[] { UInt64Enum.Min, "F", "Min" };
yield return new object[] { UInt64Enum.One | UInt64Enum.Two, "F", "One, Two" };
yield return new object[] { (UInt64Enum)5, "F", "5" };
yield return new object[] { UInt64Enum.Max, "F", "Max" };
if (PlatformDetection.IsReflectionEmitSupported)
{
// "F": Char
yield return new object[] { Enum.ToObject(s_charEnumType, (char)1), "F", "Value1" };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)(1 | 2)), "F", "Value1, Value2" };
yield return new object[] { Enum.ToObject(s_charEnumType, (char)5), "F", ((char)5).ToString() };
yield return new object[] { Enum.ToObject(s_charEnumType, char.MaxValue), "F", char.MaxValue.ToString() };
// "F": Bool
yield return new object[] { Enum.ToObject(s_boolEnumType, true), "F", "Value1" };
yield return new object[] { Enum.ToObject(s_boolEnumType, false), "F", "Value2" };
// "F": IntPtr
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 5), "F", "5" };
// "F": UIntPtr
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 5), "F", "5" };
}
// "F": SimpleEnum
yield return new object[] { SimpleEnum.Red, "F", "Red" };
yield return new object[] { SimpleEnum.Blue, "F", "Blue" };
yield return new object[] { (SimpleEnum)99, "F", "99" };
yield return new object[] { (SimpleEnum)0, "F", "0" }; // Not found
// "F": Flags Attribute
yield return new object[] { AttributeTargets.Class | AttributeTargets.Delegate, "F", "Class, Delegate" };
if (PlatformDetection.IsReflectionEmitSupported)
{
// "G": Char
yield return new object[] { Enum.ToObject(s_charEnumType, char.MaxValue), "G", char.MaxValue.ToString() };
}
// "G": SByte
yield return new object[] { SByteEnum.Min, "G", "Min" };
yield return new object[] { (SByteEnum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { SByteEnum.Max, "G", "Max" };
// "G": Byte
yield return new object[] { ByteEnum.Min, "G", "Min" };
yield return new object[] { (ByteEnum)0xff, "G", "Max" };
yield return new object[] { (ByteEnum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { ByteEnum.Max, "G", "Max" };
// "G": Int16
yield return new object[] { Int16Enum.Min, "G", "Min" };
yield return new object[] { (Int16Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { Int16Enum.Max, "G", "Max" };
// "G": UInt16
yield return new object[] { UInt16Enum.Min, "G", "Min" };
yield return new object[] { (UInt16Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { UInt16Enum.Max, "G", "Max" };
// "G": Int32
yield return new object[] { Int32Enum.Min, "G", "Min" };
yield return new object[] { (Int32Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { Int32Enum.Max, "G", "Max" };
// "G": UInt32
yield return new object[] { UInt32Enum.Min, "G", "Min" };
yield return new object[] { (UInt32Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { UInt32Enum.Max, "G", "Max" };
// "G": Int64
yield return new object[] { Int64Enum.Min, "G", "Min" };
yield return new object[] { (Int64Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { Int64Enum.Max, "G", "Max" };
// "G": UInt64
yield return new object[] { UInt64Enum.Min, "G", "Min" };
yield return new object[] { (UInt64Enum)3, "G", "3" }; // No [Flags] attribute
yield return new object[] { UInt64Enum.Max, "G", "Max" };
// "G": SimpleEnum
yield return new object[] { (SimpleEnum)99, "G", "99" };
yield return new object[] { (SimpleEnum)0, "G", "0" }; // Not found
// "G": Flags Attribute
yield return new object[] { AttributeTargets.Class | AttributeTargets.Delegate, "G", "Class, Delegate" };
}
#pragma warning disable 618 // ToString with IFormatProvider is marked as Obsolete.
[Theory]
[MemberData(nameof(ToString_Format_TestData))]
public static void ToString_Format(Enum e, string format, string expected)
{
if (format.ToUpperInvariant() == "G")
{
Assert.Equal(expected, e.ToString());
Assert.Equal(expected, e.ToString(string.Empty));
Assert.Equal(expected, e.ToString((string)null));
Assert.Equal(expected, e.ToString((IFormatProvider)null));
}
// Format string is case-insensitive.
Assert.Equal(expected, e.ToString(format));
Assert.Equal(expected, e.ToString(format.ToUpperInvariant()));
Assert.Equal(expected, e.ToString(format.ToLowerInvariant()));
Assert.Equal(expected, e.ToString(format, (IFormatProvider)null));
Format(e.GetType(), e, format, expected);
}
#pragma warning restore 618
[Fact]
public static void ToString_Format_MultipleMatches()
{
string s = ((SimpleEnum)3).ToString("F");
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
s = ((SimpleEnum)3).ToString("G");
Assert.True(s == "Green" || s == "Green_a" || s == "Green_b");
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
SimpleEnum e = SimpleEnum.Red;
Assert.Throws<FormatException>(() => e.ToString(" \t")); // Format is whitepsace
Assert.Throws<FormatException>(() => e.ToString("y")); // No such format
}
public static IEnumerable<object[]> Format_TestData()
{
// Format: D
yield return new object[] { typeof(SimpleEnum), 1, "D", "1" };
// Format: X
yield return new object[] { typeof(SimpleEnum), SimpleEnum.Red, "X", "00000001" };
yield return new object[] { typeof(SimpleEnum), 1, "X", "00000001" };
// Format: F
yield return new object[] { typeof(SimpleEnum), 1, "F", "Red" };
}
[Theory]
[MemberData(nameof(Format_TestData))]
public static void Format(Type enumType, object value, string format, string expected)
{
// Format string is case insensitive
Assert.Equal(expected, Enum.Format(enumType, value, format.ToUpperInvariant()));
Assert.Equal(expected, Enum.Format(enumType, value, format.ToLowerInvariant()));
}
[Fact]
public static void Format_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("enumType", () => Enum.Format(null, (Int32Enum)1, "F")); // Enum type is null
AssertExtensions.Throws<ArgumentNullException>("value", () => Enum.Format(typeof(SimpleEnum), null, "F")); // Value is null
AssertExtensions.Throws<ArgumentNullException>("format", () => Enum.Format(typeof(SimpleEnum), SimpleEnum.Red, null)); // Format is null
AssertExtensions.Throws<ArgumentException>("enumType", () => Enum.Format(typeof(object), 1, "F")); // Enum type is not an enum type
AssertExtensions.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), (Int32Enum)1, "F")); // Value is of the wrong enum type
AssertExtensions.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), (short)1, "F")); // Value is of the wrong integral
AssertExtensions.Throws<ArgumentException>(null, () => Enum.Format(typeof(SimpleEnum), "Red", "F")); // Value is of the wrong integral
Assert.Throws<FormatException>(() => Enum.Format(typeof(SimpleEnum), SimpleEnum.Red, "")); // Format is empty
Assert.Throws<FormatException>(() => Enum.Format(typeof(SimpleEnum), SimpleEnum.Red, " \t")); // Format is whitespace
Assert.Throws<FormatException>(() => Enum.Format(typeof(SimpleEnum), SimpleEnum.Red, "t")); // No such format
}
public static IEnumerable<object[]> UnsupportedEnumType_TestData()
{
if (PlatformDetection.IsReflectionEmitSupported)
{
yield return new object[] { s_floatEnumType, 1.0f };
yield return new object[] { s_doubleEnumType, 1.0 };
yield return new object[] { s_intPtrEnumType, (IntPtr)1 };
yield return new object[] { s_uintPtrEnumType, (UIntPtr)1 };
}
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void GetName_Unsupported_ThrowsArgumentException(Type enumType, object value)
{
AssertExtensions.Throws<ArgumentException>("value", () => Enum.GetName(enumType, value));
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void IsDefined_UnsupportedEnumType_ThrowsInvalidOperationException(Type enumType, object value)
{
Exception ex = Assert.ThrowsAny<Exception>(() => Enum.IsDefined(enumType, value));
string exName = ex.GetType().Name;
Assert.True(exName == nameof(InvalidOperationException) || exName == "ContractException");
}
public static IEnumerable<object[]> UnsupportedEnum_TestData()
{
yield return new object[] { Enum.ToObject(s_floatEnumType, 1) };
yield return new object[] { Enum.ToObject(s_doubleEnumType, 2) };
yield return new object[] { Enum.ToObject(s_intPtrEnumType, 1) };
yield return new object[] { Enum.ToObject(s_uintPtrEnumType, 2) };
}
[Theory]
[MemberData(nameof(UnsupportedEnum_TestData))]
public static void ToString_UnsupportedEnumType_ThrowsArgumentException(Enum e)
{
Exception formatXException = Assert.ThrowsAny<Exception>(() => e.ToString("X"));
string formatXExceptionName = formatXException.GetType().Name;
Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException");
}
[Theory]
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void Format_UnsupportedEnumType_ThrowsArgumentException(Type enumType, object value)
{
Exception formatGException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "G"));
string formatGExceptionName = formatGException.GetType().Name;
Assert.True(formatGExceptionName == nameof(InvalidOperationException) || formatGExceptionName == "ContractException");
Exception formatXException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "X"));
string formatXExceptionName = formatXException.GetType().Name;
Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException");
Exception formatFException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "F"));
string formatFExceptionName = formatFException.GetType().Name;
Assert.True(formatFExceptionName == nameof(InvalidOperationException) || formatFExceptionName == "ContractException");
}
private static EnumBuilder GetNonRuntimeEnumTypeBuilder(Type underlyingType)
{
if (!PlatformDetection.IsReflectionEmitSupported)
return null;
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineEnum("TestName_" + underlyingType.Name, TypeAttributes.Public, underlyingType);
}
private static Type s_boolEnumType = GetBoolEnumType();
private static Type GetBoolEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(bool));
if (enumBuilder == null)
return null;
enumBuilder.DefineLiteral("Value1", true);
enumBuilder.DefineLiteral("Value2", false);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_charEnumType = GetCharEnumType();
private static Type GetCharEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(char));
if (enumBuilder == null)
return null;
enumBuilder.DefineLiteral("Value1", (char)1);
enumBuilder.DefineLiteral("Value2", (char)2);
enumBuilder.DefineLiteral("Value0x3f06", (char)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (char)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (char)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (char)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (char)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (char)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (char)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_floatEnumType = GetFloatEnumType();
private static Type GetFloatEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(float));
if (enumBuilder == null)
return null;
enumBuilder.DefineLiteral("Value1", 1.0f);
enumBuilder.DefineLiteral("Value2", 2.0f);
enumBuilder.DefineLiteral("Value0x3f06", (float)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (float)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (float)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (float)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (float)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (float)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (float)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_doubleEnumType = GetDoubleEnumType();
private static Type GetDoubleEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(double));
if (enumBuilder == null)
return null;
enumBuilder.DefineLiteral("Value1", 1.0);
enumBuilder.DefineLiteral("Value2", 2.0);
enumBuilder.DefineLiteral("Value0x3f06", (double)0x3f06);
enumBuilder.DefineLiteral("Value0x3000", (double)0x3000);
enumBuilder.DefineLiteral("Value0x0f06", (double)0x0f06);
enumBuilder.DefineLiteral("Value0x1000", (double)0x1000);
enumBuilder.DefineLiteral("Value0x0000", (double)0x0000);
enumBuilder.DefineLiteral("Value0x0010", (double)0x0010);
enumBuilder.DefineLiteral("Value0x3f16", (double)0x3f16);
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_intPtrEnumType = GetIntPtrEnumType();
private static Type GetIntPtrEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(IntPtr));
if (enumBuilder == null)
return null;
return enumBuilder.CreateTypeInfo().AsType();
}
private static Type s_uintPtrEnumType = GetUIntPtrEnumType();
private static Type GetUIntPtrEnumType()
{
EnumBuilder enumBuilder = GetNonRuntimeEnumTypeBuilder(typeof(UIntPtr));
if (enumBuilder == null)
return null;
return enumBuilder.CreateTypeInfo().AsType();
}
}
}
| 53.42671 | 438 | 0.602322 | [
"MIT"
] | AraHaan/runtime | src/libraries/System.Runtime/tests/System/EnumTests.cs | 114,814 | C# |
using System.Drawing;
using System.Text;
using ReClassNET.Util;
namespace ReClassNET
{
public class Settings
{
// Application Settings
public string LastProcess { get; set; } = string.Empty;
public bool StayOnTop { get; set; } = false;
// Node Drawing Settings
public bool ShowNodeAddress { get; set; } = true;
public bool ShowNodeOffset { get; set; } = true;
public bool ShowNodeText { get; set; } = true;
public bool HighlightChangedValues { get; set; } = true;
public Encoding RawDataEncoding { get; set; } = Encoding.GetEncoding(1252); /* Windows-1252 */
// Comment Drawing Settings
public bool ShowCommentFloat { get; set; } = true;
public bool ShowCommentInteger { get; set; } = true;
public bool ShowCommentPointer { get; set; } = true;
public bool ShowCommentRtti { get; set; } = true;
public bool ShowCommentSymbol { get; set; } = true;
public bool ShowCommentString { get; set; } = true;
public bool ShowCommentPluginInfo { get; set; } = true;
// Colors
public Color BackgroundColor { get; set; } = Color.FromArgb(255, 255, 255);
public Color SelectedColor { get; set; } = Color.FromArgb(240, 240, 240);
public Color HiddenColor { get; set; } = Color.FromArgb(240, 240, 240);
public Color OffsetColor { get; set; } = Color.FromArgb(255, 0, 0);
public Color AddressColor { get; set; } = Color.FromArgb(0, 200, 0);
public Color HexColor { get; set; } = Color.FromArgb(0, 0, 0);
public Color TypeColor { get; set; } = Color.FromArgb(0, 0, 255);
public Color NameColor { get; set; } = Color.FromArgb(32, 32, 128);
public Color ValueColor { get; set; } = Color.FromArgb(255, 128, 0);
public Color IndexColor { get; set; } = Color.FromArgb(32, 200, 200);
public Color CommentColor { get; set; } = Color.FromArgb(0, 200, 0);
public Color TextColor { get; set; } = Color.FromArgb(0, 0, 255);
public Color VTableColor { get; set; } = Color.FromArgb(0, 255, 0);
public Color PluginColor { get; set; } = Color.FromArgb(255, 0, 255);
public CustomDataMap CustomData { get; } = new CustomDataMap();
public Settings Clone() => MemberwiseClone() as Settings;
}
}
| 27.74359 | 96 | 0.67098 | [
"MIT"
] | EliteOutlaws/ReClass.NET | ReClass.NET/Settings.cs | 2,166 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.IO;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.MarkdownLite;
public class DfmCodeRenderer
{
private readonly DfmCodeExtractor _dfmCodeExtractor;
public DfmCodeRenderer()
: this((DfmCodeExtractor)null)
{
}
public DfmCodeRenderer(DfmCodeExtractor extractor)
{
_dfmCodeExtractor = extractor ?? new DfmCodeExtractor();
}
public DfmCodeRenderer(CodeLanguageExtractorsBuilder builder)
{
_dfmCodeExtractor = new DfmCodeExtractor(builder);
}
public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesToken token, IMarkdownContext context)
{
if (!PathUtility.IsRelativePath(token.Path))
{
string errorMessage = $"Code absolute path: {token.Path} is not supported in file {context.GetFilePathStack().Peek()}";
Logger.LogError(errorMessage);
return RenderFencesCode(token, renderer.Options, errorMessage);
}
try
{
// Always report original dependency when path is valid
if (PathUtility.IsVaildFilePath(token.Path))
{
context.ReportDependency(token.Path);
}
var pathQueryOption =
!string.IsNullOrEmpty(token.QueryStringAndFragment) ?
_dfmCodeExtractor.ParsePathQueryString(token.QueryStringAndFragment) :
null;
var filePath = FindFile(token, context);
var code = ExtractCode(token, filePath, pathQueryOption);
return RenderFencesCode(token, renderer.Options, code.ErrorMessage, code.CodeLines, pathQueryOption);
}
catch (DirectoryNotFoundException)
{
return RenderReferenceNotFoundErrorMessage(renderer, token);
}
catch (FileNotFoundException)
{
return RenderReferenceNotFoundErrorMessage(renderer, token);
}
}
[Obsolete]
public virtual StringBuffer RenderFencesFromCodeContent(string codeContent, string path, string queryStringAndFragment = null, string name = null, string lang = null, string title = null)
{
if (codeContent == null)
{
return RenderCodeErrorString($"{nameof(codeContent)} can not be null");
}
if (string.IsNullOrEmpty(path))
{
return RenderCodeErrorString($"{nameof(path)} can not been null or empty");
}
if (queryStringAndFragment != null && queryStringAndFragment.Length == 1)
{
return RenderCodeErrorString($"Length of {nameof(queryStringAndFragment)} can not be 1");
}
var pathQueryOption =
!string.IsNullOrEmpty(queryStringAndFragment)
? DfmFencesRule.ParsePathQueryString(queryStringAndFragment.Remove(1), queryStringAndFragment.Substring(1), true)
: null;
var token = new DfmFencesBlockToken(null, null, name, path, new SourceInfo(), lang, title, pathQueryOption, queryStringAndFragment);
var fencesCode = codeContent.Replace("\r\n", "\n").Split('\n');
var code = ExtractCode(token, fencesCode);
return RenderFencesCode(token, new Options { ShouldExportSourceInfo = false }, code.ErrorMessage, code.CodeLines);
}
public virtual StringBuffer RenderFencesFromCodeContent(string codeContent, DfmFencesBlockToken token)
{
if (codeContent == null)
{
return RenderCodeErrorString($"{nameof(codeContent)} can not be null");
}
if (string.IsNullOrEmpty(token.Path))
{
return RenderCodeErrorString($"{nameof(token.Path)} can not been null or empty");
}
if (token.QueryStringAndFragment != null && token.QueryStringAndFragment.Length == 1)
{
return RenderCodeErrorString($"Length of {nameof(token.QueryStringAndFragment)} can not be 1");
}
var fencesCode = codeContent.Replace("\r\n", "\n").Split('\n');
var pathQueryOption = _dfmCodeExtractor.ParsePathQueryString(token.QueryStringAndFragment);
var code = ExtractCode(token, fencesCode, pathQueryOption);
return RenderFencesCode(token, new Options { ShouldExportSourceInfo = false }, code.ErrorMessage, code.CodeLines, pathQueryOption);
}
public virtual string FindFile(DfmFencesToken token, IMarkdownContext context)
{
return DfmFallbackHelper.GetFilePathWithFallback(token.Path, context).Item1;
}
[Obsolete]
public virtual DfmExtractCodeResult ExtractCode(DfmFencesToken token, string filePath)
=> ExtractCode(token, filePath, null);
public virtual DfmExtractCodeResult ExtractCode(DfmFencesToken token, string filePath, IDfmFencesBlockPathQueryOption option)
{
return _dfmCodeExtractor.ExtractFencesCode(token, filePath, option);
}
[Obsolete]
public virtual DfmExtractCodeResult ExtractCode(DfmFencesToken token, string[] fencesCode)
{
return _dfmCodeExtractor.ExtractFencesCode(token, fencesCode, null);
}
public virtual DfmExtractCodeResult ExtractCode(DfmFencesToken token, string[] fencesCode, IDfmFencesBlockPathQueryOption option)
{
return _dfmCodeExtractor.ExtractFencesCode(token, fencesCode, option);
}
public virtual StringBuffer RenderFencesCode(DfmFencesToken token,
Options options,
string errorMessage,
string[] codeLines = null,
IDfmFencesBlockPathQueryOption pathQueryOption = null)
{
StringBuffer result;
string renderedErrorMessage = string.Empty;
string renderedCodeLines = string.Empty;
if (!string.IsNullOrEmpty(errorMessage))
{
result = RenderCodeErrorString(errorMessage);
}
else
{
result = StringBuffer.Empty;
}
if (codeLines != null)
{
result = RenderOpenPreTag(result, token, options);
result = RenderOpenCodeTag(result, token, options, pathQueryOption);
foreach (var line in codeLines)
{
result += StringHelper.HtmlEncode(line);
result += "\n";
}
result = RenderCloseCodeTag(result, token, options);
result = RenderClosePreTag(result, token, options);
}
return result;
}
public virtual StringBuffer RenderOpenPreTag(StringBuffer result, DfmFencesToken token, Options options)
{
result += "<pre";
result = HtmlRenderer.AppendSourceInfo(result, options, token);
return result + ">";
}
public virtual StringBuffer RenderClosePreTag(StringBuffer result, DfmFencesToken token, Options options)
{
return result + "</pre>";
}
[Obsolete]
public virtual StringBuffer RenderOpenCodeTag(StringBuffer result, DfmFencesToken token, Options options)
{
return RenderOpenCodeTag(result, token, options, token.PathQueryOption);
}
public virtual StringBuffer RenderOpenCodeTag(StringBuffer result, DfmFencesToken token, Options options, IDfmFencesBlockPathQueryOption pathQueryOption)
{
result += "<code";
if (!string.IsNullOrEmpty(token.Lang))
{
result = result + " class=\"" + options.LangPrefix + token.Lang + "\"";
}
if (!string.IsNullOrEmpty(token.Name))
{
result = result + " name=\"" + StringHelper.HtmlEncode(token.Name) + "\"";
}
if (!string.IsNullOrEmpty(token.Title))
{
result = result + " title=\"" + StringHelper.HtmlEncode(token.Title) + "\"";
}
if (!string.IsNullOrEmpty(pathQueryOption?.HighlightLines))
{
result = result + " highlight-lines=\"" + StringHelper.HtmlEncode(pathQueryOption.HighlightLines) + "\"";
}
result += ">";
return result;
}
public virtual StringBuffer RenderCloseCodeTag(StringBuffer result, DfmFencesToken token, Options options)
{
return result + "</code>";
}
public virtual StringBuffer RenderReferenceNotFoundErrorMessage(IMarkdownRenderer renderer, DfmFencesToken token)
{
var errorMessageInMarkdown = $"Can not find reference {token.Path}";
var errorMessage = $"Unable to resolve {token.SourceInfo.Markdown}. {errorMessageInMarkdown}.";
Logger.LogWarning(errorMessage, line: token.SourceInfo.LineNumber.ToString(), code: WarningCodes.Markdown.InvalidCodeSnippet);
return RenderCodeErrorString(errorMessageInMarkdown);
}
public virtual StringBuffer RenderCodeErrorString(string errorMessage)
{
return (StringBuffer)"<!-- " + StringHelper.HtmlEncode(errorMessage) + " -->\n";
}
}
}
| 41.518672 | 196 | 0.591645 | [
"MIT"
] | Algorithman/docfx | src/Microsoft.DocAsCode.Dfm/CodeRenderer/DfmCodeRenderer.cs | 9,768 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using CascadeComboboxAsp2.Models;
namespace CascadeComboboxAsp2.Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<City> Cities { get; set; }
public DbSet<Locality> Localities { get; set; }
public DbSet<SubLocality> SubLocalities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
| 24.482759 | 87 | 0.657746 | [
"Apache-2.0"
] | rioda78/CascadeComboboxAsp2 | Data/ApplicationDbContext.cs | 712 | C# |
using System;
using Microsoft.AspNetCore.Components;
namespace Radzen.Blazor
{
/// <summary>
/// Base class for an axis in <see cref="RadzenChart" />.
/// </summary>
public abstract class AxisBase : RadzenChartComponentBase, IChartAxis
{
/// <summary>
/// Gets or sets the stroke (line color) of the axis.
/// </summary>
/// <value>The stroke.</value>
[Parameter]
public string Stroke { get; set; }
/// <summary>
/// Gets or sets the pixel width of axis.
/// </summary>
/// <value>The width of the stroke.</value>
[Parameter]
public double StrokeWidth { get; set; } = 1;
/// <summary>
/// Gets or sets the child content.
/// </summary>
/// <value>The child content.</value>
[Parameter]
public RenderFragment ChildContent { get; set; }
/// <summary>
/// Gets or sets the format string used to display the axis values.
/// </summary>
/// <value>The format string.</value>
[Parameter]
public string FormatString { get; set; }
/// <summary>
/// Gets or sets a formatter function that formats the acis values.
/// </summary>
/// <value>The formatter.</value>
[Parameter]
public Func<object, string> Formatter { get; set; }
/// <summary>
/// Gets or sets the type of the line used to display the axis.
/// </summary>
/// <value>The type of the line.</value>
[Parameter]
public LineType LineType { get; set; }
/// <summary>
/// Gets or sets the grid lines configuration of the current axis.
/// </summary>
/// <value>The grid lines.</value>
public RadzenGridLines GridLines { get; set; } = new RadzenGridLines();
/// <summary>
/// Gets or sets the title configuration.
/// </summary>
/// <value>The title.</value>
public RadzenAxisTitle Title { get; set; } = new RadzenAxisTitle();
/// <summary>
/// Gets or sets the ticks configuration.
/// </summary>
/// <value>The ticks.</value>
public RadzenTicks Ticks { get; set; } = new RadzenTicks();
internal int TickDistance { get; set; } = 100;
/// <summary>
/// Specifies the mimimum value of the axis.
/// </summary>
/// <value>The minimum.</value>
[Parameter]
public object Min { get; set; }
/// <summary>
/// Specifies the maximum value of the axis.
/// </summary>
/// <value>The maximum.</value>
[Parameter]
public object Max { get; set; }
/// <summary>
/// Specifies the step of the axis.
/// </summary>
[Parameter]
public object Step { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="AxisBase"/> is visible.
/// </summary>
/// <value><c>true</c> if visible; otherwise, <c>false</c>.</value>
[Parameter]
public bool Visible { get; set; } = true;
/// <inheritdoc />
protected override bool ShouldRefreshChart(ParameterView parameters)
{
return DidParameterChange(parameters, nameof(Min), Min) ||
DidParameterChange(parameters, nameof(Max), Max) ||
DidParameterChange(parameters, nameof(Visible), Visible) ||
DidParameterChange(parameters, nameof(Step), Step);
}
internal string Format(ScaleBase scale, double idx)
{
var value = scale.Value(idx);
return Format(scale, value);
}
internal string Format(ScaleBase scale, object value)
{
if (Formatter != null)
{
return Formatter(value);
}
else
{
return scale.FormatTick(FormatString, value);
}
}
internal abstract double Size { get; }
}
}
| 31.484615 | 91 | 0.533105 | [
"MIT"
] | Creator512/radzen-blazor | Radzen.Blazor/AxisBase.cs | 4,093 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using NewLife.Reflection;
using XCode.Membership;
using System.Collections.Generic;
#if __CORE__
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NewLife.Cube.Extensions;
#else
using System.Web.Mvc;
#endif
namespace NewLife.Cube
{
/// <summary>对象控制器</summary>
public abstract class ObjectController<TObject> : ControllerBaseX
{
/// <summary>要展现和修改的对象</summary>
protected abstract TObject Value { get; set; }
/// <summary>菜单顺序。扫描是会反射读取</summary>
protected static Int32 MenuOrder { get; set; }
/// <summary>动作执行前</summary>
/// <param name="filterContext"></param>
#if __CORE__
public override void OnActionExecuting(ActionExecutingContext filterContext)
#else
protected override void OnActionExecuting(ActionExecutingContext filterContext)
#endif
{
base.OnActionExecuting(filterContext);
// 显示名和描述
var name = GetType().GetDisplayName() ?? typeof(TObject).GetDisplayName() ?? typeof(TObject).Name;
var des = GetType().GetDescription() ?? typeof(TObject).GetDescription();
ViewBag.Title = name;
ViewBag.HeaderTitle = name;
var txt = "";
if (txt.IsNullOrEmpty()) txt = (ViewBag.Menu as IMenu)?.Remark;
if (txt.IsNullOrEmpty()) txt = (HttpContext.Items["CurrentMenu"] as IMenu)?.Remark;
if (txt.IsNullOrEmpty()) txt = des;
ViewBag.HeaderContent = txt;
if (Value != null)
{
var pis = GetMembers(Value);
var dic = new Dictionary<String, List<PropertyInfo>>();
foreach (var pi in pis)
{
var cat = pi.GetCustomAttribute<CategoryAttribute>();
var category = cat?.Category ?? "";
if (!dic.TryGetValue(category, out var list)) dic[category] = list = new List<PropertyInfo>();
list.Add(pi);
}
ViewBag.Properties = dic;
}
}
/// <summary>执行后</summary>
/// <param name="filterContext"></param>
#if __CORE__
public override void OnActionExecuted(ActionExecutedContext filterContext)
#else
protected override void OnActionExecuted(ActionExecutedContext filterContext)
#endif
{
base.OnActionExecuted(filterContext);
var title = ViewBag.Title + "";
HttpContext.Items["Title"] = title;
}
/// <summary>显示对象</summary>
/// <returns></returns>
[EntityAuthorize(PermissionFlags.Detail)]
public ActionResult Index() => View("ObjectForm", Value);
/// <summary>保存对象</summary>
/// <param name="obj"></param>
/// <returns></returns>
//[HttpPost]
//[DisplayName("修改")]
[EntityAuthorize(PermissionFlags.Update)]
public ActionResult Update(TObject obj)
{
WriteLog(obj, UserHost);
// 反射处理内部复杂成员
#if __CORE__
var keys = Request.Form.Keys;
#else
var keys = Request.Form.AllKeys;
#endif
foreach (var item in obj.GetType().GetProperties(true))
{
if (Type.GetTypeCode(item.PropertyType) == TypeCode.Object)
{
var pv = obj.GetValue(item);
foreach (var pi in item.PropertyType.GetProperties(true))
{
if (keys.Contains(pi.Name))
{
var v = (Object)Request.Form[pi.Name];
if (pi.PropertyType == typeof(Boolean)) v = GetBool(pi.Name);
pv.SetValue(pi, v);
}
}
}
}
Value = obj;
if (Request.IsAjaxRequest())
return Json(new { result = "success", content = "保存成功" });
else
return Redirect("Index");
}
Boolean GetBool(String name)
{
#if __CORE__
var v = Request.GetRequestValue(name);
#else
var v = Request[name];
#endif
if (v.IsNullOrEmpty()) return false;
v = v.Split(",")[0];
if (!v.EqualIgnoreCase("true", "false")) throw new XException("非法布尔值Request[{0}]={1}", name, v);
return v.ToBoolean();
}
/// <summary>写日志</summary>
/// <param name="obj"></param>
/// <param name="ip"></param>
protected virtual void WriteLog(TObject obj, String ip = null)
{
// 构造修改日志
var sb = new StringBuilder();
var cfg = Value;
foreach (var pi in obj.GetType().GetProperties(true))
{
if (!pi.CanWrite) continue;
var v1 = obj.GetValue(pi);
var v2 = cfg.GetValue(pi);
if (!Equals(v1, v2) && (pi.PropertyType != typeof(String) || v1 + "" != v2 + ""))
{
if (sb.Length > 0) sb.Append(", ");
var name = pi.GetDisplayName();
if (name.IsNullOrEmpty()) name = pi.Name;
sb.AppendFormat("{0}:{1}=>{2}", name, v2, v1);
}
}
LogProvider.Provider.WriteLog(obj.GetType(), "修改", true, sb.ToString(), ip: ip);
}
/// <summary>获取要显示编辑的成员</summary>
/// <param name="obj"></param>
/// <returns></returns>
protected virtual PropertyInfo[] GetMembers(Object obj)
{
var type = Value as Type;
if (type == null) type = obj.GetType();
var pis = type.GetProperties(true);
//pis = pis.Where(pi => pi.CanWrite && pi.GetIndexParameters().Length == 0 && pi.GetCustomAttribute<XmlIgnoreAttribute>() == null).ToArray();
return pis.ToArray();
}
}
} | 34.213115 | 154 | 0.513337 | [
"MIT"
] | jinyumao/NewLife.Cube | NewLife.Cube/Common/ObjectController.cs | 6,445 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Web_Application_UberEats.Models;
namespace Web_Application_UberEats.Controllers
{
public class CustomersController : ApiController
{
private CustomerDbEntities db = new CustomerDbEntities();
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult GetCustomer(int id)
{
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
// PUT: api/Customers/5
[ResponseType(typeof(void))]
public IHttpActionResult PutCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.Id)
{
return BadRequest();
}
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Customers
[ResponseType(typeof(Customer))]
public IHttpActionResult PostCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Customers.Add(customer);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = customer.Id }, customer);
}
// DELETE: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult DeleteCustomer(int id)
{
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return NotFound();
}
db.Customers.Remove(customer);
db.SaveChanges();
return Ok(customer);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool CustomerExists(int id)
{
return db.Customers.Count(e => e.Id == id) > 0;
}
}
} | 24.46281 | 84 | 0.508446 | [
"Unlicense"
] | Doctor-Bokisi/Web_Application_UberEats | Controllers/CustomersController.cs | 2,962 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace ConFormSim.Actions
{
/// <summary>
/// An action of this type can pick up and drop objects. Basically it calls the
/// Move() method of an IMovable object and controls the position of the guide
/// transform. Depending on the implementation of the Move() method the IMovable
/// object will be attached to the guide transform.
/// </summary>
/// <remarks>
/// The Execute() method requires 2 additional arguments in the kwargs parameter
/// of the function. Usually these arguments will be passed to execute by the
/// ActionProvider. To do that provide a dictionary to the kwargs parameter
/// containing a 'interactable_gameobject' key and a 'guide_transform'.
///
/// The 'interactable_gameobject' must be a GameObject with a component
/// implementing the IMovable interface.
///
/// The 'guide_transform' must be a Transform. It will be passed to the Move()
/// method of the interactable.
/// </remarks>
[CreateAssetMenu(fileName = "PhysicsPickUp", menuName = "ConFormSim/Agent Actions/PhysicsPickUp", order = 1)]
public class PhysicsPickUp : DiscreteAgentAction
{
/// <summary>
/// Local Position of the guide when dropping an object. This influences the
/// drop/release position of an interactable object.
/// </summary>
// [Tooltip("Local position of the guide, relative to the agent when an " +
// "object is released.")]
// public Vector3 guideDropPosition = new Vector3();
/// <summary>
/// Local Position of the guide when picking the object up and carrying it.
/// </summary>
// [Tooltip("Local position of the guide, relative to the agent when an " +
// "object is carried.")]
// public Vector3 guideCarryPosition = new Vector3();
/// <summary>
/// <inheritdoc cref="Execute"/>
/// </summary>
public override ActionOutcome Execute(
GameObject agent,
Dictionary<string, object> kwargs = null)
{
GameObject interactable;
Transform guide;
// helper variable
object arg;
// check if any arguments were passed
if (kwargs == null)
{
return new ActionOutcome(false, "No parameters passed.");
}
// try to retrieve the interactable object from the arguments dict
if (kwargs.TryGetValue("interactable_gameobject", out arg) && arg != null)
{
if (arg == null)
{
return new ActionOutcome(false, "No interactable object available.");
}
interactable = (GameObject) arg;
}
else
{
Debug.Log("Couldn't perform Pick up, as no interactable object"
+ " was passed to the action. Assign it to the "
+ "'interactable_gameobject' key in the kwargs dict.");
return new ActionOutcome(false, "No interactable object available.");
}
// try to get the transform to which the object will be connected while
// carrying
if (kwargs.TryGetValue("guide_transform", out arg))
{
guide = (Transform) arg;
}
else
{
Debug.Log("Couldn't perform Pick up, as no guide transform "
+ "was passed to the action. Assign a Transform object to "
+ "the 'guide_transform' key in the kwarg dict.");
return new ActionOutcome(false, "No guide transform assigned.");
}
// now that we have all necessary objects perform the actual action
// first check if the interactable has a component implementing an
// IMovable
IMovable movableComponent = interactable.GetComponent<IMovable>();
if (movableComponent == null || interactable == null)
{
Debug.LogError("Couldn't perform Pick Up. The passed interactable "
+ " doesn't have a component implementing the IMovable"
+ " interface.");
return new ActionOutcome(false, "Interactable has no IMovable "
+ "component");
}
// in case there is already an object attached to the guide
FixedJoint joint;
if (guide.childCount > 0 || guide.gameObject.TryGetComponent<FixedJoint>(out joint))
{
// Drop the object
// guide.localPosition = guideDropPosition;
movableComponent.Move(agent.transform, guide);
return new ActionOutcome(true, "Object released.");
}
// else if the guide doesn't has a object attached
else if (guide.childCount == 0 || !guide.gameObject.TryGetComponent<FixedJoint>(out joint))
{
// pick up the object
// guide.localPosition = guideCarryPosition;
movableComponent.Move(agent.transform, guide);
return new ActionOutcome(true, "Object picked.");
}
return new ActionOutcome(false, "No free space to release object.");
}
}
} | 45.04 | 114 | 0.55595 | [
"MIT"
] | JohnBergago/ConFormSim | src/ConFormSimProject/Assets/ConFormSim/Runtime/Actions/PhysicsPickUp.cs | 5,632 | 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/MsiDefs.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason"]/*' />
public enum msirbRebootReason
{
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason.msirbRebootUndeterminedReason"]/*' />
msirbRebootUndeterminedReason = 0,
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason.msirbRebootInUseFilesReason"]/*' />
msirbRebootInUseFilesReason = 1,
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason.msirbRebootScheduleRebootReason"]/*' />
msirbRebootScheduleRebootReason = 2,
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason.msirbRebootForceRebootReason"]/*' />
msirbRebootForceRebootReason = 3,
/// <include file='msirbRebootReason.xml' path='doc/member[@name="msirbRebootReason.msirbRebootCustomActionReason"]/*' />
msirbRebootCustomActionReason = 4,
}
| 49.038462 | 145 | 0.752941 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/MsiDefs/msirbRebootReason.cs | 1,277 | C# |
namespace BalkanAir.Mvp.EventArgs.Account
{
using System;
using Data.Models;
public class ItineraryEventArgs : EventArgs
{
public string UserId { get; set; }
public string Number { get; set; }
public string Passenger { get; set; }
public int BookingId { get; set; }
public BaggageType BaggageType { get; set; }
}
}
| 19.1 | 52 | 0.612565 | [
"MIT"
] | itplamen/Balkan-Air | Balkan Air/Mvp/BalkanAir.Mvp/EventArgs/Account/ItineraryEventArgs.cs | 384 | 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 workspaces-2015-04-08.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.WorkSpaces.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WorkSpaces.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ClientProperties Object
/// </summary>
public class ClientPropertiesUnmarshaller : IUnmarshaller<ClientProperties, XmlUnmarshallerContext>, IUnmarshaller<ClientProperties, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ClientProperties IUnmarshaller<ClientProperties, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ClientProperties Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ClientProperties unmarshalledObject = new ClientProperties();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("ReconnectEnabled", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ReconnectEnabled = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ClientPropertiesUnmarshaller _instance = new ClientPropertiesUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ClientPropertiesUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.880435 | 162 | 0.626675 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/WorkSpaces/Generated/Model/Internal/MarshallTransformations/ClientPropertiesUnmarshaller.cs | 3,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MailCheck.Common.Data;
namespace MailCheck.AggregateReport.Common.Aggregators
{
public interface IRecord
{
/// <summary>
/// Id of the originating record
/// </summary>
long Id { get; }
}
public interface IAggregatorDao<TRecord>
where TRecord : IRecord
{
Task<Outcome> Save(IEnumerable<TRecord> records, AggregatorDao<TRecord>.Settings settings);
}
public class AggregatorDao<TRecord> : IAggregatorDao<TRecord>
where TRecord : IRecord
{
private readonly ILogger<AggregatorDao<TRecord>> _log;
private readonly IDatabase _database;
private readonly Func<string, IDictionary<string, object>, Task<int>> _saveOperation;
public AggregatorDao(ILogger<AggregatorDao<TRecord>> log, IDatabase database) : this(log, database, null) {}
internal AggregatorDao(
ILogger<AggregatorDao<TRecord>> log,
IDatabase database,
Func<string, IDictionary<string, object>, Task<int>> saveOperation
)
{
_log = log;
_database = database;
_saveOperation = saveOperation ?? DefaultSaveToDatabase;
}
public async Task<Outcome> Save(IEnumerable<TRecord> records, Settings settings)
{
if (records is null)
{
throw new ArgumentNullException(nameof(records));
}
var recordsList = records as IList<TRecord> ?? new List<TRecord>(records);
if (recordsList.Count == 0)
{
_log.LogDebug("Empty record list passed to Save()");
return Outcome.EmptyRecords;
}
var distinctRecordIds = recordsList
.Select(r => r.Id)
.Distinct()
.ToArray();
if (distinctRecordIds.Length > 1)
{
throw new AggregatorException($"Expected record batch to all use the same record ID but found {distinctRecordIds.Length} different IDs.");
}
var recordId = distinctRecordIds[0];
var builder = new SqlBuilder()
.AddAggregatorTokens(settings, recordsList.Count);
var commandText = builder.Build(AggregatorDaoResources.IdempotentRecordUpsert);
var parameters = new Dictionary<string, object>(
recordsList.SelectMany((record, recordNum) => settings
.ParameterValuesMapper(record)
.ToDictionary(
paramValue => $"{paramValue.Key}_{recordNum}",
paramValue => paramValue.Value
)
)
);
parameters.Add("record_id", recordId);
var rowsAffected = await _saveOperation(commandText, parameters);
_log.LogInformation("Save operation completed successfully for record {0} (records: {1} rows affected: {2})", recordId, recordsList.Count, rowsAffected);
return Outcome.SavedSuccessfully;
}
private async Task<int> DefaultSaveToDatabase(string commandText, IDictionary<string, object> parameterValues)
{
int rowsAffected = 0;
await WithRetry(5, async () => {
rowsAffected = await SaveToDatabase(commandText, parameterValues);
});
return rowsAffected;
}
private async Task<int> SaveToDatabase(string commandText, IDictionary<string, object> parameterValues)
{
using (var connection = await _database.CreateAndOpenConnectionAsync())
using (var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = System.Data.CommandType.Text;
command.Transaction = transaction;
var parameters = parameterValues.Select(kvp =>
{
var parameter = command.CreateParameter();
parameter.ParameterName = kvp.Key;
parameter.Value = kvp.Value;
return parameter;
}).ToArray();
command.Parameters.AddRange(parameters);
var rowsAffected = await command.ExecuteNonQueryAsync();
transaction.Commit();
return rowsAffected;
}
}
private async Task WithRetry(int maxAttempts, Func<Task> work)
{
int attempt = 0;
while (attempt++ <= maxAttempts)
{
try
{
await work();
break;
}
catch (Exception e)
{
var message = $"Error occured saving records to database (attempt {attempt} of {maxAttempts})";
if (attempt == maxAttempts)
{
throw new AggregatorException(message, e);
}
else
{
_log.LogWarning(e, message);
}
await Task.Delay(attempt * 1000);
}
}
}
public class Settings : AggregatorSqlBuilderSettings
{
public Func<TRecord, IEnumerable<KeyValuePair<string, object>>> ParameterValuesMapper { get; set; }
}
}
public class Outcome
{
public static readonly Outcome SavedSuccessfully = new Outcome
{
Success = true,
Message = "Records saved successfully"
};
public static readonly Outcome AlreadyProcessed = new Outcome
{
Success = true,
Message = "Records already processed - ignored."
};
public static readonly Outcome EmptyRecords = new Outcome
{
Success = true,
Message = "Records empty - nothing to save."
};
public bool Success { get; private set; }
public string Message { get; private set; }
}
}
| 33.097938 | 165 | 0.551627 | [
"Apache-2.0"
] | ukncsc/MailCheck.Public.AggregateReport | src/MailCheck.AggregateReport.Common/Aggregators/AggregatorDao.cs | 6,423 | C# |
namespace Day2;
public record Command
{
public Direction Direction { get; private init; }
public int Amount { get; private init; }
public static Command FromString(string command)
{
var splitCommand = command.Split(' ');
if (splitCommand.Length != 2)
{
throw new InvalidDataException("Provided command was not in the format '<direction> <amount>'");
}
var direction = Enum.Parse<Direction>(splitCommand[0], true);
var amount = int.Parse(splitCommand[1]);
return new Command
{
Direction = direction,
Amount = amount
};
}
} | 25.5 | 108 | 0.58371 | [
"MIT"
] | LukeBillo/advent-of-code-2021 | Day2/Command.cs | 665 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
internal class Bb : Aa
{
public new bool no;
}
} | 39.5625 | 68 | 0.748815 | [
"MIT"
] | 0xced/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/Bb.cs | 1,266 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Proto.Router.Messages;
using Proto.TestFixtures;
using Xunit;
namespace Proto.Router.Tests
{
public class ConsistentHashGroupTests
{
private static readonly Props MyActorProps = Actor.FromProducer(() => new MyTestActor())
.WithMailbox(() => new TestMailbox());
private readonly TimeSpan _timeout = TimeSpan.FromMilliseconds(1000);
[Fact]
public async void ConsistentHashGroupRouter_MessageWithSameHashAlwaysGoesToSameRoutee()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
router.Tell(new Message("message1"));
router.Tell(new Message("message1"));
router.Tell(new Message("message1"));
Assert.Equal(3, await routee1.RequestAsync<int>("received?", _timeout));
Assert.Equal(0, await routee2.RequestAsync<int>("received?", _timeout));
Assert.Equal(0, await routee3.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_MessagesWithDifferentHashesGoToDifferentRoutees()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
router.Tell(new Message("message1"));
router.Tell(new Message("message2"));
router.Tell(new Message("message3"));
Assert.Equal(1, await routee1.RequestAsync<int>("received?", _timeout));
Assert.Equal(1, await routee2.RequestAsync<int>("received?", _timeout));
Assert.Equal(1, await routee3.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_MessageWithSameHashAlwaysGoesToSameRoutee_EvenWhenNewRouteeAdded()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
router.Tell(new Message("message1"));
var routee4 = Actor.Spawn(MyActorProps);
router.Tell(new RouterAddRoutee{PID = routee4});
router.Tell(new Message("message1"));
Assert.Equal(2, await routee1.RequestAsync<int>("received?", _timeout));
Assert.Equal(0, await routee2.RequestAsync<int>("received?", _timeout));
Assert.Equal(0, await routee3.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_RouteesCanBeRemoved()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
router.Tell(new RouterRemoveRoutee { PID = routee1 });
var routees = await router.RequestAsync<Routees>(new RouterGetRoutees(), _timeout);
Assert.DoesNotContain(routee1, routees.PIDs);
Assert.Contains(routee2, routees.PIDs);
Assert.Contains(routee3, routees.PIDs);
}
[Fact]
public async void ConsistentHashGroupRouter_RouteesCanBeAdded()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
var routee4 = Actor.Spawn(MyActorProps);
router.Tell(new RouterAddRoutee { PID = routee4 });
var routees = await router.RequestAsync<Routees>(new RouterGetRoutees(), _timeout);
Assert.Contains(routee1, routees.PIDs);
Assert.Contains(routee2, routees.PIDs);
Assert.Contains(routee3, routees.PIDs);
Assert.Contains(routee4, routees.PIDs);
}
[Fact]
public async void ConsistentHashGroupRouter_RemovedRouteesNoLongerReceiveMessages()
{
var (router, routee1, _, _) = CreateRouterWith3Routees();
router.Tell(new RouterRemoveRoutee { PID = routee1 });
router.Tell(new Message("message1"));
Assert.Equal(0, await routee1.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_AddedRouteesReceiveMessages()
{
var (router, _, _, _) = CreateRouterWith3Routees();
var routee4 = Actor.Spawn(MyActorProps);
router.Tell(new RouterAddRoutee { PID = routee4 });
router.Tell(new Message("message4"));
Assert.Equal(1, await routee4.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_MessageIsReassignedWhenRouteeRemoved()
{
var (router, routee1, routee2, _) = CreateRouterWith3Routees();
router.Tell(new Message("message1"));
// routee1 handles "message1"
Assert.Equal(1, await routee1.RequestAsync<int>("received?", _timeout));
// remove receiver
router.Tell(new RouterRemoveRoutee { PID = routee1 });
// routee2 should now handle "message1"
router.Tell(new Message("message1"));
Assert.Equal(1, await routee2.RequestAsync<int>("received?", _timeout));
}
[Fact]
public async void ConsistentHashGroupRouter_AllRouteesReceiveRouterBroadcastMessages()
{
var (router, routee1, routee2, routee3) = CreateRouterWith3Routees();
router.Tell(new RouterBroadcastMessage { Message = new Message("hello") });
Assert.Equal(1, await routee1.RequestAsync<int>("received?", _timeout));
Assert.Equal(1, await routee2.RequestAsync<int>("received?", _timeout));
Assert.Equal(1, await routee3.RequestAsync<int>("received?", _timeout));
}
private (PID router, PID routee1, PID routee2, PID routee3) CreateRouterWith3Routees()
{
// assign unique names for when tests run in parallel
var routee1 = Actor.SpawnNamed(MyActorProps, Guid.NewGuid() + "routee1");
var routee2 = Actor.SpawnNamed(MyActorProps, Guid.NewGuid() + "routee2");
var routee3 = Actor.SpawnNamed(MyActorProps, Guid.NewGuid() + "routee3");
var props = Router.NewConsistentHashGroup(SuperIntelligentDeterministicHash.Hash, 1, routee1, routee2, routee3)
.WithMailbox(() => new TestMailbox());
var router = Actor.Spawn(props);
return (router, routee1, routee2, routee3);
}
private static class SuperIntelligentDeterministicHash
{
public static uint Hash(string hashKey)
{
if (hashKey.EndsWith("routee1")) return 10;
if (hashKey.EndsWith("routee2")) return 20;
if (hashKey.EndsWith("routee3")) return 30;
if (hashKey.EndsWith("routee4")) return 40;
if (hashKey.EndsWith("message1")) return 9;
if (hashKey.EndsWith("message2")) return 19;
if (hashKey.EndsWith("message3")) return 29;
if (hashKey.EndsWith("message4")) return 39;
return 0;
}
}
internal class Message : IHashable
{
private readonly string _value;
public Message(string value)
{
_value = value;
}
public string HashBy()
{
return _value;
}
public override string ToString()
{
return _value;
}
}
internal class MyTestActor : IActor
{
private readonly List<string> _receivedMessages = new List<string>();
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case string msg when msg == "received?":
context.Sender.Tell(_receivedMessages.Count);
break;
case Message msg:
_receivedMessages.Add(msg.ToString());
break;
}
return Actor.Done;
}
}
}
}
| 39.911765 | 123 | 0.596659 | [
"Apache-2.0"
] | renesugar/ProjectExodus | democode/Proto.Router/router/ConsistentHashGroupTests.cs | 8,144 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 26.190909 | 201 | 0.600486 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrapWrapWrap.cs | 2,883 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using CQRSMagic.Event;
namespace CQRSMagic.Domain
{
public abstract class AggregateBase : IAggregate
{
private static readonly AggregateEventHandlers EventHandlers = new AggregateEventHandlers();
public Guid Id { get; protected set; }
public void ApplyEvents(IEnumerable<IEvent> events)
{
foreach (var @event in events.OrderBy(e => e.EventCreated))
{
ApplyEvent(@event);
}
}
private void ApplyEvent(IEvent @event)
{
try
{
var eventHandler = EventHandlers.FindEventHandler(GetType(), @event);
if (eventHandler == null)
{
return;
}
try
{
eventHandler.Invoke(this, new object[] {@event});
}
catch (Exception exception)
{
var message = string.Format("Cannot apply {0} event to {1}/{2} with {3}.{4}.", @event.GetType(), GetType(), @event.AggregateId, eventHandler.DeclaringType, eventHandler.Name);
throw new EventException(message, exception);
}
}
catch (Exception exception)
{
var message = string.Format("Cannot apply {0} event to {1}/{2}.", @event.GetType(), GetType(), @event.AggregateId);
throw new EventException(message, exception);
}
}
}
} | 31.78 | 195 | 0.522341 | [
"MIT"
] | OpenMagic/CQRSMagic | Projects/CQRSMagic/Domain/AggregateBase.cs | 1,591 | C# |
using LinCms.Zero.Data;
namespace LinCms.Web.Models.Cms.Admins
{
public class UserSearchDto:PageDto
{
public int? GroupId { get; set; }
}
}
| 16.2 | 41 | 0.648148 | [
"MIT"
] | crazyants/lin-cms-dotnetcore | src/LinCms.Web/Models/Cms/Admins/UserSearchDto.cs | 164 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.261
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Faker.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Name {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Name() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Faker.WP71.Resources.Name", typeof(Name).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Aaliyah; Aaron; Abagail; Abbey; Abbie; Abbigail; Abby; Abdiel; Abdul; Abdullah; Abe; Abel; Abelardo; Abigail; Abigale; Abigayle; Abner; Abraham; Ada; Adah; Adalberto; Adaline; Adam; Adan; Addie; Addison; Adela; Adelbert; Adele; Adelia; Adeline; Adell; Adella; Adelle; Aditya; Adolf; Adolfo; Adolph; Adolphus; Adonis; Adrain; Adrian; Adriana; Adrianna; Adriel; Adrien; Adrienne; Afton; Aglae; Agnes; Agustin; Agustina; Ahmad; Ahmed; Aida; Aidan; Aiden; Aileen; Aimee; Aisha; Aiyana; Akeem; Al; Alaina; Alan; Alana [rest of string was truncated]";.
/// </summary>
internal static string First {
get {
return ResourceManager.GetString("First", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Abbott; Abernathy; Abshire; Adams; Altenwerth; Anderson; Ankunding; Armstrong; Auer; Aufderhar; Bahringer; Bailey; Balistreri; Barrows; Bartell; Bartoletti; Barton; Bashirian; Batz; Bauch; Baumbach; Bayer; Beahan; Beatty; Bechtelar; Becker; Bednar; Beer; Beier; Berge; Bergnaum; Bergstrom; Bernhard; Bernier; Bins; Blanda; Blick; Block; Bode; Boehm; Bogan; Bogisich; Borer; Bosco; Botsford; Boyer; Boyle; Bradtke; Brakus; Braun; Breitenberg; Brekke; Brown; Bruen; Buckridge; Carroll; Carter; Cartwright; Casper; [rest of string was truncated]";.
/// </summary>
internal static string Last {
get {
return ResourceManager.GetString("Last", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mr.;Mrs.;Ms.;Miss;Dr..
/// </summary>
internal static string Prefix {
get {
return ResourceManager.GetString("Prefix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Jr.;Sr.;I;II;III;IV;V;MD;DDS;PhD;DVM.
/// </summary>
internal static string Suffix {
get {
return ResourceManager.GetString("Suffix", resourceCulture);
}
}
}
}
| 49.77 | 604 | 0.611412 | [
"MIT"
] | ghuntley/faker-cs | src/Faker.WP71/Resources/Name.Designer.cs | 4,979 | C# |
//
// Copyright 2017 James Finlay
//
// 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.Xna.Framework;
namespace FishTank.Drawing
{
/// <summary>
/// Describes a handler for tiled multi-asset <see cref="SpriteSheet"/>s. Used when an image contains multiple
/// assets within it to show different states or <see cref="Animation"/>.
/// </summary>
public class SpriteSheet
{
/// <summary>
/// Path to the tiled multi-asset <see cref="SpriteSheet"/> image.
/// </summary>
public string AssetName { get; private set; }
/// <summary>
/// The width & height of the individual tiles in the <see cref="SpriteSheet"/> image.
/// </summary>
public Point TileSize { get; private set; }
/// <summary>
/// The width of the individual tiles in the <see cref="SpriteSheet"/> image.
/// </summary>
public int TileWidth => TileSize.X;
/// <summary>
/// The height of the individual tiles in the <see cref="SpriteSheet"/> image.
/// </summary>
public int TileHeight => TileSize.Y;
/// <summary>
/// The location of the first tile in the <see cref="SpriteSheet"/> image, as a source <see cref="Rectangle"/>.
/// </summary>
public Rectangle DefaultTile => new Rectangle(Point.Zero, TileSize);
/// <summary>
/// Creates a new instance of the <see cref="SpriteSheet"/> with the given image path and tile size.
/// </summary>
/// <param name="asset">Path to the tiled multi-asset <see cref="SpriteSheet"/> image.</param>
/// <param name="tileSize">Width & height of the individual tiels in the <see cref="SpriteSheet"/> image.</param>
public SpriteSheet(string asset, Point tileSize)
{
AssetName = asset;
TileSize = tileSize;
}
}
}
| 37.90625 | 121 | 0.624897 | [
"Apache-2.0"
] | Jtfinlay/FishTank | src/FishTank/FishTank/Drawing/SpriteSheet.cs | 2,428 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Leap.Unity;
public class fingerPosition : MonoBehaviour {
[Header("Sphere Collider")]
public float collideeSize = 0.01f; // Size of all Trigger Objects Sphere Collider
//If collidingObjects are fingers then make sure Elements 0-4 is the left hand and 5-9 is the right hand
public GameObject leftHand = null;
public GameObject rightHand = null;
public GameObject[] fingers = new GameObject[10];
public string[] touchingFingers = new string[10];
public Vector3[] touchPosition3 = new Vector3[10];
public Vector2[] touchPosition2 = new Vector2[10];
public Vector3 objectPosition;
// Use this for initialization
void Start() {
objectPosition = transform.position;
for(int i = 0; i < 10; i++){
if(i < 5){
fingers[i] = leftHand.transform.GetChild(i).gameObject;
}else{
fingers[i] = rightHand.transform.GetChild(i - 5).gameObject;
}
}
// Loop all trigger objects
for (int i = 0; i < 10; i++) {
// Initialize all trigger objects to have a sphere collider and set the specified size
if (fingers[i] != null && !fingers[i].GetComponent<SphereCollider>()) {
fingers[i].AddComponent<SphereCollider> ();
fingers[i].GetComponent<SphereCollider> ().radius = collideeSize;
}
}
for(int i = 0; i < touchPosition3.Length; i++)
{
touchPosition3[i] = Vector3.zero;
touchPosition2[i] = Vector2.zero;
}
}
// Update is called once per frame
void Update () {
objectPosition = transform.position;
for (int i = 0; i < touchPosition3.Length; i++) {
if (touchPosition3[i] != Vector3.zero) {
float x = fingers[i].transform.InverseTransformPoint (objectPosition).x;
float y = fingers[i].transform.InverseTransformPoint (objectPosition).y;
float z = fingers[i].transform.InverseTransformPoint (objectPosition).z;
if (i < 5) {
touchingFingers [i] = "Left" + fingers[i].name;
touchPosition3 [i] = new Vector3 (x, y, z);
touchPosition2 [i] = new Vector2 (x, y);
} else {
touchingFingers [i] = "Right" + fingers[i].name;
touchPosition3 [i] = new Vector3 (x, y, z);
touchPosition2 [i] = new Vector2 (x, y);
}
}
}
}
void OnTriggerEnter(Collider collider)
{
for (int i = 0; i < touchingFingers.Length; i++)
{
// If colliding object is the same trigger object
if (collider.gameObject.GetInstanceID() == fingers[i].GetInstanceID())
{
float x = fingers[i].transform.InverseTransformPoint(objectPosition).x;
float y = fingers[i].transform.InverseTransformPoint(objectPosition).y;
float z = fingers[i].transform.InverseTransformPoint(objectPosition).z;
x *= 100f;
x = Mathf.Round (x)/100f;
y *= 100f;
y = Mathf.Round (y)/100f;
z *= 100f;
z = Mathf.Round (z)/100f;
if (i < 5)
{
touchingFingers[i] = "Left" + fingers[i].name;
touchPosition3[i] = new Vector3(x, y, z);
touchPosition2[i] = new Vector2(x, y);
}
else
{
touchingFingers[i] = "Right" + fingers[i].name;
touchPosition3[i] = new Vector3(x, y, z);
touchPosition2[i] = new Vector2(x, y);
}
}
}
}
void OnTriggerExit(Collider collider){
for (int i = 0; i < touchingFingers.Length; i++)
{
// If colliding object is the same trigger object
if (collider.gameObject.GetInstanceID() == fingers[i].GetInstanceID())
{
if (i < 5)
{
touchingFingers[i] = null;
touchPosition3[i] = Vector3.zero;
touchPosition2[i] = Vector2.zero;
}
else
{
touchingFingers[i] = null;
touchPosition3[i] = Vector3.zero;
touchPosition2[i] = Vector2.zero;
}
}
}
}
}
| 21.536723 | 115 | 0.62723 | [
"MIT"
] | jdesnoyers/Transcending-Perception | Assets/Scripts/XY Grid/fingerPosition.cs | 3,814 | C# |
using ServiceSupport.Infrastructure.CQRS.Queries;
using ServiceSupport.Infrastructure.DTO;
using System;
using System.Collections.Generic;
using System.Text;
namespace ServiceSupport.Infrastructure.CQRS.Shops
{
public class GetShopQuery : IQuery<ShopDto>
{
public Guid ShopId { get; }
public GetShopQuery(Guid shopId)
{
ShopId = shopId;
}
}
}
| 22.277778 | 50 | 0.688279 | [
"MIT"
] | Lukasz0303/ServiceSupport | src/ServiceSupport.Infrastructure/CQRS/Shops/GetShopQuery .cs | 403 | C# |
// Zyborg ASP.NET Core Identity Storage Provider for ASP.NET Membership Database.
// Copyright (C) Zyborg.
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Identity;
namespace Zyborg.AspNetCore.Identity.AspNetMembership;
public class MembershipPasswordHasher : IPasswordHasher<MembershipUser>
{
public const int SaltSizeBytes = 128 / 8; // 128 bits
public string HashPassword(MembershipUser user, string password)
{
return HashSaltedPassword(null, password);
}
public PasswordVerificationResult VerifyHashedPassword(MembershipUser user, string hashedPassword, string providedPassword)
{
var passparts = user.PasswordHash?.Split(":", 2);
if (passparts == null || passparts.Length < 2)
{
return PasswordVerificationResult.Failed;
}
var saltBytes = Convert.FromBase64String(passparts[0]);
var hashedNew = HashSaltedPassword(saltBytes, providedPassword);
return hashedPassword == hashedNew
? PasswordVerificationResult.Success
: PasswordVerificationResult.Failed;
}
private string HashSaltedPassword(byte[]? saltBytes, string password)
{
// Salting and hashing compatible with Membership default password hashing algo:
// * 128-bit salt
// * Unicode encoding of string password
// * SHA1-hashing
if (saltBytes == null)
saltBytes = RandomNumberGenerator.GetBytes(SaltSizeBytes);
var passBytes = Encoding.Unicode.GetBytes(password);
var totalData = new byte[saltBytes.Length + passBytes.Length];
Buffer.BlockCopy(saltBytes, 0, totalData, 0, saltBytes.Length);
Buffer.BlockCopy(passBytes, 0, totalData, saltBytes.Length, passBytes.Length);
var hashBytes = SHA1.HashData(totalData);
var saltB64 = Convert.ToBase64String(saltBytes);
var hashB64 = Convert.ToBase64String(hashBytes);
// We encode the generated salt and computed hash as a single string
return $"{saltB64}:{hashB64}";
}
}
| 36.77193 | 127 | 0.69084 | [
"MIT"
] | zyborg/Zyborg.AspNetCore.Identity.AspNetMembership | Zyborg.AspNetCore.Identity.AspNetMembership/MembershipPasswordHasher.cs | 2,098 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Nagraj.EntityFrameworkCore;
namespace Nagraj.Migrations
{
[DbContext(typeof(NagrajDbContext))]
[Migration("20170804083601_Upgraded_To_Abp_v2.2.2")]
partial class Upgraded_To_Abp_v222
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ContactIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ContactName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration")
.HasColumnType("int");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<int?>("ImpersonatorTenantId")
.HasColumnType("int");
b.Property<long?>("ImpersonatorUserId")
.HasColumnType("bigint");
b.Property<string>("MethodName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsGranted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.HasColumnType("nvarchar(450)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long?>("UserLinkId")
.HasColumnType("bigint");
b.Property<string>("UserName")
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("BrowserInfo")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("ContactIpAddress")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ContactName")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<byte>("Result")
.HasColumnType("tinyint");
b.Property<string>("TenancyName")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("UserNameOrEmailAddress")
.HasColumnType("nvarchar(255)")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<long>("OrganizationUnitId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<bool>("IsAbandoned")
.HasColumnType("bit");
b.Property<string>("JobArgs")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.HasColumnType("tinyint");
b.Property<short>("TryCount")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long?>("UserId")
.HasColumnType("bigint");
b.Property<string>("Value")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("Icon")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsDisabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasColumnType("nvarchar(10)")
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<string>("TenantIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasColumnType("nvarchar(max)")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<string>("Data")
.HasColumnType("nvarchar(max)")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasColumnType("nvarchar(512)")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasColumnType("nvarchar(96)")
.HasMaxLength(96);
b.Property<byte>("Severity")
.HasColumnType("tinyint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<Guid>("TenantNotificationId")
.HasColumnType("uniqueidentifier");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(95)")
.HasMaxLength(95);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<long?>("ParentId")
.HasColumnType("bigint");
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Nagraj.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<bool>("IsDefault")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("Nagraj.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("AuthenticationSource")
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("EmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsLockoutEnabled")
.HasColumnType("bit");
b.Property<bool>("IsPhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<bool>("IsTwoFactorEnabled")
.HasColumnType("bit");
b.Property<DateTime?>("LastLoginTime")
.HasColumnType("datetime2");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("LockoutEndDateUtc")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasColumnType("nvarchar(328)")
.HasMaxLength(328);
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.Property<int?>("TenantId")
.HasColumnType("int");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("nvarchar(32)")
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("Nagraj.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ConnectionString")
.HasColumnType("nvarchar(1024)")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("EditionId")
.HasColumnType("int");
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasColumnType("nvarchar(64)")
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId")
.HasColumnType("int");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId")
.HasColumnType("int");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("Nagraj.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Nagraj.Authorization.Roles.Role", b =>
{
b.HasOne("Nagraj.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Nagraj.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Nagraj.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Nagraj.Authorization.Users.User", b =>
{
b.HasOne("Nagraj.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Nagraj.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Nagraj.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Nagraj.MultiTenancy.Tenant", b =>
{
b.HasOne("Nagraj.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Nagraj.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("Nagraj.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("Nagraj.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("Nagraj.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 35.346549 | 117 | 0.428898 | [
"MIT"
] | malkesh-m/Nagraj | aspnet-core/src/Nagraj.EntityFrameworkCore/Migrations/20170804083601_Upgraded_To_Abp_v2.2.2.Designer.cs | 48,142 | C# |
/*
* The MIT License (MIT)
* Copyright (c) 2014 Andrés Correa Casablanca
*
* 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.
*/
/*
* Contributors:
* - Andrés Correa Casablanca <castarco@gmail.com , castarco@litipk.com>
*/
using Litipk.ColorSharp.ColorSpaces;
using Litipk.ColorSharp.LightSpectrums;
namespace Litipk.ColorSharp
{
namespace Illuminants
{
/**
* <summary>
* CIE Standard Illuminant D50. Constructed to represent natural daylight at the horizon. CCT of 5003 K.
* </summary>
*/
public static class CIE_D50
{
/**
* <value>D50 expressed in its 'original form', a light spectrum.</value>
*/
public static readonly RegularLightSpectrum spectrum_Sample = new RegularLightSpectrum(
380, 780, new [] {
24.50,
27.20,
29.80,
39.60,
49.30,
52.90,
56.50,
58.30,
60.00,
58.90,
57.80,
66.30,
74.80,
81.00,
87.20,
88.90,
90.60,
91.00,
91.40,
93.30,
95.20,
93.60,
92.00,
93.90,
95.70,
96.20,
96.60,
96.90,
97.10,
99.60,
102.10,
101.50,
100.80,
101.60,
102.30,
101.20,
100.00,
98.90,
97.70,
98.30,
98.90,
96.20,
93.50,
95.60,
97.70,
98.50,
99.30,
99.20,
99.00,
97.40,
95.70,
97.30,
98.80,
97.30,
95.70,
97.00,
98.20,
100.60,
103.00,
101.10,
99.10,
93.30,
87.40,
89.50,
91.60,
92.30,
92.90,
84.90,
76.80,
81.70,
86.60,
89.60,
92.60,
85.40,
78.20,
68.00,
57.70,
70.30,
82.90,
80.60,
78.30
}
);
}
}
}
| 20.455882 | 106 | 0.593817 | [
"MIT"
] | Litipk/ColorSharp | ColorSharp/src/Illuminants/CIE_D50.cs | 2,786 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.