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
namespace Restract { using System; using Core; using Restract.Contract; internal class InterceptorActivator : IInterceptorActivator { private readonly ITypeActivator _typeActivator; public InterceptorActivator(ITypeActivator typeActivator) { _typeActivator = typeActivator; } public HttpMessageInterceptor Activate(InterceptorRegistration registration) { if (registration.InterceptorInstance != null) { return registration.InterceptorInstance; } try { HttpMessageInterceptor interceptor; if (registration.InterceptorType != null) { interceptor = _typeActivator.Activate(registration.InterceptorType) as HttpMessageInterceptor; } else { interceptor = registration.InterceptorFactory(); } if (interceptor == null) { var interceptorType = registration.InterceptorType != null ? "type: " + registration.InterceptorType : " factory method"; throw new InvalidOperationException($"Interceptor registered with {interceptorType} resolved to null."); } return interceptor; } catch (Exception ex) { var interceptorType = registration.InterceptorType != null ? "type: " + registration.InterceptorType : " factory method"; throw new InvalidOperationException($"Cannot activate interceptor registered with {interceptorType}.", ex); } } } }
34.7
141
0.570605
[ "MIT" ]
bashiransari/Restract
src/Restract/InterceptorActivator.cs
1,735
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Shashlik.Utils.Helpers { /// <summary> /// 异步内存锁 /// </summary> public sealed class AsyncLock { private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); /// <summary> /// lock /// </summary> /// <param name="waitTimeoutCancellationToken">锁等待超时token</param> /// <returns></returns> public async Task<Releaser> LockAsync(CancellationToken waitTimeoutCancellationToken = default) { waitTimeoutCancellationToken.ThrowIfCancellationRequested(); await _semaphore.WaitAsync(waitTimeoutCancellationToken); return new Releaser(this); } /// <summary> /// lock /// </summary> /// <param name="waitTimeoutCancellationToken">锁等待超时token</param> /// <returns></returns> public Releaser Lock(CancellationToken waitTimeoutCancellationToken = default) { waitTimeoutCancellationToken.ThrowIfCancellationRequested(); _semaphore.Wait(waitTimeoutCancellationToken); return new Releaser(this); } public readonly struct Releaser : IDisposable { private readonly AsyncLock _toRelease; internal Releaser(AsyncLock toRelease) { _toRelease = toRelease; } public void Dispose() => _toRelease._semaphore.Release(); } } }
30.039216
103
0.603786
[ "MIT" ]
dotnet-shashlik/shashlik
src/Shashlik.Utils/Helpers/AsyncLock.cs
1,564
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using FakeStorage; using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.Azure.WebJobs.Host.Executors; using Microsoft.Azure.WebJobs.Host.Indexers; using Microsoft.Azure.WebJobs.Host.Protocols; using Microsoft.Azure.WebJobs.Host.TestCommon; using Microsoft.Azure.WebJobs.Host.Timers; using Microsoft.Azure.WebJobs.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using Xunit; using SingletonLockHandle = Microsoft.Azure.WebJobs.Host.StorageBaseDistributedLockManager.SingletonLockHandle; namespace Microsoft.Azure.WebJobs.Host.UnitTests.Singleton { internal static class Ext // $$$ move to better place { // Wrapper to get the internal class. public static async Task<SingletonLockHandle> TryLockInternalAsync(this SingletonManager manager, string lockId, string functionInstanceId, SingletonAttribute attribute, CancellationToken cancellationToken, bool retry = true) { var handle = await manager.TryLockAsync(lockId, functionInstanceId, attribute, cancellationToken, retry); return handle.GetInnerHandle(); } public static SingletonLockHandle GetInnerHandle(this RenewableLockHandle handle) { if (handle == null) { return null; } return (SingletonLockHandle)handle.InnerLock; } } public class SingletonManagerTests { private const string TestHostId = "testhost"; private const string TestLockId = "testid"; private const string TestInstanceId = "testinstance"; private const string TestLeaseId = "testleaseid"; private const string Secondary = "SecondaryStorage"; private readonly IConfiguration _configuration = new ConfigurationBuilder().Build(); private StorageBaseDistributedLockManager _core; private SingletonManager _singletonManager; private SingletonOptions _singletonConfig; private CloudBlobDirectory _mockBlobDirectory; private CloudBlobDirectory _mockSecondaryBlobDirectory; internal FakeAccount _account1 = new FakeAccount(); internal FakeAccount _account2 = new FakeAccount(); private Mock<IWebJobsExceptionHandler> _mockExceptionDispatcher; private Mock<CloudBlockBlob> _mockStorageBlob; private TestLoggerProvider _loggerProvider; private readonly Dictionary<string, string> _mockBlobMetadata; private TestNameResolver _nameResolver; private class FakeLeaseProvider : StorageBaseDistributedLockManager { internal FakeAccount _account1 = new FakeAccount(); internal FakeAccount _account2 = new FakeAccount(); public FakeLeaseProvider(ILoggerFactory logger) : base(logger) { } protected override CloudBlobContainer GetContainer(string accountName) { FakeAccount account; if (string.IsNullOrEmpty(accountName) || accountName == ConnectionStringNames.Storage) { account = _account1; } else if (accountName == Secondary) { account = _account2; } else { throw new InvalidOperationException("Unknown account: " + accountName); } var container = account.CreateCloudBlobClient().GetContainerReference("azure-webjobs-hosts"); return container; } } public SingletonManagerTests() { ILoggerFactory loggerFactory = new LoggerFactory(); _loggerProvider = new TestLoggerProvider(); loggerFactory.AddProvider(_loggerProvider); var logger = loggerFactory?.CreateLogger(LogCategories.Singleton); var leaseProvider = new FakeLeaseProvider(loggerFactory); _mockBlobDirectory = leaseProvider._account1.CreateCloudBlobClient().GetContainerReference(HostContainerNames.Hosts).GetDirectoryReference(HostDirectoryNames.SingletonLocks); _mockSecondaryBlobDirectory = leaseProvider._account2.CreateCloudBlobClient().GetContainerReference(HostContainerNames.Hosts).GetDirectoryReference(HostDirectoryNames.SingletonLocks); _mockExceptionDispatcher = new Mock<IWebJobsExceptionHandler>(MockBehavior.Strict); _mockStorageBlob = new Mock<CloudBlockBlob>(MockBehavior.Strict, new Uri("https://fakeaccount.blob.core.windows.net/" + HostContainerNames.Hosts + "/" + HostDirectoryNames.SingletonLocks + "/" + TestLockId)); _mockBlobMetadata = new Dictionary<string, string>(); leaseProvider._account1.SetBlob(HostContainerNames.Hosts, HostDirectoryNames.SingletonLocks + "/" + TestLockId, _mockStorageBlob.Object); _singletonConfig = new SingletonOptions(); // use reflection to bypass the normal validations (so tests can run fast) TestHelpers.SetField(_singletonConfig, "_lockAcquisitionPollingInterval", TimeSpan.FromMilliseconds(25)); TestHelpers.SetField(_singletonConfig, "_lockPeriod", TimeSpan.FromMilliseconds(500)); _singletonConfig.LockAcquisitionTimeout = TimeSpan.FromMilliseconds(200); _nameResolver = new TestNameResolver(); _core = leaseProvider; _singletonManager = new SingletonManager(_core, new OptionsWrapper<SingletonOptions>(_singletonConfig), _mockExceptionDispatcher.Object, loggerFactory, new FixedHostIdProvider(TestHostId), _nameResolver); _singletonManager.MinimumLeaseRenewalInterval = TimeSpan.FromMilliseconds(250); } [Fact] public void GetLockDirectory_HandlesMultipleAccounts() { var directory = _core.GetLockDirectory(ConnectionStringNames.Storage); Assert.Equal(_mockBlobDirectory.Uri, directory.Uri); directory = _core.GetLockDirectory(null); Assert.Equal(_mockBlobDirectory.Uri, directory.Uri); directory = _core.GetLockDirectory(Secondary); Assert.Equal(_mockSecondaryBlobDirectory.Uri, directory.Uri); } [Fact] public async Task TryLockAsync_CreatesBlob_WhenItDoesNotExist() { CancellationToken cancellationToken = new CancellationToken(); RequestResult storageResult = new RequestResult { HttpStatusCode = 404 }; StorageException storageException = new StorageException(storageResult, null, null); int count = 0; MockAcquireLeaseAsync(null, () => { if (count++ == 0) { throw storageException; } return TestLeaseId; }); _mockStorageBlob.Setup(p => p.UploadTextAsync(string.Empty, cancellationToken)).Returns(Task.FromResult(true)); //_mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); SingletonAttribute attribute = new SingletonAttribute(); RenewableLockHandle lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.Equal(_mockStorageBlob.Object, innerHandle.Blob); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(1, _mockStorageBlob.Object.Metadata.Keys.Count); Assert.Equal(_mockStorageBlob.Object.Metadata[StorageBaseDistributedLockManager.FunctionInstanceMetadataKey], TestInstanceId); } [Fact] public async Task TryLockAsync_CreatesBlobLease_WithAutoRenewal() { CancellationToken cancellationToken = new CancellationToken(); //_mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); MockAcquireLeaseAsync(null, () => TestLeaseId); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); int renewCount = 0; _mockStorageBlob.Setup(p => p.RenewLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, It.IsAny<CancellationToken>())) .Callback<AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (mockAccessCondition, mockOptions, mockContext, mockCancellationToken) => { renewCount++; }).Returns(Task.FromResult(true)); SingletonAttribute attribute = new SingletonAttribute(); var lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.Equal(_mockStorageBlob.Object, innerHandle.Blob); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(1, _mockStorageBlob.Object.Metadata.Keys.Count); Assert.Equal(_mockStorageBlob.Object.Metadata[StorageBaseDistributedLockManager.FunctionInstanceMetadataKey], TestInstanceId); // wait for enough time that we expect some lease renewals to occur int duration = 2000; int expectedRenewalCount = (int)(duration / (_singletonConfig.LockPeriod.TotalMilliseconds / 2)) - 1; await Task.Delay(duration); Assert.Equal(expectedRenewalCount, renewCount); // now release the lock and verify no more renewals await _singletonManager.ReleaseLockAsync(lockHandle, cancellationToken); // verify the logger TestLogger logger = _loggerProvider.CreatedLoggers.Single() as TestLogger; Assert.Equal(LogCategories.Singleton, logger.Category); var messages = logger.GetLogMessages(); Assert.Equal(2, messages.Count); Assert.NotNull(messages.Single(m => m.Level == Microsoft.Extensions.Logging.LogLevel.Debug && m.FormattedMessage == "Singleton lock acquired (testid)")); Assert.NotNull(messages.Single(m => m.Level == Microsoft.Extensions.Logging.LogLevel.Debug && m.FormattedMessage == "Singleton lock released (testid)")); renewCount = 0; await Task.Delay(1000); Assert.Equal(0, renewCount); _mockStorageBlob.VerifyAll(); } [Fact] public async Task TryLockAsync_WithContention_PollsForLease() { CancellationToken cancellationToken = new CancellationToken(); // _mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); int numRetries = 3; int count = 0; MockAcquireLeaseAsync(null, () => { count++; return count > numRetries ? TestLeaseId : null; }); SingletonAttribute attribute = new SingletonAttribute(); var lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.NotNull(lockHandle); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(numRetries, count - 1); Assert.NotNull(lockHandle.LeaseRenewalTimer); _mockStorageBlob.VerifyAll(); } [Fact] public async Task TryLockAsync_WithContention_NoRetry_DoesNotPollForLease() { CancellationToken cancellationToken = new CancellationToken(); int count = 0; MockAcquireLeaseAsync(null, () => { count++; return null; }); SingletonAttribute attribute = new SingletonAttribute(); SingletonLockHandle lockHandle = await _singletonManager.TryLockInternalAsync(TestLockId, TestInstanceId, attribute, cancellationToken, retry: false); Assert.Null(lockHandle); Assert.Equal(1, count); _mockStorageBlob.VerifyAll(); } // Helper to setup mock since the signatures are very complex private void MockAcquireLeaseAsync(Action fpAction, Func<string> returns) { _mockStorageBlob.Setup( p => p.AcquireLeaseAsync(_singletonConfig.LockPeriod, null, It.IsAny<AccessCondition>(), It.IsAny<BlobRequestOptions>(), It.IsAny<OperationContext>(), It.IsAny<CancellationToken>()) ) .Callback<TimeSpan?, string, AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (mockPeriod, mockLeaseId, accessCondition, blobRequest, opCtx, cancelToken) => { fpAction?.Invoke(); }).Returns(() => { var retResult = returns(); return Task.FromResult<string>(retResult); }); } private void MockFetchAttributesAsync(Action fpAction) { _mockStorageBlob.Setup( p => p.FetchAttributesAsync(It.IsAny<AccessCondition>(), It.IsAny<BlobRequestOptions>(), It.IsAny<OperationContext>(), It.IsAny<CancellationToken>()) ) .Callback<AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (accessCondition, blobRequest, opCtx, cancelToken) => { fpAction?.Invoke(); }).Returns(() => { return Task.CompletedTask; }); } [Fact] public async Task LockAsync_WithContention_AcquisitionTimeoutExpires_Throws() { CancellationToken cancellationToken = new CancellationToken(); int count = 0; MockAcquireLeaseAsync(() => { ++count; }, () => null); SingletonAttribute attribute = new SingletonAttribute(); TimeoutException exception = await Assert.ThrowsAsync<TimeoutException>(async () => await _singletonManager.LockAsync(TestLockId, TestInstanceId, attribute, cancellationToken)); int expectedRetryCount = (int)(_singletonConfig.LockAcquisitionTimeout.TotalMilliseconds / _singletonConfig.LockAcquisitionPollingInterval.TotalMilliseconds); Assert.Equal(expectedRetryCount, count - 1); Assert.Equal("Unable to acquire singleton lock blob lease for blob 'testid' (timeout of 0:00:00.2 exceeded).", exception.Message); _mockStorageBlob.VerifyAll(); } [Fact] public async Task ReleaseLockAsync_StopsRenewalTimerAndReleasesLease() { CancellationToken cancellationToken = new CancellationToken(); Mock<ITaskSeriesTimer> mockRenewalTimer = new Mock<ITaskSeriesTimer>(MockBehavior.Strict); mockRenewalTimer.Setup(p => p.StopAsync(cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); var handle = new RenewableLockHandle( new SingletonLockHandle { Blob = _mockStorageBlob.Object, LeaseId = TestLeaseId }, mockRenewalTimer.Object ); await _singletonManager.ReleaseLockAsync(handle, cancellationToken); mockRenewalTimer.VerifyAll(); } [Fact] public async Task GetLockOwnerAsync_LeaseLocked_ReturnsOwner() { MockFetchAttributesAsync(null); _mockStorageBlob.Object.Properties.SetLeaseState(LeaseState.Leased); SingletonAttribute attribute = new SingletonAttribute(); string lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(null, lockOwner); _mockStorageBlob.Object.Metadata.Add(StorageBaseDistributedLockManager.FunctionInstanceMetadataKey, TestLockId); lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(TestLockId, lockOwner); _mockStorageBlob.VerifyAll(); } [Fact] public async Task GetLockOwnerAsync_LeaseAvailable_ReturnsNull() { MockFetchAttributesAsync(null); _mockStorageBlob.Object.Properties.SetLeaseState(LeaseState.Available); _mockStorageBlob.Object.Properties.SetLeaseStatus(LeaseStatus.Unlocked); SingletonAttribute attribute = new SingletonAttribute(); string lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(null, lockOwner); _mockStorageBlob.VerifyAll(); } [Theory] [InlineData(SingletonScope.Function, null, "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob")] [InlineData(SingletonScope.Function, "", "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob")] [InlineData(SingletonScope.Function, "testscope", "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob.testscope")] [InlineData(SingletonScope.Host, "testscope", "TestHostId/testscope")] public void FormatLockId_ReturnsExpectedValue(SingletonScope scope, string scopeId, string expectedLockId) { MethodInfo methodInfo = this.GetType().GetMethod("TestJob", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(methodInfo, _configuration); string actualLockId = SingletonManager.FormatLockId(descriptor, scope, "TestHostId", scopeId); Assert.Equal(expectedLockId, actualLockId); } [Fact] public void HostId_InvokesHostIdProvider_AndCachesResult() { Mock<IHostIdProvider> mockHostIdProvider = new Mock<IHostIdProvider>(MockBehavior.Strict); mockHostIdProvider.Setup(p => p.GetHostIdAsync(CancellationToken.None)).ReturnsAsync(TestHostId); SingletonManager singletonManager = new SingletonManager(null, new OptionsWrapper<SingletonOptions>(null), null, null, mockHostIdProvider.Object); Assert.Equal(TestHostId, singletonManager.HostId); Assert.Equal(TestHostId, singletonManager.HostId); Assert.Equal(TestHostId, singletonManager.HostId); mockHostIdProvider.Verify(p => p.GetHostIdAsync(It.IsAny<CancellationToken>()), Times.Once); } [Fact] public void GetBoundScopeId_Success_ReturnsExceptedResult() { Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("Region", "testregion"); bindingData.Add("Zone", 1); string result = _singletonManager.GetBoundScopeId(@"{Region}\{Zone}", bindingData); Assert.Equal(@"testregion\1", result); } [Fact] public void GetBoundScopeId_BindingError_Throws() { // Missing binding data for "Zone" Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("Region", "testregion"); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => _singletonManager.GetBoundScopeId(@"{Region}\{Zone}", bindingData)); Assert.Equal("No value for named parameter 'Zone'.", exception.Message); } [Theory] [InlineData("", "")] [InlineData("scope", "scope")] public void GetBoundScopeId_NullBindingDataScenarios_Succeeds(string scope, string expectedResult) { string result = _singletonManager.GetBoundScopeId(scope, null); Assert.Equal(expectedResult, result); } [Theory] [InlineData("", "")] [InlineData("scope", "scope")] [InlineData("scope{P1}", "scopeTest1")] [InlineData("scope:{P1}-{P2}", "scope:Test1-Test2")] [InlineData("%var1%", "Value1")] [InlineData("{P1}%var2%{P2}%var1%", "Test1Value2Test2Value1")] public void GetBoundScopeId_BindingDataScenarios_Succeeds(string scope, string expectedResult) { Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("P1", "Test1"); bindingData.Add("P2", "Test2"); _nameResolver.Names.Add("var1", "Value1"); _nameResolver.Names.Add("var2", "Value2"); string result = _singletonManager.GetBoundScopeId(scope, bindingData); Assert.Equal(expectedResult, result); } [Fact] public void GetFunctionSingletonOrNull_ThrowsOnMultiple() { MethodInfo method = this.GetType().GetMethod("TestJob_MultipleFunctionSingletons", BindingFlags.Static | BindingFlags.NonPublic); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetFunctionSingletonOrNull(new FunctionDescriptor() { SingletonAttributes = method.GetCustomAttributes<SingletonAttribute>() }, isTriggered: true); }); Assert.Equal("Only one SingletonAttribute using mode 'Function' is allowed.", exception.Message); } [Fact] public void GetFunctionSingletonOrNull_ListenerSingletonOnNonTriggeredFunction_Throws() { MethodInfo method = this.GetType().GetMethod("TestJob_ListenerSingleton", BindingFlags.Static | BindingFlags.NonPublic); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetFunctionSingletonOrNull(new FunctionDescriptor() { SingletonAttributes = method.GetCustomAttributes<SingletonAttribute>() }, isTriggered: false); }); Assert.Equal("SingletonAttribute using mode 'Listener' cannot be applied to non-triggered functions.", exception.Message); } [Fact] public void GetListenerSingletonOrNull_ThrowsOnMultiple() { MethodInfo method = this.GetType().GetMethod("TestJob_MultipleListenerSingletons", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method, _configuration); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); }); Assert.Equal("Only one SingletonAttribute using mode 'Listener' is allowed.", exception.Message); } [Fact] public void GetListenerSingletonOrNull_MethodSingletonTakesPrecedence() { MethodInfo method = this.GetType().GetMethod("TestJob_ListenerSingleton", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method, _configuration); SingletonAttribute attribute = SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); Assert.Equal("Function", attribute.ScopeId); } [Fact] public void GetListenerSingletonOrNull_ReturnsListenerClassSingleton() { MethodInfo method = this.GetType().GetMethod("TestJob", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method, _configuration); SingletonAttribute attribute = SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); Assert.Equal("Listener", attribute.ScopeId); } [Theory] [InlineData(SingletonMode.Function)] [InlineData(SingletonMode.Listener)] public void ValidateSingletonAttribute_ScopeIsHost_ScopeIdEmpty_Throws(SingletonMode mode) { SingletonAttribute attribute = new SingletonAttribute(null, SingletonScope.Host); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => { SingletonManager.ValidateSingletonAttribute(attribute, mode); }); Assert.Equal("A ScopeId value must be provided when using scope 'Host'.", exception.Message); } [Fact] public void ValidateSingletonAttribute_ScopeIsHost_ModeIsListener_Throws() { SingletonAttribute attribute = new SingletonAttribute("TestScope", SingletonScope.Host); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => { SingletonManager.ValidateSingletonAttribute(attribute, SingletonMode.Listener); }); Assert.Equal("Scope 'Host' cannot be used when the mode is set to 'Listener'.", exception.Message); } [Fact] public void GetLockPeriod_ReturnsExpectedValue() { SingletonAttribute attribute = new SingletonAttribute { Mode = SingletonMode.Listener }; var config = new SingletonOptions() { LockPeriod = TimeSpan.FromSeconds(16), ListenerLockPeriod = TimeSpan.FromSeconds(17) }; TimeSpan value = SingletonManager.GetLockPeriod(attribute, config); Assert.Equal(config.ListenerLockPeriod, value); attribute.Mode = SingletonMode.Function; value = SingletonManager.GetLockPeriod(attribute, config); Assert.Equal(config.LockPeriod, value); } [Fact] public void GetLockAcquisitionTimeout_ReturnsExpectedValue() { // override via attribute var method = GetType().GetMethod("TestJob_LockAcquisitionTimeoutOverride", BindingFlags.Static | BindingFlags.NonPublic); var attribute = method.GetCustomAttribute<SingletonAttribute>(); var config = new SingletonOptions(); var result = SingletonManager.GetLockAcquisitionTimeout(attribute, config); Assert.Equal(TimeSpan.FromSeconds(5), result); // when not set via attribute, defaults to config value attribute = new SingletonAttribute(); config.LockAcquisitionTimeout = TimeSpan.FromSeconds(3); result = SingletonManager.GetLockAcquisitionTimeout(attribute, config); Assert.Equal(config.LockAcquisitionTimeout, result); } [Theory] [InlineData(true)] [InlineData(false)] public async Task RenewLeaseCommand_ComputesNextDelay_BasedOnRenewalResult(bool renewalSucceeded) { var lockManagerMock = new Mock<IDistributedLockManager>(MockBehavior.Strict); var lockMock = new Mock<IDistributedLock>(MockBehavior.Strict); var delayStrategyMock = new Mock<IDelayStrategy>(MockBehavior.Strict); var cancellationToken = new CancellationToken(); var delay = TimeSpan.FromMilliseconds(33); lockManagerMock.Setup(p => p.RenewAsync(lockMock.Object, cancellationToken)).ReturnsAsync(renewalSucceeded); delayStrategyMock.Setup(p => p.GetNextDelay(renewalSucceeded)).Returns(delay); var command = new SingletonManager.RenewLeaseCommand(lockManagerMock.Object, lockMock.Object, delayStrategyMock.Object); var result = await command.ExecuteAsync(cancellationToken); await result.Wait; lockManagerMock.VerifyAll(); delayStrategyMock.VerifyAll(); } private static void TestJob() { } [Singleton("Function", Mode = SingletonMode.Function, LockAcquisitionTimeout = 5)] private static void TestJob_LockAcquisitionTimeoutOverride() { } [Singleton("Function", Mode = SingletonMode.Listener)] private static void TestJob_ListenerSingleton() { } [Singleton("bar")] [Singleton("foo")] private static void TestJob_MultipleFunctionSingletons() { } [Singleton("bar", Mode = SingletonMode.Listener)] [Singleton("foo", Mode = SingletonMode.Listener)] private static void TestJob_MultipleListenerSingletons() { } [Singleton("Listener", Mode = SingletonMode.Listener)] private class TestListener { } private class TestNameResolver : INameResolver { public TestNameResolver() { Names = new Dictionary<string, string>(); } public Dictionary<string, string> Names { get; private set; } public string Resolve(string name) { if (Names.TryGetValue(name, out string value)) { return value; } throw new NotSupportedException(string.Format("Cannot resolve name: '{0}'", name)); } } } }
45.024927
233
0.654965
[ "MIT" ]
Anduin2017/azure-webjobs-sdk
test/Microsoft.Azure.WebJobs.Host.FunctionalTests/Singleton/SingletonManagerTests.cs
30,709
C#
using Vetuviem.SourceGenerator.Features.Core; namespace ReactiveUI.WinUI3.VetuviemGenerator { /// <summary> /// UI Platform resolver for WinUI3. /// </summary> public sealed class WinUi3PlatformResolver : IPlatformResolver { /// <inheritdoc /> public string[] GetAssemblyNames() { return new[] { "Microsoft.WinUI.dll", }; } /// <inheritdoc /> public string GetBaseUiElement() { return "global::Microsoft.UI.Xaml.UIElement"; } /// <inheritdoc /> public string GetCommandInterface() { return "global::System.Windows.Input.ICommand"; } } }
23.03125
66
0.537313
[ "MIT" ]
dpvreony/Vetuviem
src/ReactiveUI.WinUI3.VetuviemGenerator/WinUi3PlatformResolver.cs
739
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("AverageCharDelimiter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("AverageCharDelimiter")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("9842826d-64f5-40dc-9857-c25d34d2d17b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.540541
84
0.753857
[ "MIT" ]
uagg/SoftwareUniversity
2. Tech Module/Programming Fundamentals/8. Array and list algorithms/Exercise2/REFACTORED/AverageCharDelimiter/AverageCharDelimiter/Properties/AssemblyInfo.cs
1,429
C#
using System.Data.SqlClient; using Microsoft.Extensions.Logging; using Polly; namespace Infrastructure.Types.Abstracts { public abstract class ContextSeedBase<T> { protected bool IsStoricized(string line, int columnNumber) => line.Split(';')[columnNumber] == "S"; } public static class ContextSeedBaseExtension { public static Policy CreatePolicy<T>(this ILogger<T> logger, int retries = 3) { return Policy.Handle<SqlException>(). WaitAndRetry( retryCount: retries, sleepDurationProvider: retry => TimeSpan.FromSeconds(5), onRetry: (exception, timeSpan, retry, ctx) => { logger.LogWarning( exception, "[{prefix}] Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}", nameof(T), exception.GetType().Name, exception.Message, retry, retries ); } ); } } }
34.472222
131
0.486704
[ "MIT" ]
ildoc/Extensions
src/Infrastructure/Types/Abstracts/ContextSeedBase.cs
1,243
C#
using Admin.Core.Common.BaseModel; using FreeSql.DataAnnotations; namespace Admin.Core.Model.Admin { /// <summary> /// 文档 /// </summary> [Table(Name = "ad_document")] [Index("idx_{tablename}_01", nameof(ParentId) + "," + nameof(Label), true)] public class DocumentEntity : EntityFull, ITenant { /// <summary> /// 租户Id /// </summary> [Column(Position = -10, CanUpdate = false)] public long? TenantId { get; set; } /// <summary> /// 父级节点 /// </summary> public long ParentId { get; set; } /// <summary> /// 名称 /// </summary> [Column(StringLength = 50)] public string Label { get; set; } /// <summary> /// 类型 /// </summary> [Column(MapType = typeof(int),CanUpdate = false)] public DocumentType Type { get; set; } /// <summary> /// 命名 /// </summary> [Column(StringLength = 500)] public string Name { get; set; } /// <summary> /// 内容 /// </summary> [Column(StringLength = -1)] public string Content { get; set; } /// <summary> /// Html /// </summary> [Column(StringLength = -1)] public string Html { get; set; } /// <summary> /// 启用 /// </summary> public bool Enabled { get; set; } = true; /// <summary> /// 打开组 /// </summary> public bool? Opened { get; set; } /// <summary> /// 排序 /// </summary> public int? Sort { get; set; } = 0; /// <summary> /// 描述 /// </summary> [Column(StringLength = 100)] public string Description { get; set; } } }
23.394737
79
0.465129
[ "MIT" ]
Jafic/Admin.Core
Admin.Core.Model/Admin/DocumentEntity.cs
1,828
C#
namespace Jekov.Nevix.Common.ViewModels { using Jekov.Nevix.Common.Models; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Text; [DataContract] public class MediaFolderViewModel { public MediaFolderViewModel() { this.Folders = new List<MediaFolderViewModel>(); this.Files = new List<MediaFileViewModel>(); } [Required] [DataMember(Name = "name")] [StringLength(ModelConstants.NameLength)] public string Name { get; set; } [StringLength(ModelConstants.LocationLength)] [DataMember(Name = "location")] public string Location { get; set; } [DataMember(Name = "folders")] public ICollection<MediaFolderViewModel> Folders { get; set; } [DataMember(Name = "files")] public ICollection<MediaFileViewModel> Files { get; set; } public string GetAllLocations() { StringBuilder sb = new StringBuilder(); sb.Append(this.Location); foreach (var file in this.Files) { sb.Append(file.Location); } foreach (var subFolder in this.Folders) { sb.Append(subFolder.GetAllLocations()); } return sb.ToString(); } } }
29.3
70
0.587031
[ "Apache-2.0" ]
antony-jekov/Nevix
Source/Jekov.Nevix/Common/Jekov.Nevix.Common.ViewModels/MediaFolderViewModel.cs
1,467
C#
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { /// <summary> /// Rename file operation /// </summary> public record RenameFile : IFile { /// <summary> /// A rename /// </summary> public ResourceOperationKind Kind { get; } = ResourceOperationKind.Rename; /// <summary> /// The old (existing) location. /// </summary> public DocumentUri OldUri { get; init; } = null!; /// <summary> /// The new location. /// </summary> public DocumentUri NewUri { get; init; } = null!; /// <summary> /// Rename Options. /// </summary> [Optional] public RenameFileOptions? Options { get; init; } /// <summary> /// An optional annotation describing the operation. /// /// @since 3.16.0 /// </summary> [Optional] public ChangeAnnotationIdentifier? AnnotationId { get; init; } } }
26.55
82
0.550847
[ "MIT" ]
SeeminglyScience/csharp-language-server-protocol
src/Protocol/Models/RenameFile.cs
1,062
C#
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. using AppBrix.Data.SqlServer.Impl; using AppBrix.Lifecycle; using AppBrix.Modules; using System; using System.Collections.Generic; namespace AppBrix.Data.SqlServer; /// <summary> /// Module used for regitering a SqlServer provider. /// </summary> public sealed class SqlServerDataModule : ModuleBase { #region Properties /// <summary> /// Gets the types of the modules which are direct dependencies for the current module. /// This is used to determine the order in which the modules are loaded. /// </summary> public override IEnumerable<Type> Dependencies => new[] { typeof(DataModule) }; #endregion #region Public and overriden methods /// <summary> /// Initializes the module. /// Automatically called by <see cref="ModuleBase.Initialize"/> /// </summary> /// <param name="context">The initialization context.</param> protected override void Initialize(IInitializeContext context) { this.App.Container.Register(this); this.configurer.Initialize(context); this.App.Container.Register(this.configurer); } /// <summary> /// Uninitializes the module. /// Automatically called by <see cref="ModuleBase.Uninitialize"/> /// </summary> protected override void Uninitialize() { this.configurer.Uninitialize(); } #endregion #region Private fields and constants private readonly SqlServerDbContextConfigurer configurer = new SqlServerDbContextConfigurer(); #endregion }
32
101
0.703125
[ "MIT" ]
MarinAtanasov/AppBrix
Modules/AppBrix.Data.SqlServer/SqlServerDataModule.cs
1,664
C#
using System.Collections.Generic; namespace AutoFixtureDemo { public class DebugMessageBuffer { public List<string> Messages { get; set; } = new List<string>(); public int MessagesWritten { get; private set; } public void WriteMessages() { foreach (var message in Messages) { // Do something with message... MessagesWritten++; } } } }
21.857143
72
0.542484
[ "MIT" ]
mirusser/Learning-dontNet
src/Testing/AutoFixture/AutoFixtureDemo/DebugMessageBuffer.cs
461
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entity; using DAL; using Service; namespace Repository { public class Logininfor { TokenTableService tos = new TokenTableService(); SAuthoriza saa = new SAuthoriza(); ////验证登录状态 //public Result R_loginstate(string Username, string Token) //{ // Result result = new Result(); // EAuthentication eau = new EAuthentication(); // eau = saa.Authentication(Username, Token); // if (!eau.state) //------------------与token表对比 // { // result.state = -1; // result.msg = "未登录"; // } // else // { // result.state = 1; // result.msg = eau.name; //---------登录的账号 // result.guid = eau.token; //--------登录后的token // } // return result; //} //app传cookie与返回新guid public Result R_Changetoken(string Username, string Token) { Result result = new Result(); EAuthentication eau = new EAuthentication(); eau = saa.Authentication(Username, Token); if (!eau.state) { result.state = -1; result.msg = "未登录"; } else { DateTime now = DateTime.Now; DateTime lasttime = DateTime.Parse(eau.loginTime); int resulttime = (now - lasttime).Days; if (resulttime >= 10) { result.state = 2; result.msg = "用户长时间未登录,请重新登录!"; } else { string newToken = Guid.NewGuid().ToString("N"); if (tos.UpdataToken(eau.name, newToken, now.ToString(), eau.Role, "")) { CRM_User cu = LoginSQL.SearchCrmuser(eau.name); if (cu==null) { result.state = 3; result.msg = "未找到该用户!"; } else { if (cu.T_photoUrl == null) { cu.T_photoUrl = ""; } else { string url = cu.T_photoUrl.ToString(); var ids = url.Split(','); string one = ids[0]; string two = ""; string three = ""; if (ids.Length == 2) { two = ids[1]; } else if (ids.Length == 3) { two = ids[1]; three = ids[2]; } PicturesServiceser pse = new PicturesServiceser(); var picrlist = pse.SelAll(one, two, three); cu.T_photoUrl = picrlist; } result.state = 1; result.guid = newToken; cu.T_pwd = null; result.data = cu; } } } } return result; } } }
33.495575
90
0.34716
[ "Apache-2.0" ]
xnmmp/yulj
Repository/Logininfor.cs
3,891
C#
namespace Automatonymous { /// <summary> /// Used to create the state machine using a container, should be a single-instance registration /// </summary> public interface ISagaStateMachineFactory { SagaStateMachine<T> CreateStateMachine<T>() where T : class, SagaStateMachineInstance; } }
27.666667
100
0.674699
[ "ECL-2.0", "Apache-2.0" ]
ArmyMedalMei/MassTransit
src/MassTransit/Automatonymous/ISagaStateMachineFactory.cs
332
C#
using System; using UnityEngine; namespace SonarSpaceship.Controllers { public class AnimatorParameterControllerScript : MonoBehaviour, IAnimatorParameterController { [SerializeField] private string parameterName = string.Empty; [SerializeField] private Animator parameterAnimator = default; private int parameterNameHash = Animator.StringToHash(string.Empty); private string lastParameterName = string.Empty; public string ParameterName { get => parameterName ?? string.Empty; set => parameterName = value ?? throw new ArgumentNullException(); } public Animator ParameterAnimator { get => parameterAnimator; set { parameterAnimator = value; } } public int ParameterNameHash { get { string parameter_name = ParameterName; if (lastParameterName != parameter_name) { parameterNameHash = Animator.StringToHash(parameter_name); lastParameterName = parameter_name; } return parameterNameHash; } } public void SetBoolean(bool value) { if (parameterAnimator) { parameterAnimator.SetBool(ParameterNameHash, value); } } public void SetInteger(int value) { if (parameterAnimator) { parameterAnimator.SetInteger(ParameterNameHash, value); } } public void SetFloat(float value) { if (parameterAnimator) { parameterAnimator.SetFloat(ParameterNameHash, value); } } public void SetTrigger() { if (parameterAnimator) { parameterAnimator.SetTrigger(ParameterNameHash); } } } }
25.65
96
0.533138
[ "MIT" ]
BigETI/SonarSpaceship
Assets/SonarSpaceship/Scripts/Controllers/AnimatorParameterControllerScript.cs
2,054
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Synapse.V20201201.Inputs { /// <summary> /// The custom setup of running cmdkey commands. /// </summary> public sealed class CmdkeySetupArgs : Pulumi.ResourceArgs { /// <summary> /// The password of data source access. /// </summary> [Input("password", required: true)] public Input<Inputs.SecureStringArgs> Password { get; set; } = null!; /// <summary> /// The server name of data source access. /// </summary> [Input("targetName", required: true)] public Input<object> TargetName { get; set; } = null!; /// <summary> /// The type of custom setup. /// Expected value is 'CmdkeySetup'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// The user name of data source access. /// </summary> [Input("userName", required: true)] public Input<object> UserName { get; set; } = null!; public CmdkeySetupArgs() { } } }
29.666667
81
0.589185
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Synapse/V20201201/Inputs/CmdkeySetupArgs.cs
1,424
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. // Template Source: Templates\CSharp\Requests\EntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The type GraphServiceSubscribedSkusCollectionRequestBuilder. /// </summary> public partial class GraphServiceSubscribedSkusCollectionRequestBuilder : BaseRequestBuilder, IGraphServiceSubscribedSkusCollectionRequestBuilder { /// <summary> /// Constructs a new GraphServiceSubscribedSkusCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public GraphServiceSubscribedSkusCollectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public IGraphServiceSubscribedSkusCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public IGraphServiceSubscribedSkusCollectionRequest Request(IEnumerable<Option> options) { return new GraphServiceSubscribedSkusCollectionRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets an <see cref="ISubscribedSkuRequestBuilder"/> for the specified GraphServiceSubscribedSku. /// </summary> /// <param name="id">The ID for the GraphServiceSubscribedSku.</param> /// <returns>The <see cref="ISubscribedSkuRequestBuilder"/>.</returns> public ISubscribedSkuRequestBuilder this[string id] { get { return new SubscribedSkuRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client); } } } }
39.6
153
0.606449
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/GraphServiceSubscribedSkusCollectionRequestBuilder.cs
2,574
C#
using System; using System.IO; using System.Linq; namespace Day6 { class Program { static void Main(string[] args) { var input = File.ReadAllLines("input.txt"); var sumAny = 0; var sumAll = 0; bool[] questionsAny = null; int[] questionsAll = null; var groupSize = 0; var newGroup = true; foreach(var line in input) { if(string.IsNullOrEmpty(line)) { sumAny += questionsAny.Count(q => q); sumAll += questionsAll.Count(q => q == groupSize); newGroup = true; continue; } if(newGroup) { questionsAny = new bool[26]; questionsAll = new int[26]; groupSize = 0; newGroup = false; } foreach(var q in line) { questionsAny[q - 97] = true; questionsAll[q - 97]++; } groupSize++; } sumAny += questionsAny.Count(q => q); sumAll += questionsAll.Count(q => q == groupSize); Console.WriteLine("Part 1: " + sumAny); Console.WriteLine("Part 2: " + sumAll); } } }
26.754717
70
0.408322
[ "Unlicense" ]
aalear/Advent-of-Code-2020
Day6/Program.cs
1,420
C#
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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 org.camunda.bpm.container.impl.jboss.deployment.processor { using ProcessApplicationAttachments = org.camunda.bpm.container.impl.jboss.deployment.marker.ProcessApplicationAttachments; using ProcessApplicationModuleService = org.camunda.bpm.container.impl.jboss.service.ProcessApplicationModuleService; using ServiceNames = org.camunda.bpm.container.impl.jboss.service.ServiceNames; using AttachmentList = org.jboss.@as.server.deployment.AttachmentList; using Attachments = org.jboss.@as.server.deployment.Attachments; using DeploymentPhaseContext = org.jboss.@as.server.deployment.DeploymentPhaseContext; using DeploymentUnit = org.jboss.@as.server.deployment.DeploymentUnit; using DeploymentUnitProcessingException = org.jboss.@as.server.deployment.DeploymentUnitProcessingException; using DeploymentUnitProcessor = org.jboss.@as.server.deployment.DeploymentUnitProcessor; using ModuleDependency = org.jboss.@as.server.deployment.module.ModuleDependency; using ModuleSpecification = org.jboss.@as.server.deployment.module.ModuleSpecification; using Module = org.jboss.modules.Module; using ModuleIdentifier = org.jboss.modules.ModuleIdentifier; using ModuleLoader = org.jboss.modules.ModuleLoader; using Mode = org.jboss.msc.service.ServiceController.Mode; using ServiceName = org.jboss.msc.service.ServiceName; /// <summary> /// <para>This Processor creates implicit module dependencies for process applications</para> /// /// <para>Concretely speaking, this processor adds a module dependency from the process /// application module (deployment unit) to the process engine module (and other camunda libraries /// which are useful for process apps).</para> /// /// @author Daniel Meyer /// /// </summary> public class ModuleDependencyProcessor : DeploymentUnitProcessor { public const int PRIORITY = 0x2300; public static ModuleIdentifier MODULE_IDENTIFYER_PROCESS_ENGINE = ModuleIdentifier.create("org.camunda.bpm.camunda-engine"); public static ModuleIdentifier MODULE_IDENTIFYER_XML_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-xml-model"); public static ModuleIdentifier MODULE_IDENTIFYER_BPMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-bpmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_CMMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-cmmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_DMN_MODEL = ModuleIdentifier.create("org.camunda.bpm.model.camunda-dmn-model"); public static ModuleIdentifier MODULE_IDENTIFYER_SPIN = ModuleIdentifier.create("org.camunda.spin.camunda-spin-core"); public static ModuleIdentifier MODULE_IDENTIFYER_CONNECT = ModuleIdentifier.create("org.camunda.connect.camunda-connect-core"); public static ModuleIdentifier MODULE_IDENTIFYER_ENGINE_DMN = ModuleIdentifier.create("org.camunda.bpm.dmn.camunda-engine-dmn"); //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void deploy(org.jboss.as.server.deployment.DeploymentPhaseContext phaseContext) throws org.jboss.as.server.deployment.DeploymentUnitProcessingException public virtual void deploy(DeploymentPhaseContext phaseContext) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.jboss.as.server.deployment.DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); DeploymentUnit deploymentUnit = phaseContext.DeploymentUnit; if (deploymentUnit.Parent == null) { //The deployment unit has no parent so it is a simple war or an ear. ModuleLoader moduleLoader = Module.BootModuleLoader; //If it is a simpleWar and marked with process application we have to add the dependency bool isProcessApplicationWarOrEar = ProcessApplicationAttachments.isProcessApplication(deploymentUnit); AttachmentList<DeploymentUnit> subdeployments = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS); //Is the list of sub deployments empty the deployment unit is a war file. //In cases of war files we have nothing todo. if (subdeployments != null) { //The deployment unit contains sub deployments which means the deployment unit is an ear. //We have to check whether sub deployments are process applications or not. bool subDeploymentIsProcessApplication = false; foreach (DeploymentUnit subDeploymentUnit in subdeployments) { if (ProcessApplicationAttachments.isProcessApplication(subDeploymentUnit)) { subDeploymentIsProcessApplication = true; break; } } //If one sub deployment is a process application then we add to all the dependency //Also we have to add the dependency to the current deployment unit which is an ear if (subDeploymentIsProcessApplication) { foreach (DeploymentUnit subDeploymentUnit in subdeployments) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.jboss.as.server.deployment.module.ModuleSpecification moduleSpecification = subDeploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE_SPECIFICATION); ModuleSpecification moduleSpecification = subDeploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); addSystemDependencies(moduleLoader, moduleSpecification); } //An ear is not marked as process application but also needs the dependency isProcessApplicationWarOrEar = true; } } if (isProcessApplicationWarOrEar) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.jboss.as.server.deployment.module.ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE_SPECIFICATION); ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); addSystemDependencies(moduleLoader, moduleSpecification); } } // install the pa-module service ModuleIdentifier identifyer = deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER); string moduleName = identifyer.ToString(); ProcessApplicationModuleService processApplicationModuleService = new ProcessApplicationModuleService(); ServiceName serviceName = ServiceNames.forProcessApplicationModuleService(moduleName); phaseContext.ServiceTarget.addService(serviceName, processApplicationModuleService).addDependency(phaseContext.PhaseServiceName).setInitialMode(Mode.ACTIVE).install(); } //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: private void addSystemDependencies(org.jboss.modules.ModuleLoader moduleLoader, final org.jboss.as.server.deployment.module.ModuleSpecification moduleSpecification) private void addSystemDependencies(ModuleLoader moduleLoader, ModuleSpecification moduleSpecification) { addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_PROCESS_ENGINE); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_XML_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_BPMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_CMMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_DMN_MODEL); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_SPIN); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_CONNECT); addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFYER_ENGINE_DMN); } //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: private void addSystemDependency(org.jboss.modules.ModuleLoader moduleLoader, final org.jboss.as.server.deployment.module.ModuleSpecification moduleSpecification, org.jboss.modules.ModuleIdentifier dependency) private void addSystemDependency(ModuleLoader moduleLoader, ModuleSpecification moduleSpecification, ModuleIdentifier dependency) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, dependency, false, false, false, false)); } public virtual void undeploy(DeploymentUnit context) { } } }
57.713376
226
0.809072
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpm-platform-net/distro/jbossas7/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/processor/ModuleDependencyProcessor.cs
9,063
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.EventLog; namespace WebApplication7 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.ClearProviders(); logging.AddConsole(); logging.AddEventLog(); logging.AddFilter<EventLogLoggerProvider>((categoryName, logLevel) => { return categoryName.Equals("WebApplication7.LoggingService"); }); }) .ConfigureServices(services => { services.AddHostedService<LoggingService>(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
32.372093
89
0.574713
[ "MIT" ]
shirhatti/EventLogCrashRepro
WebApplication7/Program.cs
1,392
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Xml; using System.Xml.XPath; using System.ComponentModel; namespace System.Xml.Xsl.Runtime { /// <summary> /// Iterators that use containment to control a nested iterator return one of the following values from MoveNext(). /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public enum IteratorResult { NoMoreNodes, // Iteration is complete; there are no more nodes NeedInputNode, // The next node needs to be fetched from the contained iterator before iteration can continue HaveCurrentNode, // This iterator's Current property is set to the next node in the iteration }; /// <summary> /// Tokenize a string containing IDREF values and deref the values in order to get a list of ID elements. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct IdIterator { private XPathNavigator _navCurrent; private string[] _idrefs; private int _idx; public void Create(XPathNavigator context, string value) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _idrefs = XmlConvert.SplitString(value); _idx = -1; } public bool MoveNext() { do { _idx++; if (_idx >= _idrefs.Length) return false; } while (!_navCurrent.MoveToId(_idrefs[_idx])); return true; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } }
31.412698
130
0.609399
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlIterators.cs
1,979
C#
using System.Reflection; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("HelpAdvisor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HelpAdvisor")] [assembly: AssemblyCopyright("Copyright © Fedja Adam 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("575574a5-d37e-4c91-bece-381e07a1d350")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("2.0.4")] [assembly: AssemblyVersion("2.0.4")]
39.194444
106
0.759745
[ "MIT" ]
truong225/CSharp_Engine
Source/Plugins/EditorModules/HelpAdvisor/Properties/AssemblyInfo.cs
1,427
C#
/* ------------------------------------------------------------------------- * thZero.NetCore.Library.Asp Copyright (C) 2016-2021 thZero.com <development [at] thzero [dot] com> 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; namespace thZero.AspNetCore.Mvc.Views.Models { public interface IViewModel { } public interface IViewModel<T> : IViewModel { #region Properties T Id { get; set; } #endregion } }
30.088235
79
0.621701
[ "ECL-2.0", "Apache-2.0" ]
thzero/thZero.NetCore.Library.Asp
Views/Models/IViewModel.cs
1,025
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SimpleCustomFrameApp { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
15.827586
42
0.527233
[ "MIT" ]
AlexanderIbraimov/CustomFrame
SimpleApp/SimpleCustomFrameApp/SimpleCustomFrameApp/App.xaml.cs
461
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Sample.Automation.Scheduling.Entities { using System; using System.Collections.Generic; public partial class SchedulingHandle { public int Id { get; set; } public long ScheduleID { get; set; } public long DispatchID { get; set; } } }
32.909091
84
0.527624
[ "Apache-2.0" ]
leo-leong/wwt-scheduler
Microsoft.Sample.Automation/Scheduling/Entities/SchedulingHandle.cs
724
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using Player.Controller; using Timer = System.Windows.Forms.Timer; using Microsoft.Win32; namespace Player { public partial class Form1 : Form { [DllImport("user32.dll")] public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo); public const int KEYEVENTF_EXTENTEDKEY = 1; public const int KEYEVENTF_KEYUP = 0; public const int VK_MEDIA_NEXT_TRACK = 0xB0;// code to jump to next track public const int VK_MEDIA_PLAY_PAUSE = 0xB3;// code to play or pause a song public const int VK_MEDIA_PREV_TRACK = 0xB1;// code to jump to prev track private Controller.LowLevelKeyboardListener listener; private bool crtlPressed = false; private Timer timer = new Timer { Interval = 2000 }; public Form1() { InitializeComponent(); RegistryKey registry = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); registry.SetValue("Player", Application.ExecutablePath.ToString()); this.ShowInTaskbar = false; notifyIcon1.Icon = SystemIcons.Application; notifyIcon1.Visible = true; this.WindowState = FormWindowState.Minimized; if (this.WindowState == FormWindowState.Normal) { } } private void playPause() { keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } private void prevTrack() { keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } private void nextTrack() { keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero); } private void Form1_Load(object sender, EventArgs e) { listener = new Controller.LowLevelKeyboardListener(); listener.OnKeyPressed += listener_OnKeyPressed; listener.HookKeyboard(); } private void listener_OnKeyPressed(object sender, KeyPressedArgs e) { string key = e.KeyPressed.ToString(); timer.Enabled = true; timer.Tick += new System.EventHandler(OnTimerEvent); if (key.Equals("LeftCtrl")) { crtlPressed = true; } Console.Write(key); if (crtlPressed) { if (key.Equals("Up")) { playPause(); crtlPressed = false; } else if (key.Equals("Left")) { prevTrack(); crtlPressed = false; } else if (key.Equals("Right")) { nextTrack(); crtlPressed = false; } } } private void OnTimerEvent(object sender, EventArgs e) { if (crtlPressed) { crtlPressed = false; } timer.Enabled = false; } private void button3_Click(object sender, EventArgs e) { prevTrack(); } private void button1_Click(object sender, EventArgs e) { playPause(); } private void button2_Click(object sender, EventArgs e) { nextTrack(); } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.WindowState = FormWindowState.Normal; if (this.WindowState == FormWindowState.Normal) { this.ShowInTaskbar = true; notifyIcon1.Icon = SystemIcons.Application; notifyIcon1.Visible = false; this.WindowState = FormWindowState.Normal; } } } }
27.713415
127
0.522332
[ "MIT" ]
efedeniz/Player
Player/Player/Form1.cs
4,547
C#
using System; using JankyUI.Attributes; using JankyUI.Nodes.Binding; using JankyUI.Enums; using JankyUI.EventArgs; using UnityEngine; namespace JankyUI.Nodes { [JankyTag("Scrollbar")] [JankyProperty("type", nameof(Type))] [JankyProperty("size", nameof(Size))] [JankyProperty("value", nameof(Value))] [JankyProperty("min-value", nameof(MinValue))] [JankyProperty("max-value", nameof(MaxValue))] [JankyProperty("on-change", nameof(OnChange))] internal class ScrollBarNode : LayoutNode { public JankyMethod<Action<JankyEventArgs<float>>> OnChange; public JankyProperty<ScrollBarTypeEnum> Type; public JankyProperty<float> Value; public JankyProperty<float> Size; public JankyProperty<float> MinValue; public JankyProperty<float> MaxValue; protected override void OnGUI() { #if MOCK Console.WriteLine("ScrollBar: {0}", Value); #else float oldValue = Value; float newValue = oldValue; switch (Type.Value) { case ScrollBarTypeEnum.Horizontal: newValue = GUILayout.HorizontalScrollbar(oldValue, Size, MinValue, MaxValue, GetLayoutOptions()); break; case ScrollBarTypeEnum.Vertical: newValue = GUILayout.VerticalScrollbar(oldValue, Size, MinValue, MaxValue, GetLayoutOptions()); break; } Value.Value = newValue; if (Value.LastSetResult != DataOperationResultEnum.Unchanged) OnChange.Invoke(new JankyEventArgs<float>(Context.WindowID, Name, oldValue, newValue)); #endif } } }
32.264151
117
0.630994
[ "MIT" ]
usagirei/JankyUI
JankyUI/Nodes/Widgets/ScrollBarNode.cs
1,712
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 iotevents-data-2018-10-23.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Net; using Amazon.IoTEventsData.Model; using Amazon.IoTEventsData.Model.Internal.MarshallTransformations; using Amazon.IoTEventsData.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.IoTEventsData { /// <summary> /// Implementation for accessing IoTEventsData /// /// AWS IoT Events monitors your equipment or device fleets for failures or changes in /// operation, and triggers actions when such events occur. AWS IoT Events Data API commands /// enable you to send inputs to detectors, list detectors, and view or update a detector's /// status. /// </summary> #if NETSTANDARD13 [Obsolete("Support for .NET Standard 1.3 is in maintenance mode and will only receive critical bug fixes and security patches. Visit https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/migration-from-net-standard-1-3.html for further details.")] #endif public partial class AmazonIoTEventsDataClient : AmazonServiceClient, IAmazonIoTEventsData { private static IServiceMetadata serviceMetadata = new AmazonIoTEventsDataMetadata(); #region Constructors /// <summary> /// Constructs AmazonIoTEventsDataClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonIoTEventsDataClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTEventsDataConfig()) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonIoTEventsDataClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonIoTEventsDataConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonIoTEventsDataClient Configuration Object</param> public AmazonIoTEventsDataClient(AmazonIoTEventsDataConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonIoTEventsDataClient(AWSCredentials credentials) : this(credentials, new AmazonIoTEventsDataConfig()) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonIoTEventsDataClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonIoTEventsDataConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Credentials and an /// AmazonIoTEventsDataClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonIoTEventsDataClient Configuration Object</param> public AmazonIoTEventsDataClient(AWSCredentials credentials, AmazonIoTEventsDataConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTEventsDataConfig()) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonIoTEventsDataConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID, AWS Secret Key and an /// AmazonIoTEventsDataClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonIoTEventsDataClient Configuration Object</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonIoTEventsDataConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTEventsDataConfig()) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonIoTEventsDataConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonIoTEventsDataClient with AWS Access Key ID, AWS Secret Key and an /// AmazonIoTEventsDataClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonIoTEventsDataClient Configuration Object</param> public AmazonIoTEventsDataClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonIoTEventsDataConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchPutMessage internal virtual BatchPutMessageResponse BatchPutMessage(BatchPutMessageRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchPutMessageRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchPutMessageResponseUnmarshaller.Instance; return Invoke<BatchPutMessageResponse>(request, options); } /// <summary> /// Sends a set of messages to the AWS IoT Events system. Each message payload is transformed /// into the input you specify (<code>"inputName"</code>) and ingested into any detectors /// that monitor that input. If multiple messages are sent, the order in which the messages /// are processed isn't guaranteed. To guarantee ordering, you must send messages one /// at a time and wait for a successful response. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchPutMessage service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchPutMessage service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/BatchPutMessage">REST API Reference for BatchPutMessage Operation</seealso> public virtual Task<BatchPutMessageResponse> BatchPutMessageAsync(BatchPutMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchPutMessageRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchPutMessageResponseUnmarshaller.Instance; return InvokeAsync<BatchPutMessageResponse>(request, options, cancellationToken); } #endregion #region BatchUpdateDetector internal virtual BatchUpdateDetectorResponse BatchUpdateDetector(BatchUpdateDetectorRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpdateDetectorRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpdateDetectorResponseUnmarshaller.Instance; return Invoke<BatchUpdateDetectorResponse>(request, options); } /// <summary> /// Updates the state, variable values, and timer settings of one or more detectors (instances) /// of a specified detector model. /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchUpdateDetector service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchUpdateDetector service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/BatchUpdateDetector">REST API Reference for BatchUpdateDetector Operation</seealso> public virtual Task<BatchUpdateDetectorResponse> BatchUpdateDetectorAsync(BatchUpdateDetectorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = BatchUpdateDetectorRequestMarshaller.Instance; options.ResponseUnmarshaller = BatchUpdateDetectorResponseUnmarshaller.Instance; return InvokeAsync<BatchUpdateDetectorResponse>(request, options, cancellationToken); } #endregion #region DescribeDetector internal virtual DescribeDetectorResponse DescribeDetector(DescribeDetectorRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeDetectorRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeDetectorResponseUnmarshaller.Instance; return Invoke<DescribeDetectorResponse>(request, options); } /// <summary> /// Returns information about the specified detector (instance). /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDetector service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDetector service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ResourceNotFoundException"> /// The resource was not found. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/DescribeDetector">REST API Reference for DescribeDetector Operation</seealso> public virtual Task<DescribeDetectorResponse> DescribeDetectorAsync(DescribeDetectorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeDetectorRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeDetectorResponseUnmarshaller.Instance; return InvokeAsync<DescribeDetectorResponse>(request, options, cancellationToken); } #endregion #region ListDetectors internal virtual ListDetectorsResponse ListDetectors(ListDetectorsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListDetectorsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDetectorsResponseUnmarshaller.Instance; return Invoke<ListDetectorsResponse>(request, options); } /// <summary> /// Lists detectors (the instances of a detector model). /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDetectors service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListDetectors service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occured. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ResourceNotFoundException"> /// The resource was not found. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/ListDetectors">REST API Reference for ListDetectors Operation</seealso> public virtual Task<ListDetectorsResponse> ListDetectorsAsync(ListDetectorsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListDetectorsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListDetectorsResponseUnmarshaller.Instance; return InvokeAsync<ListDetectorsResponse>(request, options, cancellationToken); } #endregion } }
47.285393
256
0.653883
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTEventsData/Generated/_netstandard/AmazonIoTEventsDataClient.cs
21,042
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Logging; using Resources = Microsoft.AspNetCore.Mvc.Core.Resources; namespace Microsoft.AspNetCore.Mvc.Infrastructure { internal class ControllerActionInvoker : ResourceInvoker, IActionInvoker { private readonly ControllerActionInvokerCacheEntry _cacheEntry; private readonly ControllerContext _controllerContext; private Dictionary<string, object> _arguments; private ActionExecutingContextSealed _actionExecutingContext; private ActionExecutedContextSealed _actionExecutedContext; internal ControllerActionInvoker( ILogger logger, DiagnosticListener diagnosticListener, IActionContextAccessor actionContextAccessor, IActionResultTypeMapper mapper, ControllerContext controllerContext, ControllerActionInvokerCacheEntry cacheEntry, IFilterMetadata[] filters) : base(diagnosticListener, logger, actionContextAccessor, mapper, controllerContext, filters, controllerContext.ValueProviderFactories) { if (cacheEntry == null) { throw new ArgumentNullException(nameof(cacheEntry)); } _cacheEntry = cacheEntry; _controllerContext = controllerContext; } // Internal for testing internal ControllerContext ControllerContext => _controllerContext; protected override void ReleaseResources() { if (_instance != null && _cacheEntry.ControllerReleaser != null) { _cacheEntry.ControllerReleaser(_controllerContext, _instance); } } private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) { switch (next) { case State.ActionBegin: { var controllerContext = _controllerContext; _cursor.Reset(); _logger.ExecutingControllerFactory(controllerContext); _instance = _cacheEntry.ControllerFactory(controllerContext); _logger.ExecutedControllerFactory(controllerContext); _arguments = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); var task = BindArgumentsAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.ActionNext; return task; } goto case State.ActionNext; } case State.ActionNext: { var current = _cursor.GetNextFilter<IActionFilter, IAsyncActionFilter>(); if (current.FilterAsync != null) { if (_actionExecutingContext == null) { _actionExecutingContext = new ActionExecutingContextSealed(_controllerContext, _filters, _arguments, _instance); } else if (_actionExecutedContext?.Result != null) { _actionExecutingContext.Result = _actionExecutedContext.Result; } state = current.FilterAsync; goto case State.ActionAsyncBegin; } else if (current.Filter != null) { if (_actionExecutingContext == null) { _actionExecutingContext = new ActionExecutingContextSealed(_controllerContext, _filters, _arguments, _instance); } else if (_actionExecutedContext?.Result != null) { _actionExecutingContext.Result = _actionExecutedContext.Result; } state = current.Filter; goto case State.ActionSyncBegin; } else { goto case State.ActionInside; } } case State.ActionAsyncBegin: { Debug.Assert(state != null); Debug.Assert(_actionExecutingContext != null); var filter = (IAsyncActionFilter)state; var actionExecutingContext = _actionExecutingContext; _diagnosticListener.BeforeOnActionExecution(actionExecutingContext, filter); _logger.BeforeExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IAsyncActionFilter.OnActionExecutionAsync), filter); var task = filter.OnActionExecutionAsync(actionExecutingContext, InvokeNextActionFilterAwaitedAsync); if (task.Status != TaskStatus.RanToCompletion) { next = State.ActionAsyncEnd; return task; } goto case State.ActionAsyncEnd; } case State.ActionAsyncEnd: { Debug.Assert(state != null); Debug.Assert(_actionExecutingContext != null); var filter = (IAsyncActionFilter)state; if (_actionExecutedContext == null) { // If we get here then the filter didn't call 'next' indicating a short circuit. _logger.ActionFilterShortCircuited(filter); _actionExecutedContext = new ActionExecutedContextSealed( _controllerContext, _filters, _instance) { Canceled = true, Result = _actionExecutingContext.Result, }; } _diagnosticListener.AfterOnActionExecution(_actionExecutedContext, filter); _logger.AfterExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IAsyncActionFilter.OnActionExecutionAsync), filter); goto case State.ActionEnd; } case State.ActionSyncBegin: { Debug.Assert(state != null); Debug.Assert(_actionExecutingContext != null); var filter = (IActionFilter)state; var actionExecutingContext = _actionExecutingContext; _diagnosticListener.BeforeOnActionExecuting(actionExecutingContext, filter); _logger.BeforeExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IActionFilter.OnActionExecuting), filter); filter.OnActionExecuting(actionExecutingContext); _diagnosticListener.AfterOnActionExecuting(actionExecutingContext, filter); _logger.AfterExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IActionFilter.OnActionExecuting), filter); if (actionExecutingContext.Result != null) { // Short-circuited by setting a result. _logger.ActionFilterShortCircuited(filter); _actionExecutedContext = new ActionExecutedContextSealed( _actionExecutingContext, _filters, _instance) { Canceled = true, Result = _actionExecutingContext.Result, }; goto case State.ActionEnd; } var task = InvokeNextActionFilterAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.ActionSyncEnd; return task; } goto case State.ActionSyncEnd; } case State.ActionSyncEnd: { Debug.Assert(state != null); Debug.Assert(_actionExecutingContext != null); Debug.Assert(_actionExecutedContext != null); var filter = (IActionFilter)state; var actionExecutedContext = _actionExecutedContext; _diagnosticListener.BeforeOnActionExecuted(actionExecutedContext, filter); _logger.BeforeExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IActionFilter.OnActionExecuted), filter); filter.OnActionExecuted(actionExecutedContext); _diagnosticListener.AfterOnActionExecuted(actionExecutedContext, filter); _logger.AfterExecutingMethodOnFilter( MvcCoreLoggerExtensions.ActionFilter, nameof(IActionFilter.OnActionExecuted), filter); goto case State.ActionEnd; } case State.ActionInside: { var task = InvokeActionMethodAsync(); if (task.Status != TaskStatus.RanToCompletion) { next = State.ActionEnd; return task; } goto case State.ActionEnd; } case State.ActionEnd: { if (scope == Scope.Action) { if (_actionExecutedContext == null) { _actionExecutedContext = new ActionExecutedContextSealed(_controllerContext, _filters, _instance) { Result = _result, }; } isCompleted = true; return Task.CompletedTask; } var actionExecutedContext = _actionExecutedContext; Rethrow(actionExecutedContext); if (actionExecutedContext != null) { _result = actionExecutedContext.Result; } isCompleted = true; return Task.CompletedTask; } default: throw new InvalidOperationException(); } } private Task InvokeNextActionFilterAsync() { try { var next = State.ActionNext; var state = (object)null; var scope = Scope.Action; var isCompleted = false; while (!isCompleted) { var lastTask = Next(ref next, ref scope, ref state, ref isCompleted); if (!lastTask.IsCompletedSuccessfully) { return Awaited(this, lastTask, next, scope, state, isCompleted); } } } catch (Exception exception) { _actionExecutedContext = new ActionExecutedContextSealed(_controllerContext, _filters, _instance) { ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception), }; } Debug.Assert(_actionExecutedContext != null); return Task.CompletedTask; static async Task Awaited(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) { try { await lastTask; while (!isCompleted) { await invoker.Next(ref next, ref scope, ref state, ref isCompleted); } } catch (Exception exception) { invoker._actionExecutedContext = new ActionExecutedContextSealed(invoker._controllerContext, invoker._filters, invoker._instance) { ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception), }; } Debug.Assert(invoker._actionExecutedContext != null); } } private Task<ActionExecutedContext> InvokeNextActionFilterAwaitedAsync() { Debug.Assert(_actionExecutingContext != null); if (_actionExecutingContext.Result != null) { // If we get here, it means that an async filter set a result AND called next(). This is forbidden. return Throw(); } var task = InvokeNextActionFilterAsync(); if (!task.IsCompletedSuccessfully) { return Awaited(this, task); } Debug.Assert(_actionExecutedContext != null); return Task.FromResult<ActionExecutedContext>(_actionExecutedContext); static async Task<ActionExecutedContext> Awaited(ControllerActionInvoker invoker, Task task) { await task; Debug.Assert(invoker._actionExecutedContext != null); return invoker._actionExecutedContext; } #pragma warning disable CS1998 static async Task<ActionExecutedContext> Throw() { var message = Resources.FormatAsyncActionFilter_InvalidShortCircuit( typeof(IAsyncActionFilter).Name, nameof(ActionExecutingContext.Result), typeof(ActionExecutingContext).Name, typeof(ActionExecutionDelegate).Name); throw new InvalidOperationException(message); } #pragma warning restore CS1998 } private Task InvokeActionMethodAsync() { if (_diagnosticListener.IsEnabled() || _logger.IsEnabled(LogLevel.Trace)) { return Logged(this); } var objectMethodExecutor = _cacheEntry.ObjectMethodExecutor; var actionMethodExecutor = _cacheEntry.ActionMethodExecutor; var orderedArguments = PrepareArguments(_arguments, objectMethodExecutor); var actionResultValueTask = actionMethodExecutor.Execute(_mapper, objectMethodExecutor, _instance, orderedArguments); if (actionResultValueTask.IsCompletedSuccessfully) { _result = actionResultValueTask.Result; } else { return Awaited(this, actionResultValueTask); } return Task.CompletedTask; static async Task Awaited(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask) { invoker._result = await actionResultValueTask; } static async Task Logged(ControllerActionInvoker invoker) { var controllerContext = invoker._controllerContext; var objectMethodExecutor = invoker._cacheEntry.ObjectMethodExecutor; var controller = invoker._instance; var arguments = invoker._arguments; var actionMethodExecutor = invoker._cacheEntry.ActionMethodExecutor; var orderedArguments = PrepareArguments(arguments, objectMethodExecutor); var diagnosticListener = invoker._diagnosticListener; var logger = invoker._logger; IActionResult result = null; try { diagnosticListener.BeforeControllerActionMethod( controllerContext, arguments, controller); logger.ActionMethodExecuting(controllerContext, orderedArguments); var stopwatch = ValueStopwatch.StartNew(); var actionResultValueTask = actionMethodExecutor.Execute(invoker._mapper, objectMethodExecutor, controller, orderedArguments); if (actionResultValueTask.IsCompletedSuccessfully) { result = actionResultValueTask.Result; } else { result = await actionResultValueTask; } invoker._result = result; logger.ActionMethodExecuted(controllerContext, result, stopwatch.GetElapsedTime()); } finally { diagnosticListener.AfterControllerActionMethod( controllerContext, arguments, controllerContext, result); } } } /// <remarks><see cref="ResourceInvoker.InvokeFilterPipelineAsync"/> for details on what the /// variables in this method represent.</remarks> protected override Task InvokeInnerFilterAsync() { try { var next = State.ActionBegin; var scope = Scope.Invoker; var state = (object)null; var isCompleted = false; while (!isCompleted) { var lastTask = Next(ref next, ref scope, ref state, ref isCompleted); if (!lastTask.IsCompletedSuccessfully) { return Awaited(this, lastTask, next, scope, state, isCompleted); } } return Task.CompletedTask; } catch (Exception ex) { // Wrap non task-wrapped exceptions in a Task, // as this isn't done automatically since the method is not async. return Task.FromException(ex); } static async Task Awaited(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) { await lastTask; while (!isCompleted) { await invoker.Next(ref next, ref scope, ref state, ref isCompleted); } } } private static void Rethrow(ActionExecutedContextSealed context) { if (context == null) { return; } if (context.ExceptionHandled) { return; } if (context.ExceptionDispatchInfo != null) { context.ExceptionDispatchInfo.Throw(); } if (context.Exception != null) { throw context.Exception; } } private Task BindArgumentsAsync() { // Perf: Avoid allocating async state machines where possible. We only need the state // machine if you need to bind properties or arguments. var actionDescriptor = _controllerContext.ActionDescriptor; if (actionDescriptor.BoundProperties.Count == 0 && actionDescriptor.Parameters.Count == 0) { return Task.CompletedTask; } Debug.Assert(_cacheEntry.ControllerBinderDelegate != null); return _cacheEntry.ControllerBinderDelegate(_controllerContext, _instance, _arguments); } private static object[] PrepareArguments( IDictionary<string, object> actionParameters, ObjectMethodExecutor actionMethodExecutor) { var declaredParameterInfos = actionMethodExecutor.MethodParameters; var count = declaredParameterInfos.Length; if (count == 0) { return null; } var arguments = new object[count]; for (var index = 0; index < count; index++) { var parameterInfo = declaredParameterInfos[index]; if (!actionParameters.TryGetValue(parameterInfo.Name, out var value)) { value = actionMethodExecutor.GetDefaultValueForParameter(index); } arguments[index] = value; } return arguments; } private enum Scope { Invoker, Action, } private enum State { ActionBegin, ActionNext, ActionAsyncBegin, ActionAsyncEnd, ActionSyncBegin, ActionSyncEnd, ActionInside, ActionEnd, } private sealed class ActionExecutingContextSealed : ActionExecutingContext { public ActionExecutingContextSealed(ActionContext actionContext, IList<IFilterMetadata> filters, IDictionary<string, object> actionArguments, object controller) : base(actionContext, filters, actionArguments, controller) { } } private sealed class ActionExecutedContextSealed : ActionExecutedContext { public ActionExecutedContextSealed(ActionContext actionContext, IList<IFilterMetadata> filters, object controller) : base(actionContext, filters, controller) { } } } }
39.420875
236
0.508968
[ "Apache-2.0" ]
ilonze/aspnetcore
src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs
23,416
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 Cake.Core; namespace Cake.Frosting.Tests; public sealed class FakeLifetime : FrostingLifetime { public int SetupCount { get; set; } public int TeardownCount { get; set; } public override void Setup(ICakeContext context) { SetupCount++; } public override void Teardown(ICakeContext context, ITeardownContext info) { TeardownCount++; } }
26
78
0.707358
[ "MIT" ]
ecampidoglio/cake
src/Cake.Frosting.Tests/Fakes/FakeLifetime.cs
600
C#
using JRSoftware.Clientes.Core.Abstracao; using JRSoftware.Clientes.Core.Dominio; using JRSoftware.Clientes.Core.Repositorio.DAL; using System; using System.Collections.Generic; using System.Linq; namespace JRSoftware.Clientes.Core.Repositorio { public class EnderecoRepository { public IConnectionManager ConnectionManager { get; set; } private EnderecoDAL _enderecoDAL; private CidadeDAL _cidadeDAL; private UFDAL _ufDAL; public EnderecoDAL EnderecoDAL => _enderecoDAL ?? (_enderecoDAL = new EnderecoDAL() { ConnectionManager = ConnectionManager }); public CidadeDAL CidadeDAL => _cidadeDAL ?? (_cidadeDAL = new CidadeDAL() { ConnectionManager = ConnectionManager }); public UFDAL UFDAL => _ufDAL ?? (_ufDAL = new UFDAL() { ConnectionManager = ConnectionManager }); public void PreencherEnderecos(IEnumerable<Cliente> clientes) { foreach (var cliente in clientes) PreencherEnderecos(cliente); } private void PreencherEnderecos(Cliente cliente) { var enderecos = ObterPorClienteId(cliente.Id); PreencherCidade(enderecos); cliente.AdicionarEnderecos(enderecos); } public IEnumerable<Endereco> ObterPorClienteId(long clienteId) { return EnderecoDAL.ObterPorClienteId(clienteId); } public void Incluir(IEnumerable<Endereco> enderecos) { foreach (var endereco in enderecos) Incluir(endereco); } public void Incluir(Endereco endereco) { endereco.Validar(true); PreencherCidade(endereco); EnderecoDAL.Incluir(endereco); } public void Incluir(Cidade cidade) { cidade.Validar(true); CidadeDAL.Incluir(cidade); } public void Incluir(UF uf) { uf.Validar(true); UFDAL.Incluir(uf); } public void Excluir(IEnumerable<Endereco> enderecos) { foreach (var endereco in enderecos) Excluir(endereco); } public void Excluir(Endereco endereco) { EnderecoDAL.Excluir(endereco); } public void Excluir(Cidade cidade) { CidadeDAL.Excluir(cidade); } public void Excluir(UF uf) { UFDAL.Excluir(uf); } private void PreencherCidade(IEnumerable<Endereco> enderecos) { foreach (var endereco in enderecos) PreencherCidade(endereco); } private void PreencherCidade(Endereco endereco) { var cidades = CidadeDAL.ObterPor(endereco.Cidade); if (cidades.Any()) endereco.Cidade = cidades.FirstOrDefault(); PreencherUF(endereco.Cidade); if (!cidades.Any()) Incluir(endereco.Cidade); } private void PreencherUF(Cidade cidade) { var ufs = UFDAL.ObterPor(cidade.UF); if (ufs.Any()) cidade.UF = ufs.FirstOrDefault(); else Incluir(cidade.UF); } public void Setup() { UFDAL.Setup(); CidadeDAL.Setup(); EnderecoDAL.Setup(); } } }
22.725
129
0.719839
[ "Apache-2.0" ]
JOHNRAMOSRJ/JRSoftware.AspNetCoreWebAPI
src/JRSoftware.Clientes.Core/Repositorio/EnderecoRepository.cs
2,729
C#
// Copyright (c) Matt Lacey Ltd. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using RapidXaml; namespace RapidXamlToolkit.Tests.AutoFix { [TestClass] public class ProjectTests { [TestMethod] public void AllFilesAreAnalyzed() { var xamlFile1 = @"<Page> <WebView /> </Page>"; var xamlFile2 = @"<Page> <Grid /> </Page>"; var xamlFile3 = @"<Page> <WebView></WebView> </Page>"; var projFile = @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration> <Platform Condition="" '$(Platform)' == '' "">x86</Platform> <ProjectGuid>{5B9F660F-7966-4AF6-8B83-9A6CB2E81FF4}</ProjectGuid> <OutputType>AppContainerExe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>BlankWinuiUwpApp</RootNamespace> <AssemblyName>BlankWinuiUwpApp</AssemblyName> <DefaultLanguage>en-US</DefaultLanguage> <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier> <TargetPlatformVersion Condition="" '$(TargetPlatformVersion)' == '' "">10.0.19041.0</TargetPlatformVersion> <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion> <MinimumVisualStudioVersion>16</MinimumVisualStudioVersion> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <WindowsXamlEnableOverview>true</WindowsXamlEnableOverview> <IsWinUIAlpha Condition=""'$(IsWinUIAlpha)' == ''"">true</IsWinUIAlpha> <WindowsKitsPath Condition=""'$(IsWinUIAlpha)' == 'true'"">WinUI-Alpha-Projects-Don-t-Use-SDK-Xaml-Tools</WindowsKitsPath> <PackageCertificateKeyFile>BlankWinuiUwpApp_TemporaryKey.pfx</PackageCertificateKeyFile> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'""> <DebugSymbols>true</DebugSymbols> <OutputPath>bin\x86\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants> <DebugType>full</DebugType> <PlatformTarget>x86</PlatformTarget> <UseVSHostingProcess>false</UseVSHostingProcess> <ErrorReport>prompt</ErrorReport> <Prefer32Bit>true</Prefer32Bit> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'""> <OutputPath>bin\x86\Release\</OutputPath> <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants> <Optimize>true</Optimize> <DebugType>pdbonly</DebugType> <PlatformTarget>x86</PlatformTarget> <UseVSHostingProcess>false</UseVSHostingProcess> <ErrorReport>prompt</ErrorReport> <Prefer32Bit>true</Prefer32Bit> <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'""> <DebugSymbols>true</DebugSymbols> <OutputPath>bin\x64\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants> <DebugType>full</DebugType> <PlatformTarget>x64</PlatformTarget> <UseVSHostingProcess>false</UseVSHostingProcess> <ErrorReport>prompt</ErrorReport> <Prefer32Bit>true</Prefer32Bit> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'""> <OutputPath>bin\x64\Release\</OutputPath> <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants> <Optimize>true</Optimize> <DebugType>pdbonly</DebugType> <PlatformTarget>x64</PlatformTarget> <UseVSHostingProcess>false</UseVSHostingProcess> <ErrorReport>prompt</ErrorReport> <Prefer32Bit>true</Prefer32Bit> <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain> </PropertyGroup> <PropertyGroup> <RestoreProjectStyle>PackageReference</RestoreProjectStyle> </PropertyGroup> <ItemGroup> <Compile Include=""App.xaml.cs""> <DependentUpon>App.xaml</DependentUpon> </Compile> <Compile Include=""MainPage.xaml.cs""> <DependentUpon>MainPage.xaml</DependentUpon> </Compile> <Compile Include=""Page1.xaml.cs""> <DependentUpon>Page1.xaml</DependentUpon> </Compile> <Compile Include=""Page2.xaml.cs""> <DependentUpon>Page2.xaml</DependentUpon> </Compile> <Compile Include=""Page3.xaml.cs""> <DependentUpon>Page3.xaml</DependentUpon> </Compile> <Compile Include=""Properties\AssemblyInfo.cs"" /> </ItemGroup> <ItemGroup> <AppxManifest Include=""Package.appxmanifest""> <SubType>Designer</SubType> </AppxManifest> <None Include=""BlankWinuiUwpApp_TemporaryKey.pfx"" /> </ItemGroup> <ItemGroup> <Content Include=""Properties\Default.rd.xml"" /> <Content Include=""Assets\LockScreenLogo.scale-200.png"" /> <Content Include=""Assets\SplashScreen.scale-200.png"" /> <Content Include=""Assets\Square150x150Logo.scale-200.png"" /> <Content Include=""Assets\Square44x44Logo.scale-200.png"" /> <Content Include=""Assets\Square44x44Logo.targetsize-24_altform-unplated.png"" /> <Content Include=""Assets\StoreLogo.png"" /> <Content Include=""Assets\Wide310x150Logo.scale-200.png"" /> </ItemGroup> <ItemGroup> <ApplicationDefinition Include=""App.xaml""> <Generator>MSBuild:Compile</Generator> </ApplicationDefinition> <Page Include=""MainPage.xaml""> <Generator>MSBuild:Compile</Generator> </Page> <Page Include=""Page1.xaml""> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> </Page> <Page Include=""Page2.xaml""> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> </Page> <Page Include=""Page3.xaml""> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> </Page> </ItemGroup> <ItemGroup> <PackageReference Include=""Microsoft.NETCore.UniversalWindowsPlatform""> <Version>6.2.10</Version> </PackageReference> <PackageReference Include=""Microsoft.WinUI""> <Version>3.0.0-preview2.200713.0</Version> </PackageReference> </ItemGroup> <PropertyGroup Condition="" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '$(MinimumVisualStudioVersion)' ""> <VisualStudioVersion>$(MinimumVisualStudioVersion)</VisualStudioVersion> </PropertyGroup> <Import Project=""$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets"" /> </Project>"; var fs = new BespokeTestFileSystem { FileExistsResponse = true, FileLines = projFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None), }; fs.FilesAndContents.Add("MyApp.csproj", projFile); fs.FilesAndContents.Add("Page1.xaml", xamlFile1); fs.FilesAndContents.Add("Page2.xaml", xamlFile2); fs.FilesAndContents.Add("Page3.xaml", xamlFile3); #if DEBUG var expectedXaml1 = @"<Page> <WebView2 Source=""https://rapidxaml.dev/"" /> </Page>"; var expectedXaml2 = @"<Page> <Grid /> </Page>"; var expectedXaml3 = @"<Page> <WebView2 Source=""https://rapidxaml.dev/""></WebView2> </Page>"; var sut = new XamlConverter(fs); var (success, details) = sut.ConvertAllFilesInProject("MyApp.csproj", new[] { new WebViewMultipleActionsAnalyzer() }); Assert.AreEqual(true, success); Assert.AreEqual(20, details.Count()); Assert.AreEqual(expectedXaml1, fs.WrittenFiles["Page1.xaml"]); Assert.AreEqual(expectedXaml2, fs.WrittenFiles["Page2.xaml"]); Assert.AreEqual(expectedXaml3, fs.WrittenFiles["Page3.xaml"]); #endif } } }
41.12
190
0.692972
[ "MIT" ]
Microsoft/Rapid-XAML-Toolkit
VSIX/RapidXamlToolkit.Tests.AutoFix/ProjectTests.cs
8,226
C#
using ProtoBuf.Grpc.Configuration; using System; using System.Linq; using System.Threading.Tasks; using Xunit; using static ProtoBuf.Grpc.Configuration.ServerBinder; namespace protobuf_net.Grpc.Test { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)] public class SomethingAttribute : Attribute { public string Value { get; } public SomethingAttribute(string value) => Value = value; } [Something("Interface")] public interface ISomeService { [Something("ImplicitInterfaceMethod")] ValueTask Implicit(); [Something("ExplicitInterfaceMethod")] ValueTask Explicit(); } [Something("BaseType")] public class BaseService { [Something("ImplicitServiceMethodBase")] public virtual ValueTask Implicit() => default; } [Something("Service")] public class SomeServer : BaseService, ISomeService { [Something("ImplicitServiceMethodOverride")] public override ValueTask Implicit() => default; [Something("ExplicitServiceMethod")] ValueTask ISomeService.Explicit() => default; } public class AttributeDetection { [Theory] [InlineData(nameof(ISomeService.Implicit), "Interface,ImplicitInterfaceMethod,BaseType,Service,ImplicitServiceMethodBase,ImplicitServiceMethodOverride")] [InlineData(nameof(ISomeService.Explicit), "Interface,ExplicitInterfaceMethod,BaseType,Service,ExplicitServiceMethod")] public void AttributesDetectedWherever(string methodName, string expected) { var ctx = new ServiceBindContext(typeof(ISomeService), typeof(SomeServer), "n/a"); var method = typeof(ISomeService).GetMethod(methodName)!; var actual = string.Join(",", ctx.GetMetadata(method).OfType<SomethingAttribute>().Select(x => x.Value)); Assert.Equal(expected, actual); } } }
32.540984
122
0.675567
[ "Apache-2.0" ]
GrantEmpire/protobuf-net.Grpc
tests/protobuf-net.Grpc.Test/AttributeDetection.cs
1,987
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("MScResearchTool.Mobile.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MScResearchTool.Mobile.Services")] [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("782cc16c-2b0d-4eb1-85b6-38f52bff4a8c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.648649
84
0.751748
[ "MIT" ]
zbigniewmarszolik/MScResearchTool
MScResearchTool.Mobile/MScResearchTool.Mobile.Services/Properties/AssemblyInfo.cs
1,433
C#
using System; using System.Collections.Generic; using System.Text; namespace Patchwork.Attributes { /// <summary> /// You must decorate your <see cref="IPatchInfo"/>-implementing class with this attribute. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class PatchInfoAttribute : Attribute { } }
21.375
92
0.74269
[ "MIT" ]
DankRank/Patchwork
Patchwork.Attributes/Automatic Patching/PatchInfoAttribute.cs
344
C#
using System; using Castle.MicroKernel.Registration; using NSubstitute; using Abp.AutoMapper; using Abp.Dependency; using Abp.Modules; using Abp.Configuration.Startup; using Abp.Net.Mail; using Abp.TestBase; using Abp.Zero.Configuration; using Abp.Zero.EntityFrameworkCore; using CallOfShare.EntityFrameworkCore; using CallOfShare.Tests.DependencyInjection; namespace CallOfShare.Tests { [DependsOn( typeof(CallOfShareApplicationModule), typeof(CallOfShareEntityFrameworkModule), typeof(AbpTestBaseModule) )] public class CallOfShareTestModule : AbpModule { public CallOfShareTestModule(CallOfShareEntityFrameworkModule abpProjectNameEntityFrameworkModule) { abpProjectNameEntityFrameworkModule.SkipDbContextRegistration = true; abpProjectNameEntityFrameworkModule.SkipDbSeed = true; } public override void PreInitialize() { Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30); Configuration.UnitOfWork.IsTransactional = false; // Disable static mapper usage since it breaks unit tests (see https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2052) Configuration.Modules.AbpAutoMapper().UseStaticMapper = false; Configuration.BackgroundJobs.IsJobExecutionEnabled = false; // Use database for language management Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization(); RegisterFakeService<AbpZeroDbMigrator<CallOfShareDbContext>>(); Configuration.ReplaceService<IEmailSender, NullEmailSender>(DependencyLifeStyle.Transient); } public override void Initialize() { ServiceCollectionRegistrar.Register(IocManager); } private void RegisterFakeService<TService>() where TService : class { IocManager.IocContainer.Register( Component.For<TService>() .UsingFactoryMethod(() => Substitute.For<TService>()) .LifestyleSingleton() ); } } }
33.952381
142
0.693782
[ "MIT" ]
nguyendiennghia/CallOfShare
aspnet-core/test/CallOfShare.Tests/CallOfShareTestModule.cs
2,139
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; namespace LinqToDB.Tools { [PublicAPI] public static class SqlExtensions { #region In/NotIn [ExpressionMethod(nameof(InImpl1))] public static bool In<T>(this T value, IEnumerable<T> sequence) { return sequence.Contains(value); } static Expression<Func<T,IEnumerable<T>,bool>> InImpl1<T>() { return (value,sequence) => sequence.Contains(value); } [ExpressionMethod(nameof(InImpl2))] public static bool In<T>(this T value, IQueryable<T> sequence) { return sequence.Contains(value); } static Expression<Func<T,IQueryable<T>,bool>> InImpl2<T>() { return (value,sequence) => sequence.Contains(value); } [ExpressionMethod(nameof(InImpl3))] public static bool In<T>(this T value, params T[] sequence) { return sequence.Contains(value); } static Expression<Func<T,T[],bool>> InImpl3<T>() { return (value,sequence) => sequence.Contains(value); } [ExpressionMethod(nameof(InImpl4))] public static bool In<T>(this T value, T cmp1, T cmp2) { return object.Equals(value, cmp1) || object.Equals(value, cmp2); } static Expression<Func<T,T,T,bool>> InImpl4<T>() { return (value,cmp1,cmp2) => value.In(new[] { cmp1, cmp2 }); } [ExpressionMethod(nameof(InImpl5))] public static bool In<T>(this T value, T cmp1, T cmp2, T cmp3) { return object.Equals(value, cmp1) || object.Equals(value, cmp2) || object.Equals(value, cmp3); } static Expression<Func<T,T,T,T,bool>> InImpl5<T>() { return (value,cmp1,cmp2,cmp3) => value.In(new[] { cmp1, cmp2, cmp3 }); } [ExpressionMethod(nameof(NotInImpl1))] public static bool NotIn<T>(this T value, IEnumerable<T> sequence) { return !sequence.Contains(value); } static Expression<Func<T,IEnumerable<T>,bool>> NotInImpl1<T>() { return (value,sequence) => !sequence.Contains(value); } [ExpressionMethod(nameof(NotInImpl2))] public static bool NotIn<T>(this T value, IQueryable<T> sequence) { return !sequence.Contains(value); } static Expression<Func<T,IQueryable<T>,bool>> NotInImpl2<T>() { return (value,sequence) => !sequence.Contains(value); } [ExpressionMethod(nameof(NotInImpl3))] public static bool NotIn<T>(this T value, params T[] sequence) { return !sequence.Contains(value); } static Expression<Func<T,T[],bool>> NotInImpl3<T>() { return (value,sequence) => !sequence.Contains(value); } [ExpressionMethod(nameof(NotInImpl4))] public static bool NotIn<T>(this T value, T cmp1, T cmp2) { return !object.Equals(value, cmp1) && !object.Equals(value, cmp2); } static Expression<Func<T,T,T,bool>> NotInImpl4<T>() { return (value,cmp1,cmp2) => value.NotIn(new[] { cmp1, cmp2 }); } [ExpressionMethod(nameof(NotInImpl5))] public static bool NotIn<T>(this T value, T cmp1, T cmp2, T cmp3) { return !object.Equals(value, cmp1) && !object.Equals(value, cmp2) && !object.Equals(value, cmp3); } static Expression<Func<T,T,T,T,bool>> NotInImpl5<T>() { return (value,cmp1,cmp2,cmp3) => value.NotIn(new[] { cmp1, cmp2, cmp3 }); } #endregion // #region Truncate // // public static int Truncate<T>(this ITable<T> table) // { // var tableName = table.GetTableName(); // // switch (table.DataContext) // { // case DataConnection dc : return dc. Execute<int>($"TRUNCATE TABLE {tableName}"); // case DataContext dx : return dx.GetDataConnection().Execute<int>($"TRUNCATE TABLE {tableName}"); // default : throw new NotImplementedException(); // } // } // // #endregion } }
26.652778
106
0.638874
[ "MIT" ]
AndreyAndryushinPSB/linq2db
Source/LinqToDB/Tools/SqlExtensions.cs
3,697
C#
namespace StyleCop.Analyzers.DocumentationRules { using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; /// <summary> /// The documentation text within a C# property's <c>&lt;summary&gt;</c> tag does not match the accessors within the /// property. /// </summary> /// <remarks> /// <para>C# syntax provides a mechanism for inserting documentation for classes and elements directly into the /// code, through the use of XML documentation headers. For an introduction to these headers and a description of /// the header syntax, see the following article: /// <see href="http://msdn.microsoft.com/en-us/magazine/cc302121.aspx">XML Comments Let You Build Documentation /// Directly From Your Visual Studio .NET Source Files</see>.</para> /// /// <para>A violation of this rule occurs if a property's summary documentation does not match the accessors within /// the property.</para> /// /// <para>The property's summary text must begin with wording describing the types of accessors exposed within the /// property. If the property contains only a get accessor, the summary must begin with the word "Gets". If the /// property contains only a set accessor, the summary must begin with the word "Sets". If the property exposes both /// a get and set accessor, the summary text must begin with "Gets or sets".</para> /// /// <para>For example, consider the following property, which exposes both a get and set accessor. The summary text /// begins with the words "Gets or sets".</para> /// <code language="csharp"> /// /// &lt;summary&gt; /// /// Gets or sets the name of the customer. /// /// &lt;/summary&gt; /// public string Name /// { ///     get { return this.name; } ///     set { this.name = value; } /// } /// </code> /// /// <para>If the property returns a Boolean value, an additional rule is applied. The summary text for Boolean /// properties must contain the words "Gets a value indicating whether", "Sets a value indicating whether", or "Gets /// or sets a value indicating whether". For example, consider the following Boolean property, which only exposes a /// get accessor:</para> /// /// <code language="csharp"> /// /// &lt;summary&gt; /// /// Gets a value indicating whether the item is enabled. /// /// &lt;/summary&gt; /// public bool Enabled /// { ///     get { return this.enabled; } /// } /// </code> /// /// <para>In some situations, the set accessor for a property can have more restricted access than the get accessor. /// For example:</para> /// /// <code language="csharp"> /// /// &lt;summary&gt; /// /// Gets the name of the customer. /// /// &lt;/summary&gt; /// public string Name /// { ///     get { return this.name; } ///     private set { this.name = value; } /// } /// </code> /// /// <para>In this example, the set accessor has been given private access, meaning that it can only be accessed by /// local members of the class in which it is contained. The get accessor, however, inherits its access from the /// parent property, thus it can be accessed by any caller, since the property has public access.</para> /// /// <para>>In this case, the documentation summary text should avoid referring to the set accessor, since it is not /// visible to external callers.</para> /// /// <para>StyleCop applies a series of rules to determine when the set accessor should be referenced in the /// property's summary documentation. In general, these rules require the set accessor to be referenced whenever it /// is visible to the same set of callers as the get accessor, or whenever it is visible to external classes or /// inheriting classes.</para> /// /// <para>The specific rules for determining whether to include the set accessor in the property's summary /// documentation are:</para> /// /// <list type="number"> /// <item> /// <para>The set accessor has the same access level as the get accessor. For example:</para> /// /// <code language="csharp"> /// /// &lt;summary&gt; /// /// Gets or sets the name of the customer. /// /// &lt;/summary&gt; /// protected string Name /// { ///     get { return this.name; } ///     set { this.name = value; } /// } /// </code> /// </item> /// <item> /// <para>The property is only internally accessible within the assembly, and the set accessor also has internal /// access. For example:</para> /// <code language="csharp"> /// internal class Class1 /// { ///     /// &lt;summary&gt; ///     /// Gets or sets the name of the customer. /// /// &lt;/summary&gt; /// protected string Name /// { ///     get { return this.name; } ///         internal set { this.name = value; } ///     } /// } /// </code> /// /// <code language="csharp"> /// internal class Class1 /// { /// public class Class2 /// { ///         /// &lt;summary&gt; ///      /// Gets or sets the name of the customer. ///         /// &lt;/summary&gt; ///         public string Name ///         { ///             get { return this.name; } ///          internal set { this.name = value; } ///         } ///     } /// } /// </code> /// </item> /// <item> /// <para>The property is private or is contained beneath a private class, and the set accessor has any access /// modifier other than private. In the example below, the access modifier declared on the set accessor has no /// meaning, since the set accessor is contained within a private class and thus cannot be seen by other classes /// outside of <c>Class1</c>. This effectively gives the set accessor the same access level as the get /// accessor.</para> /// /// <code language="csharp"> /// public class Class1 /// { ///     private class Class2 ///     { ///         public class Class3 ///         { ///             /// &lt;summary&gt; ///             /// Gets or sets the name of the customer. ///             /// &lt;/summary&gt; ///             public string Name ///             { ///                 get { return this.name; } ///                 internal set { this.name = value; } ///             } ///         } ///     } /// } /// </code> /// </item> /// <item> /// <para>Whenever the set accessor has protected or protected internal access, it should be referenced in the /// documentation. A protected or protected internal set accessor can always been seen by a class inheriting from /// the class containing the property.</para> /// /// <code language="csharp"> /// internal class Class1 /// { ///     public class Class2 ///     { ///         /// &lt;summary&gt; ///         /// Gets or sets the name of the customer. ///         /// &lt;/summary&gt; ///         internal string Name ///         { ///             get { return this.name; } ///             protected set { this.name = value; } ///         } ///     } /// ///     private class Class3 : Class2 ///     { ///         public Class3(string name) { this.Name = name; } ///     } /// } /// </code> /// </item> /// </list> /// </remarks> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class SA1623PropertySummaryDocumentationMustMatchAccessors : DiagnosticAnalyzer { public const string DiagnosticId = "SA1623"; internal const string Title = "Property summary documentation must match accessors"; internal const string MessageFormat = "TODO: Message format"; internal const string Category = "StyleCop.CSharp.DocumentationRules"; internal const string Description = "The documentation text within a C# property’s &lt;summary&gt; tag does not match the accessors within the property."; internal const string HelpLink = "http://www.stylecop.com/docs/SA1623.html"; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink); private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = ImmutableArray.Create(Descriptor); /// <inheritdoc/> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return _supportedDiagnostics; } } /// <inheritdoc/> public override void Initialize(AnalysisContext context) { // TODO: Implement analysis } } }
41.277273
169
0.58672
[ "Apache-2.0" ]
ishisaka/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/DocumentationRules/SA1623PropertySummaryDocumentationMustMatchAccessors.cs
9,400
C#
using System; namespace Torch.Utils { /// <summary> /// Indicates that this field should contain the <see cref="System.Reflection.PropertyInfo"/> instance for the given property. /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ReflectedPropertyInfoAttribute : ReflectedMemberAttribute { /// <summary> /// Creates a reflected property info attribute using the given type and name. /// </summary> /// <param name="type">Type that contains the member</param> /// <param name="name">Name of the member</param> public ReflectedPropertyInfoAttribute(Type type, string name) { Type = type; Name = name; } } }
33.590909
130
0.630582
[ "Apache-2.0" ]
Andargor/Torch
Torch/Utils/Reflected/ReflectedPropertyInfoAttribute.cs
739
C#
namespace Microsoft.AspNetCore.Mvc { using Http; /// <summary> /// An <see cref="ObjectResult"/> that when executed performs content negotiation, formats the entity body, and /// will produce a <see cref="StatusCodes.Status412PreconditionFailed"/> response if negotiation and formatting succeed. /// </summary> public class PreconditionFailedObjectResult : ObjectResult { /// <summary> /// Initializes a new instance of the <see cref="PreconditionFailedObjectResult"/> class. /// </summary> /// <param name="value">The content to format into the entity body.</param> public PreconditionFailedObjectResult(object value) : base(value) { this.StatusCode = StatusCodes.Status412PreconditionFailed; } } }
38.714286
124
0.660517
[ "MIT" ]
Magicianred/AspNetCore.Mvc.HttpActionResults
src/AspNetCore.Mvc.HttpActionResults.ClientError/PreconditionFailedObjectResult.cs
815
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Adic.Util; namespace Adic.Cache { /// <summary> /// Factory for <see cref="IReflectedClass"/>. /// </summary> public class ReflectionFactory : IReflectionFactory { /// <summary> /// Creates a <see cref="ReflectedClass"/> from a <paramref name="type"/>. /// </summary> /// <param name="type">Type from which the reflected class will be created.</param> public ReflectedClass Create(Type type) { var reflectedClass = new ReflectedClass(); reflectedClass.type = type; var constructor = this.ResolveConstructor(type); if (constructor != null) { if (constructor.GetParameters().Length == 0) { reflectedClass.constructor = MethodUtils.CreateConstructor(type, constructor); } else { reflectedClass.paramsConstructor = MethodUtils.CreateConstructorWithParams(type, constructor); ; } } reflectedClass.constructorParameters = this.ResolveConstructorParameters(constructor); reflectedClass.methods = this.ResolveMethods(type); reflectedClass.properties = this.ResolveProperties(type); reflectedClass.fields = this.ResolveFields(type); return reflectedClass; } /// <summary> /// Selects the constructor marked with <see cref="InjectAttribute"/> or with the minimum amount of parameters. /// </summary> /// <param name="type">Type from which reflection will be resolved.</param> /// <returns>The constructor.</returns> #pragma warning disable 0618 protected ConstructorInfo ResolveConstructor(Type type) { var constructors = type.GetConstructors( BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod); if (constructors.Length == 0) { return null; } if (constructors.Length == 1) { return constructors[0]; } ConstructorInfo shortestConstructor = null; for (int i = 0, length = 0, shortestLength = int.MaxValue; i < constructors.Length; i++) { var constructor = constructors[i]; // Construct attribute will be removed on future version. var attributesConstruct = constructor.GetCustomAttributes(typeof(Construct), true); var attributesInject = constructor.GetCustomAttributes(typeof(Inject), true); if (attributesConstruct.Length > 0 || attributesInject.Length > 0) { return constructor; } length = constructor.GetParameters().Length; if (length < shortestLength) { shortestLength = length; shortestConstructor = constructor; } } return shortestConstructor; } /// <summary> /// Resolves the constructor parameters. /// </summary> /// <param name="constructor">The constructor to have the parameters resolved.</param> /// <returns>The constructor parameters.</returns> protected ParameterInfo[] ResolveConstructorParameters(ConstructorInfo constructor) { if (constructor == null) return null; var parameters = constructor.GetParameters(); var constructorParameters = new ParameterInfo[parameters.Length]; for (int paramIndex = 0; paramIndex < constructorParameters.Length; paramIndex++) { object identifier = null; var parameter = parameters[paramIndex]; var attributes = parameter.GetCustomAttributes(typeof(Inject), true); if (attributes.Length > 0) { identifier = (attributes[0] as Inject).identifier; } constructorParameters[paramIndex] = new ParameterInfo(parameter.ParameterType, parameter.Name, identifier); } return constructorParameters; } /// <summary> /// Resolves the methods that can be injected. /// </summary> /// <returns>The methods with Inject attributes.</returns> #pragma warning disable 0618 protected MethodInfo[] ResolveMethods(Type type) { var methodCalls = new List<MethodInfo>(); var methods = type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++) { var method = methods[methodIndex]; // PostConstruct attribute will be removed on future version. var attributesPostConstruct = method.GetCustomAttributes(typeof(PostConstruct), true); var attributesInject = method.GetCustomAttributes(typeof(Inject), true); if (attributesPostConstruct.Length > 0 || attributesInject.Length > 0) { var parameters = method.GetParameters(); var methodParameters = new ParameterInfo[parameters.Length]; for (int paramIndex = 0; paramIndex < methodParameters.Length; paramIndex++) { object identifier = null; var parameter = parameters[paramIndex]; var parameterAttributes = parameter.GetCustomAttributes(typeof(Inject), true); if (parameterAttributes.Length > 0) { identifier = (parameterAttributes[0] as Inject).identifier; } methodParameters[paramIndex] = new ParameterInfo(parameter.ParameterType, parameter.Name, identifier); } var methodCall = new MethodInfo(method.Name, methodParameters); if (methodParameters.Length == 0) { methodCall.method = MethodUtils.CreateParameterlessMethod(type, method); } else { methodCall.paramsMethod = MethodUtils.CreateParameterizedMethod(type, method); } methodCalls.Add(methodCall); } } return methodCalls.ToArray(); } /// <summary> /// Resolves the properties that can be injected. /// </summary> /// <param name="type">Type from which reflection will be resolved.</param> /// <returns>The properties.</returns> protected AcessorInfo[] ResolveProperties(Type type) { var setters = new List<AcessorInfo>(); var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex++) { var property = properties[propertyIndex] as PropertyInfo; var attributes = property.GetCustomAttributes(typeof(Inject), true); if (attributes.Length > 0) { var attribute = attributes[0] as Inject; var getter = MethodUtils.CreatePropertyGetter(type, property); var setter = MethodUtils.CreatePropertySetter(type, property); var info = new AcessorInfo(property.PropertyType, property.Name, attribute.identifier, getter, setter); setters.Add(info); } } return setters.ToArray(); } /// <summary> /// Resolves the fields that can be injected. /// </summary> /// <param name="type">Type from which reflection will be resolved.</param> /// <returns>The fields.</returns> protected AcessorInfo[] ResolveFields(Type type) { var setters = new List<AcessorInfo>(); var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int fieldIndex = 0; fieldIndex < fields.Length; fieldIndex++) { var field = fields[fieldIndex] as FieldInfo; var attributes = field.GetCustomAttributes(typeof(Inject), true); if (attributes.Length > 0) { var attribute = attributes[0] as Inject; var getter = MethodUtils.CreateFieldGetter(type, field); var setter = MethodUtils.CreateFieldSetter(type, field); var info = new AcessorInfo(field.FieldType, field.Name, attribute.identifier, getter, setter); setters.Add(info); } } return setters.ToArray(); } } }
43.557078
126
0.556767
[ "Unlicense" ]
Djohnnie/BuildCloudNativeApplicationsWithDotNet5-DotNetDeveloperDays-2020
csharpwars/frontend/CSharpWars/Assets/External/Adic/Scripts/Framework/Cache/ReflectionFactory.cs
9,539
C#
using System; namespace Dice { public class Dice { private int sides; private Random rnd = new Random(); public int Roll() { int rollResult = rnd.Next(1, this.sides + 1); return rollResult; } } class Program { static void Main(string[] args) { } } }
14.615385
57
0.460526
[ "MIT" ]
BorislavVladimirov/C-Software-University
C# Advanced May 2019/Defining Classes/Defining Classes/Dice/Program.cs
382
C#
#nullable enable using System; using System.Threading; using NUnit.Framework; namespace Omnifactotum.Tests { [TestFixture(TestOf = typeof(StopwatchElapsedTimeProvider))] internal sealed class StopwatchElapsedTimeProviderTests { private static readonly TimeSpan WaitInterval = TimeSpan.FromMilliseconds(10); [Test] public void TestConstruction() { var testee = CreateTestee(); Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(TimeSpan.Zero)); Thread.Sleep(WaitInterval); Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(TimeSpan.Zero)); } [Test] public void TestStartAndStop() { var testee = CreateTestee(); testee.Start(); Assert.That(testee.IsRunning, Is.True); Assert.That(testee.Elapsed, Is.GreaterThanOrEqualTo(TimeSpan.Zero)); Thread.Sleep(WaitInterval); var elapsedAfterWait1 = testee.Elapsed; Assert.That(testee.IsRunning, Is.True); Assert.That(elapsedAfterWait1, Is.GreaterThan(TimeSpan.Zero)); Thread.Sleep(WaitInterval); var elapsedAfterWait2 = testee.Elapsed; Assert.That(testee.IsRunning, Is.True); Assert.That(elapsedAfterWait2, Is.GreaterThan(elapsedAfterWait1)); Thread.Sleep(WaitInterval); testee.Stop(); var elapsedWhenStopped = testee.Elapsed; Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(elapsedWhenStopped)); Thread.Sleep(WaitInterval); Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(elapsedWhenStopped)); } [Test] public void TestStartAndReset() { var testee = CreateTestee(); testee.Start(); Thread.Sleep(WaitInterval); Assert.That(testee.IsRunning, Is.True); Assert.That(testee.Elapsed, Is.GreaterThan(TimeSpan.Zero)); testee.Reset(); Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(TimeSpan.Zero)); Thread.Sleep(WaitInterval); Assert.That(testee.IsRunning, Is.False); Assert.That(testee.Elapsed, Is.EqualTo(TimeSpan.Zero)); } private static StopwatchElapsedTimeProvider CreateTestee() => new(); } }
29.678161
86
0.611929
[ "MIT" ]
HarinezumiSama/omnifactotum
src/Omnifactotum.Tests/StopwatchElapsedTimeProviderTests.cs
2,584
C#
using System; using System.Collections.Generic; namespace ModLib { public static class IEnumerableExtensions { /// <summary> /// Applies the action to all elements in the collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="action"></param> public static IEnumerable<T> Do<T>(this IEnumerable<T> enumerable, Action<T> action) { if (enumerable != null) { foreach (var item in enumerable) action?.Invoke(item); return enumerable; } else return null; } } }
26.740741
92
0.515235
[ "MIT" ]
MiCLeal/ModLib
ExtensionMethods/IEnumerableExtensions.cs
724
C#
using MrMatrix.Net.ActorOnServiceBus.ActorSystem.Interfaces; namespace MrMatrix.Net.ActorOnServiceBus.ActorSystem.Core { public interface IActorMetadata { Type ActorType { get; } MessageDirection Direction { get; } string TopicUri { get; } IActorMessageHandler CreateActorMessageHandler(); } }
28.166667
60
0.713018
[ "MIT" ]
MariuszKrzanowski/asb-actor-model
src/MrMatrix.Net.ActorOnServiceBus.ActorSystem.Core/IActorMetadata.cs
338
C#
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Agent.Sdk; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Loader; using System.Threading; using System.Threading.Tasks; using System.Text; using Microsoft.TeamFoundation.Framework.Common; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(AgentPluginManager))] public interface IAgentPluginManager : IAgentService { AgentTaskPluginInfo GetPluginTask(Guid taskId, string taskVersion); AgentCommandPluginInfo GetPluginCommad(string commandArea, string commandEvent); Task RunPluginTaskAsync(IExecutionContext context, string plugin, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, EventHandler<ProcessDataReceivedEventArgs> outputHandler); void ProcessCommand(IExecutionContext context, Command command); } public sealed class AgentPluginManager : AgentService, IAgentPluginManager { private readonly Dictionary<string, Dictionary<string, AgentCommandPluginInfo>> _supportedLoggingCommands = new Dictionary<string, Dictionary<string, AgentCommandPluginInfo>>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<Guid, Dictionary<string, AgentTaskPluginInfo>> _supportedTasks = new Dictionary<Guid, Dictionary<string, AgentTaskPluginInfo>>(); private readonly HashSet<string> _taskPlugins = new HashSet<string>() { "Agent.Plugins.Repository.CheckoutTask, Agent.Plugins", "Agent.Plugins.Repository.CleanupTask, Agent.Plugins", "Agent.Plugins.PipelineArtifact.DownloadPipelineArtifactTask, Agent.Plugins", "Agent.Plugins.PipelineArtifact.PublishPipelineArtifactTask, Agent.Plugins", "Agent.Plugins.PipelineArtifact.DownloadPipelineArtifactTaskV1, Agent.Plugins", "Agent.Plugins.PipelineArtifact.DownloadPipelineArtifactTaskV1_1_0, Agent.Plugins" }; private readonly HashSet<string> _commandPlugins = new HashSet<string>(); public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); // Load task plugins foreach (var pluginTypeName in _taskPlugins) { IAgentTaskPlugin taskPlugin = null; AssemblyLoadContext.Default.Resolving += ResolveAssembly; try { Trace.Info($"Load task plugin from '{pluginTypeName}'."); Type type = Type.GetType(pluginTypeName, throwOnError: true); taskPlugin = Activator.CreateInstance(type) as IAgentTaskPlugin; } finally { AssemblyLoadContext.Default.Resolving -= ResolveAssembly; } ArgUtil.NotNull(taskPlugin, nameof(taskPlugin)); ArgUtil.NotNull(taskPlugin.Id, nameof(taskPlugin.Id)); ArgUtil.NotNullOrEmpty(taskPlugin.Version, nameof(taskPlugin.Version)); ArgUtil.NotNullOrEmpty(taskPlugin.Stage, nameof(taskPlugin.Stage)); if (!_supportedTasks.ContainsKey(taskPlugin.Id)) { _supportedTasks[taskPlugin.Id] = new Dictionary<string, AgentTaskPluginInfo>(StringComparer.OrdinalIgnoreCase); } if (!_supportedTasks[taskPlugin.Id].ContainsKey(taskPlugin.Version)) { _supportedTasks[taskPlugin.Id][taskPlugin.Version] = new AgentTaskPluginInfo(); } Trace.Info($"Loaded task plugin id '{taskPlugin.Id}' ({taskPlugin.Version}) ({taskPlugin.Stage})."); if (taskPlugin.Stage == "pre") { _supportedTasks[taskPlugin.Id][taskPlugin.Version].TaskPluginPreJobTypeName = pluginTypeName; } else if (taskPlugin.Stage == "main") { _supportedTasks[taskPlugin.Id][taskPlugin.Version].TaskPluginTypeName = pluginTypeName; } else if (taskPlugin.Stage == "post") { _supportedTasks[taskPlugin.Id][taskPlugin.Version].TaskPluginPostJobTypeName = pluginTypeName; } } // Load command plugin foreach (var pluginTypeName in _commandPlugins) { IAgentCommandPlugin commandPlugin = null; AssemblyLoadContext.Default.Resolving += ResolveAssembly; try { Trace.Info($"Load command plugin from '{pluginTypeName}'."); Type type = Type.GetType(pluginTypeName, throwOnError: true); commandPlugin = Activator.CreateInstance(type) as IAgentCommandPlugin; } finally { AssemblyLoadContext.Default.Resolving -= ResolveAssembly; } ArgUtil.NotNull(commandPlugin, nameof(commandPlugin)); ArgUtil.NotNullOrEmpty(commandPlugin.Area, nameof(commandPlugin.Area)); ArgUtil.NotNullOrEmpty(commandPlugin.Event, nameof(commandPlugin.Event)); ArgUtil.NotNullOrEmpty(commandPlugin.DisplayName, nameof(commandPlugin.DisplayName)); if (!_supportedLoggingCommands.ContainsKey(commandPlugin.Area)) { _supportedLoggingCommands[commandPlugin.Area] = new Dictionary<string, AgentCommandPluginInfo>(StringComparer.OrdinalIgnoreCase); } Trace.Info($"Loaded command plugin to handle '##vso[{commandPlugin.Area}.{commandPlugin.Event}]'."); _supportedLoggingCommands[commandPlugin.Area][commandPlugin.Event] = new AgentCommandPluginInfo() { CommandPluginTypeName = pluginTypeName, DisplayName = commandPlugin.DisplayName }; } } public AgentTaskPluginInfo GetPluginTask(Guid taskId, string taskVersion) { if (_supportedTasks.ContainsKey(taskId) && _supportedTasks[taskId].ContainsKey(taskVersion)) { return _supportedTasks[taskId][taskVersion]; } else { return null; } } public AgentCommandPluginInfo GetPluginCommad(string commandArea, string commandEvent) { if (_supportedLoggingCommands.ContainsKey(commandArea) && _supportedLoggingCommands[commandArea].ContainsKey(commandEvent)) { return _supportedLoggingCommands[commandArea][commandEvent]; } else { return null; } } public async Task RunPluginTaskAsync(IExecutionContext context, string plugin, Dictionary<string, string> inputs, Dictionary<string, string> environment, Variables runtimeVariables, EventHandler<ProcessDataReceivedEventArgs> outputHandler) { ArgUtil.NotNullOrEmpty(plugin, nameof(plugin)); // Only allow plugins we defined if (!_taskPlugins.Contains(plugin)) { throw new NotSupportedException(plugin); } // Resolve the working directory. string workingDirectory = HostContext.GetDirectory(WellKnownDirectory.Work); ArgUtil.Directory(workingDirectory, nameof(workingDirectory)); // Agent.PluginHost string file = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), $"Agent.PluginHost{Util.IOUtil.ExeExtension}"); ArgUtil.File(file, $"Agent.PluginHost{Util.IOUtil.ExeExtension}"); // Agent.PluginHost's arguments string arguments = $"task \"{plugin}\""; // construct plugin context AgentTaskPluginExecutionContext pluginContext = new AgentTaskPluginExecutionContext { Inputs = inputs, Repositories = context.Repositories, Endpoints = context.Endpoints }; // variables foreach (var publicVar in runtimeVariables.Public) { pluginContext.Variables[publicVar.Key] = publicVar.Value; } foreach (var publicVar in runtimeVariables.Private) { pluginContext.Variables[publicVar.Key] = new VariableValue(publicVar.Value, true); } // task variables (used by wrapper task) foreach (var publicVar in context.TaskVariables.Public) { pluginContext.TaskVariables[publicVar.Key] = publicVar.Value; } foreach (var publicVar in context.TaskVariables.Private) { pluginContext.TaskVariables[publicVar.Key] = new VariableValue(publicVar.Value, true); } using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var redirectStandardIn = new InputQueue<string>(); redirectStandardIn.Enqueue(JsonUtility.ToString(pluginContext)); processInvoker.OutputDataReceived += outputHandler; processInvoker.ErrorDataReceived += outputHandler; // Execute the process. Exit code 0 should always be returned. // A non-zero exit code indicates infrastructural failure. // Task failure should be communicated over STDOUT using ## commands. await processInvoker.ExecuteAsync(workingDirectory: workingDirectory, fileName: file, arguments: arguments, environment: environment, requireExitCodeZero: true, outputEncoding: Encoding.UTF8, killProcessOnCancel: false, redirectStandardIn: redirectStandardIn, cancellationToken: context.CancellationToken); } } public void ProcessCommand(IExecutionContext context, Command command) { // queue async command task to run agent plugin. context.Debug($"Process {command.Area}.{command.Event} command through agent plugin in backend."); if (!_supportedLoggingCommands.ContainsKey(command.Area) || !_supportedLoggingCommands[command.Area].ContainsKey(command.Event)) { throw new NotSupportedException(command.ToString()); } var plugin = _supportedLoggingCommands[command.Area][command.Event]; ArgUtil.NotNull(plugin, nameof(plugin)); ArgUtil.NotNullOrEmpty(plugin.DisplayName, nameof(plugin.DisplayName)); // construct plugin context AgentCommandPluginExecutionContext pluginContext = new AgentCommandPluginExecutionContext { Data = command.Data, Properties = command.Properties, Endpoints = context.Endpoints, }; // variables foreach (var publicVar in context.Variables.Public) { pluginContext.Variables[publicVar.Key] = publicVar.Value; } foreach (var publicVar in context.Variables.Private) { pluginContext.Variables[publicVar.Key] = new VariableValue(publicVar.Value, true); } var commandContext = HostContext.CreateService<IAsyncCommandContext>(); commandContext.InitializeCommandContext(context, plugin.DisplayName); commandContext.Task = ProcessPluginCommandAsync(commandContext, pluginContext, plugin.CommandPluginTypeName, command, context.CancellationToken); context.AsyncCommands.Add(commandContext); } private async Task ProcessPluginCommandAsync(IAsyncCommandContext context, AgentCommandPluginExecutionContext pluginContext, string plugin, Command command, CancellationToken token) { // Resolve the working directory. string workingDirectory = HostContext.GetDirectory(WellKnownDirectory.Work); ArgUtil.Directory(workingDirectory, nameof(workingDirectory)); // Agent.PluginHost string file = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), $"Agent.PluginHost{Util.IOUtil.ExeExtension}"); // Agent.PluginHost's arguments string arguments = $"command \"{plugin}\""; // Execute the process. Exit code 0 should always be returned. // A non-zero exit code indicates infrastructural failure. // Any content coming from STDERR will indicate the command process failed. // We can't use ## command for plugin to communicate, since we are already processing ## command using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { object stderrLock = new object(); List<string> stderr = new List<string>(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { context.Output(e.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (stderrLock) { stderr.Add(e.Data); }; }; var redirectStandardIn = new InputQueue<string>(); redirectStandardIn.Enqueue(JsonUtility.ToString(pluginContext)); int returnCode = await processInvoker.ExecuteAsync(workingDirectory: workingDirectory, fileName: file, arguments: arguments, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, redirectStandardIn: redirectStandardIn, cancellationToken: token); if (returnCode != 0) { context.Output(string.Join(Environment.NewLine, stderr)); throw new ProcessExitCodeException(returnCode, file, arguments); } else if (stderr.Count > 0) { throw new InvalidOperationException(string.Join(Environment.NewLine, stderr)); } else { // Everything works fine. // Return code is 0. // No STDERR comes out. } } } private Assembly ResolveAssembly(AssemblyLoadContext context, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return context.LoadFromAssemblyPath(Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), assemblyFilename)); } } public class AgentCommandPluginInfo { public string CommandPluginTypeName { get; set; } public string DisplayName { get; set; } } public class AgentTaskPluginInfo { public string TaskPluginPreJobTypeName { get; set; } public string TaskPluginTypeName { get; set; } public string TaskPluginPostJobTypeName { get; set; } } }
48.403561
247
0.592141
[ "MIT" ]
ShreyasRmsft/azure-pipelines-agent
src/Agent.Worker/AgentPluginManager.cs
16,312
C#
namespace UglyToad.PdfPig.Fonts.Type1.CharStrings.Commands.PathConstruction { using Geometry; /// <summary> /// Vertical move to. Moves relative to the current point. /// </summary> internal static class VMoveToCommand { public const string Name = "vmoveto"; public static readonly byte First = 4; public static readonly byte? Second = null; public static bool TakeFromStackBottom { get; } = true; public static bool ClearsOperandStack { get; } = true; public static LazyType1Command Lazy { get; } = new LazyType1Command(Name, Run); public static void Run(Type1BuildCharContext context) { var deltaY = context.Stack.PopBottom(); if (context.IsFlexing) { // TODO: flex commands } else { var y = context.CurrentPosition.Y + deltaY; var x = context.CurrentPosition.X; context.CurrentPosition = new PdfPoint(x, y); context.Path.MoveTo(x, y); } context.Stack.Clear(); } } }
28.146341
87
0.566724
[ "Apache-2.0" ]
BenyErnest/PdfPig
src/UglyToad.PdfPig/Fonts/Type1/CharStrings/Commands/PathConstruction/VMoveToCommand.cs
1,156
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; namespace SuperRocket.Angular2Core.MultiTenancy.Dto { [AutoMapFrom(typeof(Tenant))] public class TenantListDto : EntityDto { public string TenancyName { get; set; } public string Name { get; set; } } }
22.538462
51
0.68942
[ "MIT" ]
AccentureRapid/SuperRocket.Angular2Core
aspnet-core/src/SuperRocket.Angular2Core.Application/MultiTenancy/Dto/TenantListDto.cs
293
C#
using System; using System.IO; using System.Text.RegularExpressions; using System.Web; namespace Utilities { public static class HttpPostedFileExtensions { public const int ImageMinimumBytes = 512; public static bool IsImage(this HttpPostedFileBase postedFile) { //------------------------------------------- // Check the image mime types //------------------------------------------- if (postedFile.ContentType.ToLower() != "image/jpg" && postedFile.ContentType.ToLower() != "image/jpeg" && postedFile.ContentType.ToLower() != "image/pjpeg" && postedFile.ContentType.ToLower() != "image/gif" && postedFile.ContentType.ToLower() != "image/x-png" && postedFile.ContentType.ToLower() != "image/png") { return false; } //------------------------------------------- // Check the image extension //------------------------------------------- if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg" && Path.GetExtension(postedFile.FileName).ToLower() != ".png" && Path.GetExtension(postedFile.FileName).ToLower() != ".gif" && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg") { return false; } //------------------------------------------- // Attempt to read the file and check the first bytes //------------------------------------------- try { if (!postedFile.InputStream.CanRead) { return false; } if (postedFile.ContentLength < ImageMinimumBytes) { return false; } byte[] buffer = new byte[512]; postedFile.InputStream.Read(buffer, 0, 512); string content = System.Text.Encoding.UTF8.GetString(buffer); if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline)) { return false; } } catch (Exception) { return false; } //------------------------------------------- // Try to instantiate new Bitmap, if .NET will throw exception // we can assume that it's not a valid image //------------------------------------------- try { using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream)) { } } catch (Exception) { return false; } finally { postedFile.InputStream.Position = 0; } return true; } } }
27.133333
128
0.546683
[ "MIT" ]
nzhul/garderob
App/App.Utilities/HttpPostedFileExtensions.cs
2,444
C#
namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS { public sealed partial class Vic { private int _borderPixel; private int _bufferPixel; private int _pixel; private int _pixelCounter; private int _pixelOwner; private Sprite _spr; private int _sprData; private int _sprIndex; private int _sprPixel; private int _srColor0; private int _srColor1; private int _srColor2; private int _srColor3; private int _srData1; private int _srColorEnable; private int _videoMode; private int _borderOnShiftReg; private const int VideoMode000 = 0; private const int VideoMode001 = 1; private const int VideoMode010 = 2; private const int VideoMode011 = 3; private const int VideoMode100 = 4; private const int VideoModeInvalid = -1; private const int SrMask1 = 0x40000; private const int SrSpriteMask = SrSpriteMask2; private const int SrSpriteMask1 = 0x400000; private const int SrSpriteMask2 = SrSpriteMask1 << 1; private const int SrSpriteMask3 = SrSpriteMask1 | SrSpriteMask2; private const int SrSpriteMaskMc = SrSpriteMask3; private void Render() { if (_rasterX == _hblankEndCheckXRaster) _hblank = false; if (_rasterX == _hblankStartCheckXRaster) _hblank = true; _renderEnabled = !_hblank && !_vblank; _pixelCounter = 4; while (--_pixelCounter >= 0) { #region PRE-RENDER BORDER // check left border if (_borderCheckLEnable && (_rasterX == _borderL)) { if (_rasterLine == _borderB) _borderOnVertical = true; if (_cycle == _totalCycles && _rasterLine == _borderT && _displayEnable) _borderOnVertical = false; if (!_borderOnVertical) _borderOnMain = false; } // check right border if (_borderCheckREnable && (_rasterX == _borderR)) _borderOnMain = true; #endregion // render graphics if ((_srColorEnable & SrMask1) != 0) { _pixel = ((_srColor0 & SrMask1) >> 18) | ((_srColor1 & SrMask1) >> 17) | ((_srColor2 & SrMask1) >> 16) | ((_srColor3 & SrMask1) >> 15); } else { switch (((_srColor0 & SrMask1) >> 18) | ((_srColor1 & SrMask1) >> 17)) { case 1: _pixel = _idle ? 0 : _backgroundColor1; break; case 2: _pixel = _idle ? 0 : _backgroundColor2; break; case 3: _pixel = _idle ? 0 : _backgroundColor3; break; default: _pixel = _backgroundColor0; break; } } // render sprites _pixelOwner = -1; for (_sprIndex = 0; _sprIndex < 8; _sprIndex++) { _spr = _sprites[_sprIndex]; _sprData = 0; _sprPixel = _pixel; if (_spr.X == _rasterX) { _spr.ShiftEnable = _spr.Display; _spr.XCrunch = !_spr.XExpand; _spr.MulticolorCrunch = false; } else { _spr.XCrunch |= !_spr.XExpand; } if (_spr.ShiftEnable) // sprite rule 6 { if (_spr.Multicolor) { _sprData = _spr.Sr & SrSpriteMaskMc; if (_spr.MulticolorCrunch && _spr.XCrunch && !_rasterXHold) { if (_spr.Loaded == 0) { _spr.ShiftEnable = false; } _spr.Sr <<= 2; _spr.Loaded >>= 2; } _spr.MulticolorCrunch ^= _spr.XCrunch; } else { _sprData = _spr.Sr & SrSpriteMask; if (_spr.XCrunch && !_rasterXHold) { if (_spr.Loaded == 0) { _spr.ShiftEnable = false; } _spr.Sr <<= 1; _spr.Loaded >>= 1; } } _spr.XCrunch ^= _spr.XExpand; if (_sprData != 0) { // sprite-sprite collision if (_pixelOwner < 0) { switch (_sprData) { case SrSpriteMask1: _sprPixel = _spriteMulticolor0; break; case SrSpriteMask2: _sprPixel = _spr.Color; break; case SrSpriteMask3: _sprPixel = _spriteMulticolor1; break; } _pixelOwner = _sprIndex; } else { if (!_borderOnVertical) { _spr.CollideSprite = true; _sprites[_pixelOwner].CollideSprite = true; _intSpriteCollision = true; } } // sprite-data collision if (!_borderOnVertical && (_srData1 & SrMask1) != 0) { _spr.CollideData = true; _intSpriteDataCollision = true; } // sprite priority logic if (_spr.Priority) { _pixel = (_srData1 & SrMask1) != 0 ? _pixel : _sprPixel; } else { _pixel = _sprPixel; } } } } #region POST-RENDER BORDER // border doesn't work with the background buffer _borderPixel = _pixBorderBuffer[_pixBufferBorderIndex]; _pixBorderBuffer[_pixBufferBorderIndex] = _borderColor; #endregion // plot pixel if within viewing area if (_renderEnabled) { _bufferPixel = (_borderOnShiftReg & 0x80000) != 0 ? _borderPixel : _pixBuffer[_pixBufferIndex]; _buf[_bufOffset] = Palette[_bufferPixel]; _bufOffset++; if (_bufOffset == _bufLength) _bufOffset = 0; } _borderOnShiftReg <<= 1; _borderOnShiftReg |= (_borderOnVertical || _borderOnMain) ? 1 : 0; _pixBuffer[_pixBufferIndex] = _pixel; _pixBufferIndex++; _pixBufferBorderIndex++; if (!_rasterXHold) _rasterX++; _srColor0 <<= 1; _srColor1 <<= 1; _srColor2 <<= 1; _srColor3 <<= 1; _srData1 <<= 1; _srColorEnable <<= 1; } if (_pixBufferBorderIndex >= PixBorderBufferSize) { _pixBufferBorderIndex = 0; } if (_pixBufferIndex >= PixBufferSize) { _pixBufferIndex = 0; } } } }
24.895397
101
0.566218
[ "MIT" ]
Diefool/BizHawk
BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Render.cs
5,952
C#
using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; namespace Dfe.Spi.HistoricalDataPreparer.Infrastructure.SpiApi { internal static class OAuthAuthenticator { internal static async Task<string> GetBearerTokenAsync( string tokenEndpoint, string clientId, string clientSecret, string resource, CancellationToken cancellationToken) { var token = await GetTokenFromEndpointAsync(tokenEndpoint, clientId, clientSecret, resource, cancellationToken); return token.AccessToken; } private static async Task<OAuthToken> GetTokenFromEndpointAsync( string tokenEndpoint, string clientId, string clientSecret, string resource, CancellationToken cancellationToken) { using var httpClient = new HttpClient(); var body = "grant_type=client_credentials" + $"&client_id={HttpUtility.UrlEncode(clientId)}" + $"&client_secret={HttpUtility.UrlEncode(clientSecret)}" + $"&resource={HttpUtility.UrlEncode(resource)}"; var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync(tokenEndpoint, content, cancellationToken); if (!response.IsSuccessStatusCode) { throw new OAuthException($"Error calling token endpoint. Status code = {(int)response.StatusCode}"); } var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<OAuthToken>(json); } } internal class OAuthToken { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("expires_in")] public long ExpiresIn { get; set; } } }
37.127273
124
0.624388
[ "MIT" ]
DFE-Digital/spi-tools
HistoricalDataPreparer/src/Dfe.Spi.HistoricalDataPreparer.Infrastructure.SpiApi/OAuthAuthenticator.cs
2,042
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using SignalR.Hubs; namespace SignalR.Samples.Hubs.ConnectDisconnect { public class Status : Hub, IDisconnect, IConnected { public Task Disconnect() { return Clients.leave(Context.ConnectionId, DateTime.Now.ToString()); } public Task Connect(IEnumerable<string> groups) { return Clients.joined(Context.ConnectionId, DateTime.Now.ToString()); } public Task Reconnect(IEnumerable<string> groups) { return Clients.rejoined(Context.ConnectionId, DateTime.Now.ToString()); } } }
27
83
0.651852
[ "MIT" ]
cburgdorf/SignalR
SignalR.Hosting.AspNet.Samples/Hubs/ConnectDisconnect/Status.cs
677
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. using System; using System.Diagnostics.CodeAnalysis; namespace TheGrapho.Parser.Syntax { public sealed class DotStatementSyntax : DotSyntax { public DotStatementSyntax([DisallowNull] DotSyntax statement) : base( SyntaxKind.DotStatement, statement?.Start ?? 0, statement?.FullWidth ?? 0, new[] {statement}) { Statement = statement ?? throw new ArgumentNullException(nameof(statement)); } [NotNull] public DotSyntax Statement { get; } [return: NotNull] public override string ToString() => $"{base.ToString()}, {nameof(Statement)}: {Statement}"; [return: MaybeNull] public override TResult Accept<TResult>([DisallowNull] DotSyntaxVisitor<TResult> syntaxVisitor) { if (syntaxVisitor == null) throw new ArgumentNullException(nameof(syntaxVisitor)); return syntaxVisitor.VisitStatement(this); } public override void Accept([DisallowNull] DotSyntaxVisitor syntaxVisitor) { if (syntaxVisitor == null) throw new ArgumentNullException(nameof(syntaxVisitor)); syntaxVisitor.VisitStatement(this); } } }
36.538462
103
0.651228
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ssyp-ru/ssyp-ws09
TheGrapho.Parser/Syntax/DotStatementSyntax.cs
1,427
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Globalization; namespace Crypto { internal static class Program { static void Main(string[] args) { int argsI; string command; Dictionary<string, string> dictionary = ReadConsoleArguments(args, out argsI, out command); if (string.IsNullOrEmpty(command) || command.Equals("Blake2B", StringComparison.OrdinalIgnoreCase)) { Blake2B(dictionary); return; } if (command.Equals("Blake2S", StringComparison.OrdinalIgnoreCase)) { Blake2S(dictionary); return; } string format = " HELP: ./Blake2B.exe --In=./Hallo.txt -- Blake2B{0}" + " ./Blake2B.exe [ --option=value ] [ -- ] [ command ]{0}" + "{0}" + " Option: --In=./FileName.txt is required{0}" + "{0}" + " Commands: Blake2B (Default), Blake2S"; Console.WriteLine(format, Environment.NewLine); } public static void Blake2B(IDictionary<string, string> dictionary) { FileInfo inFile = null; if (dictionary.ContainsKey("In")) if (File.Exists(dictionary["In"])) inFile = new FileInfo(dictionary["In"]); if (inFile == null || !inFile.Exists) { Console.WriteLine("Blake2B: --In file not found"); return; } // using (var hash = new Blake2B()) value = hash.ComputeHash(bytes); byte[] hashValue; using (var fileIn = new FileStream(inFile.FullName, FileMode.Open)) using (var hash = new Blake2B()) { var buffer = new byte[512]; int bufferL, fileI = 0; long fileL = inFile.Length; do { bufferL = fileIn.Read(buffer, 0, buffer.Length); if (bufferL > 0) { hash.Core(buffer, 0, bufferL); } fileL -= bufferL; fileI += bufferL; } while(0 < fileL); hashValue = hash.Final(); } foreach (byte v in hashValue) Console.Write("{0:x2}", v); Console.WriteLine(); } public static void Blake2S(IDictionary<string, string> dictionary) { FileInfo inFile = null; if (dictionary.ContainsKey("In")) if (File.Exists(dictionary["In"])) inFile = new FileInfo(dictionary["In"]); if (inFile == null || !inFile.Exists) { Console.WriteLine("Blake2S: --In file not found"); return; } // using (var hash = new Blake2S()) value = hash.ComputeHash(bytes); byte[] hashValue; using (var fileIn = new FileStream(inFile.FullName, FileMode.Open)) using (var hash = new Blake2S()) { var buffer = new byte[256]; int bufferL, fileI = 0; long fileL = inFile.Length; do { bufferL = fileIn.Read(buffer, 0, buffer.Length); if (bufferL > 0) { hash.Core(buffer, 0, bufferL); } fileL -= bufferL; fileI += bufferL; } while(0 < fileL); hashValue = hash.Final(); } foreach (byte v in hashValue) Console.Write("{0:x2}", v); Console.WriteLine(); } static Dictionary<string, string> ReadConsoleArguments(string[] args, out int argsI, out string command) { argsI = 0; int nameI, dashs; string arg, argName; var dictionary = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase); do { if (args.Length == 0) break; arg = args[argsI]; nameI = arg.IndexOf('='); dashs = arg.StartsWith("--") ? 2 : (arg.StartsWith("-") ? 1 : 0); if (dashs > 0) { if (arg.Length == dashs) { break; } if (nameI > -1) { argName = arg.Substring(dashs, nameI - dashs); arg = arg.Substring(nameI + 1); dictionary.Add(argName, arg); continue; } argName = arg.Substring(dashs); dictionary.Add(argName, string.Empty); continue; } --argsI; break; } while (++argsI < args.Length); command = string.Empty; if (argsI + 1 < args.Length) { command = args[++argsI]; } /**/ return dictionary; } } }
22.976471
106
0.604199
[ "CC0-1.0" ]
metadings/Blake2.cs
Program.cs
3,908
C#
using System.Collections.Generic; namespace Model { public class Lodging { public int LodgingId { get; set; } public string Name { get; set; } public string Owner { get; set; } public bool IsResort { get; set; } public decimal MilesFromNearestAirport { get; set; } public int DestinationId { get; set; } public Destination Destination { get; set; } public List<InternetSpecial> InternetSpecials { get; set; } public Person PrimaryContact { get; set; } public Person SecondaryContact { get; set; } } }
28.894737
63
0.675774
[ "MIT" ]
julielerman/ProgrammingEntityFrameworkBook
Programming EF Code First/chapter4/Chapter4/BAGA_FluentAPI/Model/Lodging.cs
551
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.HttpSys.Internal; namespace Microsoft.AspNetCore.Server.HttpSys { internal sealed class Request { private NativeRequestContext _nativeRequestContext; private X509Certificate2 _clientCert; // TODO: https://github.com/aspnet/HttpSysServer/issues/231 // private byte[] _providedTokenBindingId; // private byte[] _referredTokenBindingId; private BoundaryType _contentBoundaryType; private long? _contentLength; private RequestStream _nativeStream; private AspNetCore.HttpSys.Internal.SocketAddress _localEndPoint; private AspNetCore.HttpSys.Internal.SocketAddress _remoteEndPoint; private IReadOnlyDictionary<int, ReadOnlyMemory<byte>> _requestInfo; private bool _isDisposed = false; internal Request(RequestContext requestContext, NativeRequestContext nativeRequestContext) { // TODO: Verbose log RequestContext = requestContext; _nativeRequestContext = nativeRequestContext; _contentBoundaryType = BoundaryType.None; RequestId = nativeRequestContext.RequestId; UConnectionId = nativeRequestContext.ConnectionId; SslStatus = nativeRequestContext.SslStatus; KnownMethod = nativeRequestContext.VerbId; Method = _nativeRequestContext.GetVerb(); RawUrl = nativeRequestContext.GetRawUrl(); var cookedUrl = nativeRequestContext.GetCookedUrl(); QueryString = cookedUrl.GetQueryString() ?? string.Empty; var rawUrlInBytes = _nativeRequestContext.GetRawUrlInBytes(); var originalPath = RequestUriBuilder.DecodeAndUnescapePath(rawUrlInBytes); // 'OPTIONS * HTTP/1.1' if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawUrl, "*", StringComparison.Ordinal)) { PathBase = string.Empty; Path = string.Empty; } else if (requestContext.Server.RequestQueue.Created) { var prefix = requestContext.Server.Options.UrlPrefixes.GetPrefix((int)nativeRequestContext.UrlContext); if (originalPath.Length == prefix.PathWithoutTrailingSlash.Length) { // They matched exactly except for the trailing slash. PathBase = originalPath; Path = string.Empty; } else { // url: /base/path, prefix: /base/, base: /base, path: /path // url: /, prefix: /, base: , path: / PathBase = originalPath.Substring(0, prefix.PathWithoutTrailingSlash.Length); // Preserve the user input casing Path = originalPath.Substring(prefix.PathWithoutTrailingSlash.Length); } } else { // When attaching to an existing queue, the UrlContext hint may not match our configuration. Search manualy. if (requestContext.Server.Options.UrlPrefixes.TryMatchLongestPrefix(IsHttps, cookedUrl.GetHost(), originalPath, out var pathBase, out var path)) { PathBase = pathBase; Path = path; } else { PathBase = string.Empty; Path = originalPath; } } ProtocolVersion = _nativeRequestContext.GetVersion(); Headers = new RequestHeaders(_nativeRequestContext); User = _nativeRequestContext.GetUser(); if (IsHttps) { GetTlsHandshakeResults(); } // GetTlsTokenBindingInfo(); TODO: https://github.com/aspnet/HttpSysServer/issues/231 // Finished directly accessing the HTTP_REQUEST structure. _nativeRequestContext.ReleasePins(); // TODO: Verbose log parameters } internal ulong UConnectionId { get; } // No ulongs in public APIs... public long ConnectionId => (long)UConnectionId; internal ulong RequestId { get; } private SslStatus SslStatus { get; } private RequestContext RequestContext { get; } // With the leading ?, if any public string QueryString { get; } public long? ContentLength { get { if (_contentBoundaryType == BoundaryType.None) { string transferEncoding = Headers[HttpKnownHeaderNames.TransferEncoding]; if (string.Equals("chunked", transferEncoding?.Trim(), StringComparison.OrdinalIgnoreCase)) { _contentBoundaryType = BoundaryType.Chunked; } else { string length = Headers[HttpKnownHeaderNames.ContentLength]; long value; if (length != null && long.TryParse(length.Trim(), NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out value)) { _contentBoundaryType = BoundaryType.ContentLength; _contentLength = value; } else { _contentBoundaryType = BoundaryType.Invalid; } } } return _contentLength; } } public RequestHeaders Headers { get; } internal HttpApiTypes.HTTP_VERB KnownMethod { get; } internal bool IsHeadMethod => KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbHEAD; public string Method { get; } public Stream Body => EnsureRequestStream() ?? Stream.Null; private RequestStream EnsureRequestStream() { if (_nativeStream == null && HasEntityBody) { _nativeStream = new RequestStream(RequestContext); } return _nativeStream; } public bool HasRequestBodyStarted => _nativeStream?.HasStarted ?? false; public long? MaxRequestBodySize { get => EnsureRequestStream()?.MaxSize; set { EnsureRequestStream(); if (_nativeStream != null) { _nativeStream.MaxSize = value; } } } public string PathBase { get; } public string Path { get; } public bool IsHttps => SslStatus != SslStatus.Insecure; public string RawUrl { get; } public Version ProtocolVersion { get; } public bool HasEntityBody { get { // accessing the ContentLength property delay creates _contentBoundaryType return (ContentLength.HasValue && ContentLength.Value > 0 && _contentBoundaryType == BoundaryType.ContentLength) || _contentBoundaryType == BoundaryType.Chunked; } } private AspNetCore.HttpSys.Internal.SocketAddress RemoteEndPoint { get { if (_remoteEndPoint == null) { _remoteEndPoint = _nativeRequestContext.GetRemoteEndPoint(); } return _remoteEndPoint; } } private AspNetCore.HttpSys.Internal.SocketAddress LocalEndPoint { get { if (_localEndPoint == null) { _localEndPoint = _nativeRequestContext.GetLocalEndPoint(); } return _localEndPoint; } } // TODO: Lazy cache? public IPAddress RemoteIpAddress => RemoteEndPoint.GetIPAddress(); public IPAddress LocalIpAddress => LocalEndPoint.GetIPAddress(); public int RemotePort => RemoteEndPoint.GetPort(); public int LocalPort => LocalEndPoint.GetPort(); public string Scheme => IsHttps ? Constants.HttpsScheme : Constants.HttpScheme; // HTTP.Sys allows you to upgrade anything to opaque unless content-length > 0 or chunked are specified. internal bool IsUpgradable => !HasEntityBody && ComNetOS.IsWin8orLater; internal WindowsPrincipal User { get; } public SslProtocols Protocol { get; private set; } public CipherAlgorithmType CipherAlgorithm { get; private set; } public int CipherStrength { get; private set; } public HashAlgorithmType HashAlgorithm { get; private set; } public int HashStrength { get; private set; } public ExchangeAlgorithmType KeyExchangeAlgorithm { get; private set; } public int KeyExchangeStrength { get; private set; } public IReadOnlyDictionary<int, ReadOnlyMemory<byte>> RequestInfo { get { if (_requestInfo == null) { _requestInfo = _nativeRequestContext.GetRequestInfo(); } return _requestInfo; } } private void GetTlsHandshakeResults() { var handshake = _nativeRequestContext.GetTlsHandshake(); Protocol = handshake.Protocol; // The OS considers client and server TLS as different enum values. SslProtocols choose to combine those for some reason. // We need to fill in the client bits so the enum shows the expected protocol. // https://docs.microsoft.com/windows/desktop/api/schannel/ns-schannel-_secpkgcontext_connectioninfo // Compare to https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,8905d1bf17729de3 #pragma warning disable CS0618 // Type or member is obsolete if ((Protocol & SslProtocols.Ssl2) != 0) { Protocol |= SslProtocols.Ssl2; } if ((Protocol & SslProtocols.Ssl3) != 0) { Protocol |= SslProtocols.Ssl3; } #pragma warning restore CS0618 // Type or member is obsolete if ((Protocol & SslProtocols.Tls) != 0) { Protocol |= SslProtocols.Tls; } if ((Protocol & SslProtocols.Tls11) != 0) { Protocol |= SslProtocols.Tls11; } if ((Protocol & SslProtocols.Tls12) != 0) { Protocol |= SslProtocols.Tls12; } CipherAlgorithm = handshake.CipherType; CipherStrength = (int)handshake.CipherStrength; HashAlgorithm = handshake.HashType; HashStrength = (int)handshake.HashStrength; KeyExchangeAlgorithm = handshake.KeyExchangeType; KeyExchangeStrength = (int)handshake.KeyExchangeStrength; } // Populates the client certificate. The result may be null if there is no client cert. // TODO: Does it make sense for this to be invoked multiple times (e.g. renegotiate)? Client and server code appear to // enable this, but it's unclear what Http.Sys would do. public async Task<X509Certificate2> GetClientCertificateAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (SslStatus == SslStatus.Insecure) { // Non-SSL return null; } // TODO: Verbose log if (_clientCert != null) { return _clientCert; } cancellationToken.ThrowIfCancellationRequested(); var certLoader = new ClientCertLoader(RequestContext, cancellationToken); try { await certLoader.LoadClientCertificateAsync().SupressContext(); // Populate the environment. if (certLoader.ClientCert != null) { _clientCert = certLoader.ClientCert; } // TODO: Expose errors and exceptions? } catch (Exception) { if (certLoader != null) { certLoader.Dispose(); } throw; } return _clientCert; } /* TODO: https://github.com/aspnet/WebListener/issues/231 private byte[] GetProvidedTokenBindingId() { return _providedTokenBindingId; } private byte[] GetReferredTokenBindingId() { return _referredTokenBindingId; } */ // Only call from the constructor so we can directly access the native request blob. // This requires Windows 10 and the following reg key: // Set Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters to Value: EnableSslTokenBinding = 1 [DWORD] // Then for IE to work you need to set these: // Key: HKLM\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING // Value: "iexplore.exe"=dword:0x00000001 // Key: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING // Value: "iexplore.exe"=dword:00000001 // TODO: https://github.com/aspnet/WebListener/issues/231 // TODO: https://github.com/aspnet/WebListener/issues/204 Move to NativeRequestContext /* private unsafe void GetTlsTokenBindingInfo() { var nativeRequest = (HttpApi.HTTP_REQUEST_V2*)_nativeRequestContext.RequestBlob; for (int i = 0; i < nativeRequest->RequestInfoCount; i++) { var pThisInfo = &nativeRequest->pRequestInfo[i]; if (pThisInfo->InfoType == HttpApi.HTTP_REQUEST_INFO_TYPE.HttpRequestInfoTypeSslTokenBinding) { var pTokenBindingInfo = (HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO*)pThisInfo->pInfo; _providedTokenBindingId = TokenBindingUtil.GetProvidedTokenIdFromBindingInfo(pTokenBindingInfo, out _referredTokenBindingId); } } } */ internal uint GetChunks(ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size) { return _nativeRequestContext.GetChunks(ref dataChunkIndex, ref dataChunkOffset, buffer, offset, size); } // should only be called from RequestContext internal void Dispose() { // TODO: Verbose log _isDisposed = true; _nativeRequestContext.Dispose(); (User?.Identity as WindowsIdentity)?.Dispose(); if (_nativeStream != null) { _nativeStream.Dispose(); } } private void CheckDisposed() { if (_isDisposed) { throw new ObjectDisposedException(this.GetType().FullName); } } internal void SwitchToOpaqueMode() { if (_nativeStream == null) { _nativeStream = new RequestStream(RequestContext); } _nativeStream.SwitchToOpaqueMode(); } } }
36.841743
160
0.576916
[ "Apache-2.0" ]
1426463237/AspNetCore
src/Servers/HttpSys/src/RequestProcessing/Request.cs
16,063
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 securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// BatchEnableStandards Request Marshaller /// </summary> public class BatchEnableStandardsRequestMarshaller : IMarshaller<IRequest, BatchEnableStandardsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((BatchEnableStandardsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(BatchEnableStandardsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SecurityHub"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-10-26"; request.HttpMethod = "POST"; string uriResourcePath = "/standards/register"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetStandardsSubscriptionRequests()) { context.Writer.WritePropertyName("StandardsSubscriptionRequests"); context.Writer.WriteArrayStart(); foreach(var publicRequestStandardsSubscriptionRequestsListValue in publicRequest.StandardsSubscriptionRequests) { context.Writer.WriteObjectStart(); var marshaller = StandardsSubscriptionRequestMarshaller.Instance; marshaller.Marshall(publicRequestStandardsSubscriptionRequestsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static BatchEnableStandardsRequestMarshaller _instance = new BatchEnableStandardsRequestMarshaller(); internal static BatchEnableStandardsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static BatchEnableStandardsRequestMarshaller Instance { get { return _instance; } } } }
37.345133
155
0.635308
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/BatchEnableStandardsRequestMarshaller.cs
4,220
C#
namespace ServicesCars { partial class FrmCoorporacao { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmCoorporacao)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); this.xuiFlatMenuStrip1 = new XanderUI.XUIFlatMenuStrip(); this.empresasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.adicionarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editarToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.FacturasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CrriarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.listaDeFaturasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panel2 = new System.Windows.Forms.Panel(); this.pcClose = new System.Windows.Forms.PictureBox(); this.dgvFull = new System.Windows.Forms.DataGridView(); this.pcRefresh = new System.Windows.Forms.PictureBox(); this.txtPesquisar = new System.Windows.Forms.TextBox(); this.xuiFlatMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pcClose)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvFull)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pcRefresh)).BeginInit(); this.SuspendLayout(); // // xuiFlatMenuStrip1 // this.xuiFlatMenuStrip1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(42)))), ((int)(((byte)(58)))), ((int)(((byte)(86))))); this.xuiFlatMenuStrip1.Font = new System.Drawing.Font("Segoe UI", 11F); this.xuiFlatMenuStrip1.HoverBackColor = System.Drawing.Color.RoyalBlue; this.xuiFlatMenuStrip1.HoverTextColor = System.Drawing.Color.White; this.xuiFlatMenuStrip1.ItemBackColor = System.Drawing.Color.RoyalBlue; this.xuiFlatMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.empresasToolStripMenuItem, this.FacturasToolStripMenuItem}); this.xuiFlatMenuStrip1.Location = new System.Drawing.Point(0, 0); this.xuiFlatMenuStrip1.Name = "xuiFlatMenuStrip1"; this.xuiFlatMenuStrip1.SelectedBackColor = System.Drawing.Color.RoyalBlue; this.xuiFlatMenuStrip1.SelectedTextColor = System.Drawing.Color.White; this.xuiFlatMenuStrip1.SeperatorColor = System.Drawing.Color.White; this.xuiFlatMenuStrip1.Size = new System.Drawing.Size(781, 28); this.xuiFlatMenuStrip1.TabIndex = 27; this.xuiFlatMenuStrip1.Text = "xuiFlatMenuStrip1"; this.xuiFlatMenuStrip1.TextColor = System.Drawing.Color.White; // // empresasToolStripMenuItem // this.empresasToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.adicionarToolStripMenuItem, this.editarToolStripMenuItem1}); this.empresasToolStripMenuItem.ForeColor = System.Drawing.Color.White; this.empresasToolStripMenuItem.Name = "empresasToolStripMenuItem"; this.empresasToolStripMenuItem.Size = new System.Drawing.Size(84, 24); this.empresasToolStripMenuItem.Text = "Empresas"; // // adicionarToolStripMenuItem // this.adicionarToolStripMenuItem.ForeColor = System.Drawing.Color.White; this.adicionarToolStripMenuItem.Name = "adicionarToolStripMenuItem"; this.adicionarToolStripMenuItem.Size = new System.Drawing.Size(180, 24); this.adicionarToolStripMenuItem.Text = "Adicionar"; this.adicionarToolStripMenuItem.Click += new System.EventHandler(this.AdicionarToolStripMenuItem_Click); // // editarToolStripMenuItem1 // this.editarToolStripMenuItem1.ForeColor = System.Drawing.Color.White; this.editarToolStripMenuItem1.Name = "editarToolStripMenuItem1"; this.editarToolStripMenuItem1.Size = new System.Drawing.Size(180, 24); this.editarToolStripMenuItem1.Text = "Editar"; this.editarToolStripMenuItem1.Click += new System.EventHandler(this.EditarToolStripMenuItem1_Click); // // FacturasToolStripMenuItem // this.FacturasToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.CrriarToolStripMenuItem, this.listaDeFaturasToolStripMenuItem}); this.FacturasToolStripMenuItem.ForeColor = System.Drawing.Color.White; this.FacturasToolStripMenuItem.Name = "FacturasToolStripMenuItem"; this.FacturasToolStripMenuItem.Size = new System.Drawing.Size(74, 24); this.FacturasToolStripMenuItem.Text = "Facturas"; this.FacturasToolStripMenuItem.Click += new System.EventHandler(this.FacturasToolStripMenuItem_Click); // // CrriarToolStripMenuItem // this.CrriarToolStripMenuItem.ForeColor = System.Drawing.Color.White; this.CrriarToolStripMenuItem.Name = "CrriarToolStripMenuItem"; this.CrriarToolStripMenuItem.Size = new System.Drawing.Size(178, 24); this.CrriarToolStripMenuItem.Text = "Criar"; this.CrriarToolStripMenuItem.Click += new System.EventHandler(this.CrriarToolStripMenuItem_Click); // // listaDeFaturasToolStripMenuItem // this.listaDeFaturasToolStripMenuItem.ForeColor = System.Drawing.Color.White; this.listaDeFaturasToolStripMenuItem.Name = "listaDeFaturasToolStripMenuItem"; this.listaDeFaturasToolStripMenuItem.Size = new System.Drawing.Size(178, 24); this.listaDeFaturasToolStripMenuItem.Text = "Lista de faturas"; this.listaDeFaturasToolStripMenuItem.Click += new System.EventHandler(this.ListaDeFaturasToolStripMenuItem_Click); // // panel2 // this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(42)))), ((int)(((byte)(58)))), ((int)(((byte)(86))))); this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(0, 442); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(781, 8); this.panel2.TabIndex = 56; // // pcClose // this.pcClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pcClose.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(42)))), ((int)(((byte)(58)))), ((int)(((byte)(86))))); this.pcClose.Cursor = System.Windows.Forms.Cursors.Hand; this.pcClose.Image = ((System.Drawing.Image)(resources.GetObject("pcClose.Image"))); this.pcClose.Location = new System.Drawing.Point(757, 6); this.pcClose.Name = "pcClose"; this.pcClose.Size = new System.Drawing.Size(15, 15); this.pcClose.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.pcClose.TabIndex = 28; this.pcClose.TabStop = false; this.pcClose.Click += new System.EventHandler(this.PcClose_Click); // // dgvFull // this.dgvFull.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgvFull.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dgvFull.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.dgvFull.BackgroundColor = System.Drawing.Color.WhiteSmoke; this.dgvFull.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dgvFull.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.SingleHorizontal; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(42)))), ((int)(((byte)(58)))), ((int)(((byte)(86))))); dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 11F); dataGridViewCellStyle3.ForeColor = System.Drawing.Color.White; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.RoyalBlue; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dgvFull.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle3; this.dgvFull.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle4.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle4.SelectionBackColor = System.Drawing.Color.RoyalBlue; dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dgvFull.DefaultCellStyle = dataGridViewCellStyle4; this.dgvFull.EnableHeadersVisualStyles = false; this.dgvFull.Location = new System.Drawing.Point(12, 73); this.dgvFull.Name = "dgvFull"; this.dgvFull.ReadOnly = true; this.dgvFull.Size = new System.Drawing.Size(757, 337); this.dgvFull.TabIndex = 61; this.dgvFull.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvFull_CellClick); this.dgvFull.DoubleClick += new System.EventHandler(this.DgvFull_DoubleClick); // // pcRefresh // this.pcRefresh.Cursor = System.Windows.Forms.Cursors.Hand; this.pcRefresh.Image = ((System.Drawing.Image)(resources.GetObject("pcRefresh.Image"))); this.pcRefresh.Location = new System.Drawing.Point(632, 40); this.pcRefresh.Name = "pcRefresh"; this.pcRefresh.Size = new System.Drawing.Size(24, 24); this.pcRefresh.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pcRefresh.TabIndex = 60; this.pcRefresh.TabStop = false; this.pcRefresh.Click += new System.EventHandler(this.FrmCoorporacao_Load); // // txtPesquisar // this.txtPesquisar.Font = new System.Drawing.Font("Segoe UI", 10F); this.txtPesquisar.Location = new System.Drawing.Point(12, 40); this.txtPesquisar.Name = "txtPesquisar"; this.txtPesquisar.Size = new System.Drawing.Size(614, 25); this.txtPesquisar.TabIndex = 59; this.txtPesquisar.TextChanged += new System.EventHandler(this.TxtPesquisar_TextChanged); // // FrmCoorporacao // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(781, 450); this.Controls.Add(this.dgvFull); this.Controls.Add(this.pcRefresh); this.Controls.Add(this.txtPesquisar); this.Controls.Add(this.panel2); this.Controls.Add(this.pcClose); this.Controls.Add(this.xuiFlatMenuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "FrmCoorporacao"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "FrmCoorporacao"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.FrmCoorporacao_Load); this.xuiFlatMenuStrip1.ResumeLayout(false); this.xuiFlatMenuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pcClose)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgvFull)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pcRefresh)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private XanderUI.XUIFlatMenuStrip xuiFlatMenuStrip1; private System.Windows.Forms.ToolStripMenuItem FacturasToolStripMenuItem; private System.Windows.Forms.PictureBox pcClose; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.ToolStripMenuItem CrriarToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem listaDeFaturasToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem empresasToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem adicionarToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editarToolStripMenuItem1; private System.Windows.Forms.DataGridView dgvFull; private System.Windows.Forms.PictureBox pcRefresh; public System.Windows.Forms.TextBox txtPesquisar; } }
61.465587
167
0.666908
[ "Apache-2.0" ]
RaulMatias7/ServicesCar
ServicesCars/Forms/FrmCoorporacao.Designer.cs
15,184
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WAVArrayifier.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.419355
152
0.566485
[ "MIT" ]
ajportelli/WAVArrayifier
WAVArrayifier/Properties/Settings.Designer.cs
1,100
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); private CompilationVerifier CompileAndVerify(CSharpTestSource src, string? expectedOutput = null) => base.CompileAndVerify(new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.Regular9, // init-only fails verification verify: Verification.Skipped); [Fact] public void GeneratedConstructor() { var comp = CreateCompilation(@"record C(int x, string y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var y = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, y.Type.SpecialType); Assert.Equal("y", y.Name); } [Fact] public void GeneratedConstructorDefaultValues() { var comp = CreateCompilation(@"record C<T>(int x, T t = default);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Arity); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(0, ctor.Arity); Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var t = ctor.Parameters[1]; Assert.Equal(c.TypeParameters[0], t.Type); Assert.Equal("t", t.Name); } [Fact] public void RecordExistingConstructor1() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, string b) { } }"); comp.VerifyDiagnostics( // (4,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, string b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(4, 12), // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, string b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[2]; Assert.Equal(2, ctor.ParameterCount); var a = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, a.Type.SpecialType); Assert.Equal("a", a.Name); var b = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, b.Type.SpecialType); Assert.Equal("b", b.Name); } [Fact] public void RecordExistingConstructor01() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, int b) // overload { } }"); comp.VerifyDiagnostics( // (4,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) // overload Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctors = c.GetMembers(".ctor"); Assert.Equal(3, ctors.Length); foreach (MethodSymbol ctor in ctors) { if (ctor.ParameterCount == 2) { var p1 = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, p1.Type.SpecialType); var p2 = ctor.Parameters[1]; if (ctor is SynthesizedRecordConstructor) { Assert.Equal("x", p1.Name); Assert.Equal("y", p2.Name); Assert.Equal(SpecialType.System_String, p2.Type.SpecialType); } else { Assert.Equal("a", p1.Name); Assert.Equal("b", p2.Name); Assert.Equal(SpecialType.System_Int32, p2.Type.SpecialType); } } else { Assert.Equal(1, ctor.ParameterCount); Assert.True(c.Equals(ctor.Parameters[0].Type, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void GeneratedProperties() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var x = (SourcePropertySymbolBase)c.GetProperty("x"); Assert.NotNull(x.GetMethod); Assert.Equal(MethodKind.PropertyGet, x.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.False(x.IsReadOnly); Assert.False(x.IsWriteOnly); Assert.False(x.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, x.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, x.ContainingType); Assert.Equal(c, x.ContainingSymbol); var backing = x.BackingField; Assert.Equal(x, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); var getAccessor = x.GetMethod; Assert.Equal(x, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); Assert.Equal(Accessibility.Public, getAccessor.DeclaredAccessibility); var setAccessor = x.SetMethod; Assert.Equal(x, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); var y = (SourcePropertySymbolBase)c.GetProperty("y"); Assert.NotNull(y.GetMethod); Assert.Equal(MethodKind.PropertyGet, y.GetMethod!.MethodKind); Assert.Equal(SpecialType.System_Int32, y.Type.SpecialType); Assert.False(y.IsReadOnly); Assert.False(y.IsWriteOnly); Assert.False(y.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, y.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, y.ContainingType); Assert.Equal(c, y.ContainingSymbol); backing = y.BackingField; Assert.Equal(y, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); getAccessor = y.GetMethod; Assert.Equal(y, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); setAccessor = y.SetMethod; Assert.Equal(y, setAccessor!.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); } [Fact] public void RecordEquals_01() { var comp = CreateCompilation(@" record C(int X, int Y) { public bool Equals(C c) => throw null; public override bool Equals(object o) => false; } "); comp.VerifyDiagnostics( // (4,17): error CS8872: 'C.Equals(C)' must allow overriding because the containing record is not sealed. // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("C.Equals(C)").WithLocation(4, 17), // (4,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(4, 17), // (5,26): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object o) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(5, 26) ); comp = CreateCompilation(@" record C { public int Equals(object o) => throw null; } record D : C { } "); comp.VerifyDiagnostics( // (4,16): warning CS0114: 'C.Equals(object)' hides inherited member 'object.Equals(object)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Equals(object o) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Equals").WithArguments("C.Equals(object)", "object.Equals(object)").WithLocation(4, 16), // (4,16): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public int Equals(object o) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(4, 16) ); CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); Console.WriteLine(c.Equals(c)); } public virtual bool Equals(C c) => false; }", expectedOutput: "False").VerifyDiagnostics( // (10,25): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(C c) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(10, 25) ); } [Fact] public void RecordEquals_02() { CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(1, 1); var c2 = new C(1, 1); Console.WriteLine(c.Equals(c)); Console.WriteLine(c.Equals(c2)); } }", expectedOutput: @"True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_03() { var verifier = CompileAndVerify(@" using System; sealed record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } public bool Equals(C c) => X == c.X && Y == c.Y; }", expectedOutput: @"True False").VerifyDiagnostics( // (13,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) => X == c.X && Y == c.Y; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(13, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: call ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""int C.X.get"" IL_0006: ldarg.1 IL_0007: callvirt ""int C.X.get"" IL_000c: bne.un.s IL_001d IL_000e: ldarg.0 IL_000f: call ""int C.Y.get"" IL_0014: ldarg.1 IL_0015: callvirt ""int C.Y.get"" IL_001a: ceq IL_001c: ret IL_001d: ldc.i4.0 IL_001e: ret }"); } [Fact] public void RecordEquals_04() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"True False").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_06() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { var c = new C(0, 0); object c2 = null; C c3 = null; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False False").VerifyDiagnostics(); } [Fact] public void RecordEquals_07() { var verifier = CompileAndVerify(@" using System; record C(int[] X, string Y) { public static void Main() { var arr = new[] {1, 2}; var c = new C(arr, ""abc""); var c2 = new C(new[] {1, 2}, ""abc""); var c3 = new C(arr, ""abc""); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False True").VerifyDiagnostics(); } [Fact] public void RecordEquals_08() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z; public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""int C.Z"" IL_0051: ldarg.1 IL_0052: ldfld ""int C.Z"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void RecordEquals_09() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z { get; set; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_10() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static int Z; public static void Main() { var c = new C(1, 2); C.Z = 3; var c2 = new C(1, 2); C.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); C.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_11() { var verifier = CompileAndVerify(@" using System; using System.Collections.Generic; record C(int X, int Y) { static Dictionary<C, int> s_dict = new Dictionary<C, int>(); public int Z { get => s_dict[this]; set => s_dict[this] = value; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_12() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { private event Action E; public static void Main() { var c = new C(1, 2); c.E = () => { }; var c2 = new C(1, 2); c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""System.Action C.E"" IL_0051: ldarg.1 IL_0052: ldfld ""System.Action C.E"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void RecordClone1() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ret }"); } [Fact] public void RecordClone2_0() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { x = other.x; y = other.y; } }"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: callvirt ""int C.x.get"" IL_000d: call ""void C.x.init"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: callvirt ""int C.y.get"" IL_0019: call ""void C.y.init"" IL_001e: ret } "); } [Fact] public void RecordClone2_0_WithThisInitializer() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : this(other.x, other.y) { } }"); comp.VerifyDiagnostics( // (4,25): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C other) : this(other.x, other.y) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(4, 25) ); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_1() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_2() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : base() { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44782, "https://github.com/dotnet/roslyn/issues/44782")] public void RecordClone3() { var comp = CreateCompilation(@" using System; public record C(int x, int y) { public event Action E; public int Z; public int W = 123; }"); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 67 (0x43) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""System.Action C.E"" IL_0025: stfld ""System.Action C.E"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Z"" IL_0031: stfld ""int C.Z"" IL_0036: ldarg.0 IL_0037: ldarg.1 IL_0038: ldfld ""int C.W"" IL_003d: stfld ""int C.W"" IL_0042: ret } "); } [Fact(Skip = "record struct")] public void RecordClone4_0() { var comp = CreateCompilation(@" using System; public data struct S(int x, int y) { public event Action E; public int Z; }"); comp.VerifyDiagnostics( // (3,21): error CS0171: Field 'S.E' must be fully assigned before control is returned to the caller // public data struct S(int x, int y) Diagnostic(ErrorCode.ERR_UnassignedThis, "(int x, int y)").WithArguments("S.E").WithLocation(3, 21), // (3,21): error CS0171: Field 'S.Z' must be fully assigned before control is returned to the caller // public data struct S(int x, int y) Diagnostic(ErrorCode.ERR_UnassignedThis, "(int x, int y)").WithArguments("S.Z").WithLocation(3, 21), // (5,25): warning CS0067: The event 'S.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E").WithLocation(5, 25) ); var s = comp.GlobalNamespace.GetTypeMember("S"); var clone = s.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(s, clone.ReturnType); var ctor = (MethodSymbol)s.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(s, TypeCompareKind.ConsiderEverything)); } [Fact(Skip = "record struct")] public void RecordClone4_1() { var comp = CreateCompilation(@" using System; public data struct S(int x, int y) { public event Action E = null; public int Z = 0; }"); comp.VerifyDiagnostics( // (5,25): error CS0573: 'S': cannot have instance property or field initializers in structs // public event Action E = null; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "E").WithArguments("S").WithLocation(5, 25), // (5,25): warning CS0414: The field 'S.E' is assigned but its value is never used // public event Action E = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "E").WithArguments("S.E").WithLocation(5, 25), // (6,16): error CS0573: 'S': cannot have instance property or field initializers in structs // public int Z = 0; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "Z").WithArguments("S").WithLocation(6, 16) ); } [Fact] public void NominalRecordEquals() { var verifier = CompileAndVerify(@" using System; record C { private int X; private int Y { get; set; } private event Action E; public static void Main() { var c = new C { X = 1, Y = 2 }; c.E = () => { }; var c2 = new C { X = 1, Y = 2 }; c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics( // (5,17): warning CS0414: The field 'C.X' is assigned but its value is never used // private int X; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "X").WithArguments("C.X").WithLocation(5, 17) ); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.X"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.X"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""System.Action C.E"" IL_0051: ldarg.1 IL_0052: ldfld ""System.Action C.E"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void PositionalAndNominalSameEquals() { var v1 = CompileAndVerify(@" using System; record C(int X, string Y) { public event Action E; } ").VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(5, 25) ); var v2 = CompileAndVerify(@" using System; record C { public int X { get; } public string Y { get; } public event Action E; }").VerifyDiagnostics( // (7,25): warning CS0067: The event 'C.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E").WithLocation(7, 25) ); Assert.Equal(v1.VisualizeIL("C.Equals(C)"), v2.VisualizeIL("C.Equals(C)")); Assert.Equal(v1.VisualizeIL("C.Equals(object)"), v2.VisualizeIL("C.Equals(object)")); } [Fact] public void NominalRecordMembers() { var comp = CreateCompilation(@" #nullable enable record C { public int X { get; init; } public string Y { get; init; } }"); var members = comp.GlobalNamespace.GetTypeMember("C").GetMembers(); AssertEx.Equal(new[] { "System.Type! C.EqualityContract.get", "System.Type! C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X { get; init; }", "System.Int32 C.X.get", "void C.X.init", "System.String! C.<Y>k__BackingField", "System.String! C.Y { get; init; }", "System.String! C.Y.get", "void C.Y.init", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder! builder)", "System.Boolean C.operator !=(C? r1, C? r2)", "System.Boolean C.operator ==(C? r1, C? r2)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C! C." + WellKnownMemberNames.CloneMethodName + "()", "C.C(C! original)", "C.C()", }, members.Select(m => m.ToTestDisplayString(includeNonNullable: true))); } [Fact] public void PartialTypes_01() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X, int Y) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X, int Y) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X, int Y)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_02() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_03() { var src = @" partial record C { public int X = 1; } partial record C(int Y); partial record C { public int Z { get; } = 2; }"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stfld ""int C.X"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.2 IL_0010: stfld ""int C.<Z>k__BackingField"" IL_0015: ldarg.0 IL_0016: call ""object..ctor()"" IL_001b: ret }"); } [Fact] public void PartialTypes_04_PartialBeforeModifiers() { var src = @" partial public record C { } "; CreateCompilation(src).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public record C Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1) ); } [Fact] public void DataClassAndStruct() { var src = @" data class C1 { } data class C2(int X, int Y); data struct S1 { } data struct S2(int X, int Y);"; var comp = CreateCompilation(src, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS8805: Program using top-level statements must be an executable. Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable).WithLocation(1, 1), // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(2, 1), // (3,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(3, 1), // (3,14): error CS1514: { expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS1513: } expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS8803: Top-level statements must precede namespace and type declarations. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int X, int Y);").WithLocation(3, 14), // (3,14): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(3, 14), // (3,15): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(3, 15), // (3,15): error CS0165: Use of unassigned local variable 'X' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(3, 15), // (3,22): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(3, 22), // (3,22): error CS0165: Use of unassigned local variable 'Y' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(3, 22), // (4,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(4, 1), // (5,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(5, 1), // (5,15): error CS1514: { expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS1513: } expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(5, 15), // (5,16): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(5, 16), // (5,16): error CS0165: Use of unassigned local variable 'X' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(5, 16), // (5,20): error CS0128: A local variable or function named 'X' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "X").WithArguments("X").WithLocation(5, 20), // (5,23): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(5, 23), // (5,23): error CS0165: Use of unassigned local variable 'Y' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(5, 23), // (5,27): error CS0128: A local variable or function named 'Y' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Y").WithArguments("Y").WithLocation(5, 27) ); } [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] [Fact] public void ClassInheritingFromRecord() { var src = @" abstract record AbstractRecord {} class SomeClass : AbstractRecord {}"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,19): error CS8865: Only records may inherit from records. // class SomeClass : AbstractRecord {} Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "AbstractRecord").WithLocation(3, 19) ); } [Fact] public void RecordInheritance() { var src = @" class A { } record B : A { } record C : B { } class D : C { } interface E : C { } struct F : C { } enum G : C { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record B : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (5,11): error CS8865: Only records may inherit from records. // class D : C { } Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "C").WithLocation(5, 11), // (6,15): error CS0527: Type 'C' in interface list is not an interface // interface E : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(6, 15), // (7,12): error CS0527: Type 'C' in interface list is not an interface // struct F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(7, 12), // (8,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum G : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(8, 10) ); } [Theory] [InlineData(true)] [InlineData(false)] public void RecordInheritance2(bool emitReference) { var src = @" public class A { } public record B { } public record C : B { }"; var comp = CreateCompilation(src); var src2 = @" record D : C { } record E : A { } interface F : C { } struct G : C { } enum H : C { } "; var comp2 = CreateCompilation(src2, parseOptions: TestOptions.Regular9, references: new[] { emitReference ? comp.EmitToImageReference() : comp.ToMetadataReference() }); comp2.VerifyDiagnostics( // (3,8): error CS0115: 'E.EqualityContract': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'E.Equals(A?)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.Equals(A?)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record E : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record E : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (4,15): error CS0527: Type 'C' in interface list is not an interface // interface F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(4, 15), // (5,12): error CS0527: Type 'C' in interface list is not an interface // struct G : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(5, 12), // (6,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum H : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(6, 10) ); } [Fact] public void GenericRecord() { var src = @" using System; record A<T> { public T Prop { get; init; } } record B : A<int>; record C<T>(T Prop2) : A<T>; class P { public static void Main() { var a = new A<int>() { Prop = 1 }; var a2 = a with { Prop = 2 }; Console.WriteLine(a.Prop + "" "" + a2.Prop); var b = new B() { Prop = 3 }; var b2 = b with { Prop = 4 }; Console.WriteLine(b.Prop + "" "" + b2.Prop); var c = new C<int>(5) { Prop = 6 }; var c2 = c with { Prop = 7, Prop2 = 8 }; Console.WriteLine(c.Prop + "" "" + c.Prop2); Console.WriteLine(c2.Prop2 + "" "" + c2.Prop); } }"; CompileAndVerify(src, expectedOutput: @" 1 2 3 4 6 5 8 7").VerifyDiagnostics(); } [Fact] public void RecordCloneSymbol() { var src = @" record R; record R2 : R"; var comp = CreateCompilation(src); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.False(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); } [Fact] public void AbstractRecordClone() { var src = @" abstract record R; abstract record R2 : R; record R3 : R2; abstract record R4 : R3; record R5 : R4; class C { public static void Main() { R r = new R3(); r = r with { }; R4 r4 = new R5(); r4 = r4 with { }; } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); Assert.Equal("R R." + WellKnownMemberNames.CloneMethodName + "()", clone.ToTestDisplayString()); Assert.True(clone.IsImplicitlyDeclared); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.True(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R2." + WellKnownMemberNames.CloneMethodName + "()", clone2.ToTestDisplayString()); Assert.True(clone2.IsImplicitlyDeclared); var r3 = comp.GlobalNamespace.GetTypeMember("R3"); var clone3 = (MethodSymbol)r3.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone3.IsOverride); Assert.False(clone3.IsVirtual); Assert.False(clone3.IsAbstract); Assert.Equal(0, clone3.ParameterCount); Assert.Equal(0, clone3.Arity); Assert.True(clone3.OverriddenMethod.Equals(clone2, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R3." + WellKnownMemberNames.CloneMethodName + "()", clone3.ToTestDisplayString()); Assert.True(clone3.IsImplicitlyDeclared); var r4 = comp.GlobalNamespace.GetTypeMember("R4"); var clone4 = (MethodSymbol)r4.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone4.IsOverride); Assert.False(clone4.IsVirtual); Assert.True(clone4.IsAbstract); Assert.Equal(0, clone4.ParameterCount); Assert.Equal(0, clone4.Arity); Assert.True(clone4.OverriddenMethod.Equals(clone3, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R4." + WellKnownMemberNames.CloneMethodName + "()", clone4.ToTestDisplayString()); Assert.True(clone4.IsImplicitlyDeclared); var r5 = comp.GlobalNamespace.GetTypeMember("R5"); var clone5 = (MethodSymbol)r5.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone5.IsOverride); Assert.False(clone5.IsVirtual); Assert.False(clone5.IsAbstract); Assert.Equal(0, clone5.ParameterCount); Assert.Equal(0, clone5.Arity); Assert.True(clone5.OverriddenMethod.Equals(clone4, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R5." + WellKnownMemberNames.CloneMethodName + "()", clone5.ToTestDisplayString()); Assert.True(clone5.IsImplicitlyDeclared); var verifier = CompileAndVerify(comp, expectedOutput: "", verify: Verification.Passes).VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: newobj ""R3..ctor()"" IL_0005: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000a: pop IL_000b: newobj ""R5..ctor()"" IL_0010: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: castclass ""R4"" IL_001a: pop IL_001b: ret }"); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithEventImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { event Action E1; } public record R1 : I1 { public event Action E1 { add { } remove { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithPropertyImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action P1 { get; set; } } public record R1 : I1 { public Action P1 { get; set; } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(49286, "https://github.com/dotnet/roslyn/issues/49286")] public void RecordWithMethodImplicitlyImplementingAnInterface() { var src = @" using System; public interface I1 { Action M1(); } public record R1 : I1 { public Action M1() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } } }
37.407453
223
0.591009
[ "MIT" ]
Cosifne/roslyn
src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs
61,238
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved. * */ #endregion namespace Krypton.Toolkit { /// <summary> /// Colors associated with menus and tool strip. /// </summary> public class KryptonPaletteTMS : Storage { #region Instance Fields #endregion #region Identity /// <summary> /// Initialize a new instance of the KryptonPaletteKCT class. /// </summary> /// <param name="palette">Associated palettte instance.</param> /// <param name="baseKCT">Initial base KCT to inherit values from.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> internal KryptonPaletteTMS(IPalette palette, KryptonColorTable baseKCT, NeedPaintHandler needPaint) { Debug.Assert(baseKCT != null); // Create actual KCT for storage InternalKCT = new KryptonInternalKCT(baseKCT, palette); // Create the set of sub objects that expose the palette properties Button = new KryptonPaletteTMSButton(InternalKCT, needPaint); Grip = new KryptonPaletteTMSGrip(InternalKCT, needPaint); Menu = new KryptonPaletteTMSMenu(InternalKCT, needPaint); MenuStrip = new KryptonPaletteTMSMenuStrip(InternalKCT, needPaint); Rafting = new KryptonPaletteTMSRafting(InternalKCT, needPaint); Separator = new KryptonPaletteTMSSeparator(InternalKCT, needPaint); StatusStrip = new KryptonPaletteTMSStatusStrip(InternalKCT, needPaint); ToolStrip = new KryptonPaletteTMSToolStrip(InternalKCT, needPaint); } /// <summary> /// Gets a value indicating if all values are default. /// </summary> public override bool IsDefault => InternalKCT.IsDefault && Button.IsDefault && Grip.IsDefault && Menu.IsDefault && Rafting.IsDefault && MenuStrip.IsDefault && Separator.IsDefault && StatusStrip.IsDefault && ToolStrip.IsDefault; #endregion #region PopulateFromBase /// <summary> /// Populate values from the base palette. /// </summary> public void PopulateFromBase() { Button.PopulateFromBase(); Grip.PopulateFromBase(); Menu.PopulateFromBase(); Rafting.PopulateFromBase(); MenuStrip.PopulateFromBase(); Separator.PopulateFromBase(); StatusStrip.PopulateFromBase(); ToolStrip.PopulateFromBase(); UseRoundedEdges = InternalKCT.UseRoundedEdges; } #endregion #region Button /// <summary> /// Get access to the button colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("Button specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSButton Button { get; } private bool ShouldSerializeButton() => !Button.IsDefault; #endregion #region Grip /// <summary> /// Get access to the grip colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("Grip specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSGrip Grip { get; } private bool ShouldSerializeGrip() => !Grip.IsDefault; #endregion #region Menu /// <summary> /// Get access to the menu colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("Menu specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSMenu Menu { get; } private bool ShouldSerializeMenu() => !Menu.IsDefault; #endregion #region Rafting /// <summary> /// Get access to the rafting colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("Rafting specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSRafting Rafting { get; } private bool ShouldSerializeRafting() => !Rafting.IsDefault; #endregion #region MenuStrip /// <summary> /// Get access to the menu strip colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("MenuStrip specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSMenuStrip MenuStrip { get; } private bool ShouldSerializeMenuStrip() => !MenuStrip.IsDefault; #endregion #region Separator /// <summary> /// Get access to the separator colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("Separator specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSSeparator Separator { get; } private bool ShouldSerializeSeparator() => !Separator.IsDefault; #endregion #region StatusStrip /// <summary> /// Get access to the status strip colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("StatusStrip specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSStatusStrip StatusStrip { get; } private bool ShouldSerializeStatusStrip() => !StatusStrip.IsDefault; #endregion #region ToolStrip /// <summary> /// Get access to the tool strip colors. /// </summary> [KryptonPersist] [Category("ToolMenuStatus")] [Description("ToolStrip specific colors.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public KryptonPaletteTMSToolStrip ToolStrip { get; } private bool ShouldSerializeToolStrip() => !ToolStrip.IsDefault; #endregion #region UseRoundedEdges /// <summary> /// Gets and sets the use of rounded or square edges when rendering. /// </summary> [KryptonPersist(false)] [Category("ToolMenuStatus")] [Description("Should rendering use rounded or square edges.")] [DefaultValue(typeof(InheritBool), "Inherit")] public InheritBool UseRoundedEdges { get => InternalKCT.InternalUseRoundedEdges; set { InternalKCT.InternalUseRoundedEdges = value; PerformNeedPaint(false); } } /// <summary> /// esets the UseRoundedEdges property to its default value. /// </summary> public void ResetUseRoundedEdges() { UseRoundedEdges = InheritBool.Inherit; } #endregion #region Internal internal KryptonColorTable BaseKCT { get => InternalKCT.BaseKCT; set => InternalKCT.BaseKCT = value; } internal KryptonInternalKCT InternalKCT { get; } #endregion } }
34.662447
119
0.59647
[ "BSD-3-Clause" ]
Krypton-Suite/Standard-Toolk
Source/Krypton Components/Krypton.Toolkit/Palette Component/KryptonPaletteTMS.cs
8,218
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #nullable enable namespace Microsoft.Toolkit.Diagnostics { /// <summary> /// Helper methods to throw exceptions /// </summary> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] internal static partial class ThrowHelper { /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNullOrEmpty"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNullOrEmpty(string? text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be null or empty, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNotNullOrEmpty"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNotNullOrEmpty(string? text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be null or empty, was {(text is null ? "null" : "empty")}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNullOrWhitespace"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNullOrWhitespace(string? text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be null or whitespace, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNotNullOrWhitespace"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNotNullOrWhitespace(string? text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be null or whitespace, was {(text is null ? "null" : "whitespace")}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsEmpty"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsEmpty(string text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be empty, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNotEmpty"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNotEmpty(string text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be empty"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsWhitespace"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsWhitespace(string text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be whitespace, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.IsNotWhitespace"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForIsNotWhitespace(string text, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be whitespace, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeEqualTo"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeEqualTo(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size equal to {size}, had a size of {text.Length} and was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeNotEqualTo"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeNotEqualTo(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not have a size equal to {size}, was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeOver"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeOver(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size over {size}, had a size of {text.Length} and was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeAtLeast"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeAtLeast(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size of at least {size}, had a size of {text.Length} and was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeLessThan"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeLessThan(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size less than {size}, had a size of {text.Length} and was {text.ToAssertString()}"); } /// <summary> /// Throws an <see cref="ArgumentException"/> when <see cref="Guard.HasSizeLessThanOrEqualTo"/> fails. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(string text, int size, string name) { ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size less than or equal to {size}, had a size of {text.Length} and was {text.ToAssertString()}"); } } }
49.69863
195
0.65339
[ "MIT" ]
Cyberh1/WindowsCommunityToolkit
Microsoft.Toolkit/Diagnostics/ThrowHelper.String.cs
7,256
C#
// // Recipient.cs // // Author: Kees van Spelde <sicos2002@hotmail.com> // // Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com) // // 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 NON INFRINGEMENT. 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.Collections.Generic; using MsgKit.Enums; using MsgKit.Helpers; using MsgKit.Streams; using MsgKit.Structures; using OpenMcdf; namespace MsgKit { /// <summary> /// Contains a list of <see cref="Recipients"/> objects that are added to a <see cref="Message"/> /// </summary> public class Recipients : List<Recipient> { #region Add /// <summary> /// Add's an <see cref="RecipientType.To"/> <see cref="Recipient"/> /// </summary> /// <param name="email">The full E-mail address</param> /// <param name="displayName">The displayname for the <paramref name="email"/></param> /// <param name="addressType">The <see cref="AddressType"/></param> /// <param name="objectType"><see cref="MapiObjectType"/></param> /// <param name="displayType"><see cref="RecipientRowDisplayType"/></param> public void AddTo(string email, string displayName = "", AddressType addressType = AddressType.Smtp, MapiObjectType objectType = MapiObjectType.MAPI_MAILUSER, RecipientRowDisplayType displayType = RecipientRowDisplayType.MessagingUser) { Add(new Recipient(Count, email, displayName, addressType, RecipientType.To, objectType, displayType )); } /// <summary> /// Add's an <see cref="RecipientType.Cc"/> <see cref="Recipient"/> /// </summary> /// <param name="email">The full E-mail address</param> /// <param name="displayName">The displayname for the <paramref name="email"/></param> /// <param name="addressType">The <see cref="AddressType"/></param> /// <param name="objectType"><see cref="MapiObjectType"/></param> /// <param name="displayType"><see cref="RecipientRowDisplayType"/></param> public void AddCc(string email, string displayName = "", AddressType addressType = AddressType.Smtp, MapiObjectType objectType = MapiObjectType.MAPI_MAILUSER, RecipientRowDisplayType displayType = RecipientRowDisplayType.MessagingUser) { Add(new Recipient(Count, email, displayName, addressType, RecipientType.Cc, objectType, displayType)); } /// <summary> /// Add's an <see cref="RecipientType.Bcc"/> <see cref="Recipient"/> /// </summary> /// <param name="email">The full E-mail address</param> /// <param name="displayName">The displayname for the <paramref name="email"/></param> /// <param name="addressType">The <see cref="AddressType"/></param> /// <param name="objectType"><see cref="MapiObjectType"/></param> /// <param name="displayType"><see cref="RecipientRowDisplayType"/></param> public void AddBcc(string email, string displayName = "", AddressType addressType = AddressType.Smtp, MapiObjectType objectType = MapiObjectType.MAPI_MAILUSER, RecipientRowDisplayType displayType = RecipientRowDisplayType.MessagingUser) { Add(new Recipient(Count, email, displayName, addressType, RecipientType.Bcc, objectType, displayType)); } /// <summary> /// Add's an <see cref="Recipient"/> /// </summary> /// <param name="email">The full E-mail address</param> /// <param name="displayName">The displayname for the <paramref name="email"/></param> /// <param name="addressType">The <see cref="AddressType"/></param> /// <param name="recipientType">The <see cref="RecipientType"/></param> /// <param name="objectType"><see cref="MapiObjectType"/></param> /// <param name="displayType"><see cref="RecipientRowDisplayType"/></param> public void AddRecipient(string email, string displayName, AddressType addressType, RecipientType recipientType, MapiObjectType objectType = MapiObjectType.MAPI_MAILUSER, RecipientRowDisplayType displayType = RecipientRowDisplayType.MessagingUser) { Add(new Recipient(Count, email, displayName, addressType, recipientType, objectType, displayType)); } #endregion #region WriteToStorage /// <summary> /// Writes the <see cref="Recipient"/> objects to the given <paramref name="rootStorage"/> /// and it will set all the needed properties /// </summary> /// <param name="rootStorage">The root <see cref="CFStorage"/></param> /// <returns> /// Total size of the written <see cref="Recipient"/> objects and it's <see cref="Properties"/> /// </returns> internal long WriteToStorage(CFStorage rootStorage) { long size = 0; for (var index = 0; index < Count; index++) { var recipient = this[index]; var storage = rootStorage.AddStorage(PropertyTags.RecipientStoragePrefix + index.ToString("X8").ToUpper()); size += recipient.WriteProperties(storage); } return size; } #endregion } /// <summary> /// This class represents a recipient /// </summary> public class Recipient : Address { #region Properties /// <summary> /// Returns or sets a unique identifier for a recipient in a recipient table or status table. /// </summary> public long RowId { get; } /// <summary> /// The <see cref="RecipientType"/> /// </summary> public RecipientType RecipientType { get; } /// <summary> /// The <see cref="RecipientFlags"/> /// </summary> // ReSharper disable once UnusedAutoPropertyAccessor.Local public RecipientFlags Flags { get; private set; } /// <summary> /// Contains the type of email object. /// </summary> public MapiObjectType ObjectType { get; } /// <summary> /// Contains the display type. /// </summary> public RecipientRowDisplayType DisplayType { get; } #endregion #region Constructor /// <summary> /// Creates a new recipient object and sets all its properties /// </summary> /// <param name="rowId">Contains a unique identifier for a recipient in a recipient table or status table.</param> /// <param name="email">The full E-mail address</param> /// <param name="displayName">The displayname for the <paramref name="email"/></param> /// <param name="recipientType">The <see cref="RecipientType"/></param> /// <param name="addressType">The <see cref="AddressType"/></param> /// <param name="objectType"><see cref="MapiObjectType"/></param> /// <param name="displayType"><see cref="RecipientRowDisplayType"/></param> internal Recipient(long rowId, string email, string displayName, AddressType addressType, RecipientType recipientType, MapiObjectType objectType, RecipientRowDisplayType displayType) : base(email, displayName, addressType) { RowId = rowId; Email = email; DisplayName = string.IsNullOrWhiteSpace(displayName) ? email : displayName; AddressType = addressType; RecipientType = recipientType; DisplayType = displayType; ObjectType = objectType; } #endregion #region WriteProperties /// <summary> /// Writes all <see cref="Property">properties</see> either as a <see cref="CFStream"/> or as a collection in /// a <see cref="PropertyTags.PropertiesStreamName"/> stream to the given <paramref name="storage"/>, this depends /// on the <see cref="PropertyType"/> /// </summary> /// <remarks> /// See the <see cref="Properties"/> class it's <see cref="Properties.WriteProperties"/> method for the logic /// that is used to determine this /// </remarks> /// <param name="storage">The <see cref="CFStorage"/></param> /// <returns> /// Total size of the written <see cref="Recipient"/> object and it's <see cref="Properties"/> /// </returns> internal long WriteProperties(CFStorage storage) { var propertiesStream = new RecipientProperties(); propertiesStream.AddProperty(PropertyTags.PR_ROWID, RowId); propertiesStream.AddProperty(PropertyTags.PR_ENTRYID, Mapi.GenerateEntryId()); propertiesStream.AddProperty(PropertyTags.PR_INSTANCE_KEY, Mapi.GenerateInstanceKey()); propertiesStream.AddProperty(PropertyTags.PR_RECIPIENT_TYPE, RecipientType); propertiesStream.AddProperty(PropertyTags.PR_ADDRTYPE_W, AddressTypeString); propertiesStream.AddProperty(PropertyTags.PR_EMAIL_ADDRESS_W, Email); propertiesStream.AddProperty(PropertyTags.PR_OBJECT_TYPE, ObjectType); propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_TYPE, DisplayType); propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_NAME_W, DisplayName); propertiesStream.AddProperty(PropertyTags.PR_SEARCH_KEY, Mapi.GenerateSearchKey(AddressTypeString, Email)); return propertiesStream.WriteProperties(storage); } #endregion } }
46.233463
127
0.569601
[ "Unlicense", "MIT" ]
gohenderson/MsgKit
MsgKit/Recipient.cs
11,884
C#
#if !JSB_UNITYLESS using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace QuickJS.Binding { using UnityEngine; using Native; public partial class Values { public static JSValue NewBridgeClassObject(JSContext ctx, JSValue new_target, Vector2Int o, int type_id, bool disposable) { var val = JSApi.JSB_NewBridgeClassValue(ctx, new_target, sizeof(int) * 2); if (!JSApi.JS_IsException(val)) { JSApi.jsb_set_int_2(ctx, val, o.x, o.y); } return val; } public static bool js_rebind_this(JSContext ctx, JSValue this_obj, ref Vector2Int o) { return JSApi.jsb_set_int_2(ctx, this_obj, o.x, o.y) == 1; } public static JSValue js_push_structvalue(JSContext ctx, Vector2Int o) { var proto = FindPrototypeOf<Vector2Int>(ctx); JSValue val = JSApi.jsb_new_bridge_value(ctx, proto, sizeof(int) * 2); JSApi.jsb_set_int_2(ctx, val, o.x, o.y); return val; } public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2Int o) { int x, y; var ret = JSApi.jsb_get_int_2(ctx, val, out x, out y); o = new Vector2Int(x, y); return ret != 0; } public static bool js_get_structvalue(JSContext ctx, JSValue val, out Vector2Int? o) { if (val.IsNullish()) { o = null; return true; } int x, y; var ret = JSApi.jsb_get_int_2(ctx, val, out x, out y); o = new Vector2Int(x, y); return ret != 0; } } } #endif
31.101695
130
0.541689
[ "MIT" ]
shunfy/unity-jsb
Packages/cc.starlessnight.unity-jsb/Source/Binding/ValueTypes/Values_Vector2Int.cs
1,835
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Reflection.Tests.AssemblyVersion { public class Program_1_1_3_0 { } }
23.7
71
0.742616
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Reflection/tests/AssemblyVersion/Program_1_1_3_0.cs
237
C#
using System; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using SFA.DAS.Reservations.Domain.Interfaces; using SFA.DAS.Reservations.Infrastructure.Configuration; namespace SFA.DAS.Reservations.Infrastructure.TagHelpers { public class ExternalUrlHelper : IExternalUrlHelper { private readonly IConfiguration _configuration; private readonly ReservationsWebConfiguration _options; public ExternalUrlHelper(IOptions<ReservationsWebConfiguration> options, IConfiguration configuration) { _configuration = configuration; _options = options.Value; } /// <summary> /// usage https://subDomain.baseUrl/folder/id/controller/action?queryString /// </summary> /// <param name="urlParameters"></param> /// <returns></returns> public string GenerateUrl(UrlParameters urlParameters) { var baseUrl = GetBaseUrl(); return FormatUrl(baseUrl, urlParameters); } public string GenerateAddApprenticeUrl(Guid reservationId, string accountLegalEntityPublicHashedId, string courseId, uint? ukPrn, DateTime? startDate, string cohortRef, string accountHashedId, bool isEmptyEmployerCohort = false, string transferSenderId = "", string journeyData = "") { var queryString = $"?reservationId={reservationId}"; if (ukPrn.HasValue && !isEmptyEmployerCohort) { queryString += $"&employerAccountLegalEntityPublicHashedId={accountLegalEntityPublicHashedId}"; } else { queryString += $"&accountLegalEntityHashedId={accountLegalEntityPublicHashedId}"; } if (ukPrn.HasValue && isEmptyEmployerCohort) { queryString += $"&providerId={ukPrn}"; } if (startDate.HasValue) { queryString += $"&startMonthYear={startDate:MMyyyy}"; } if (!string.IsNullOrWhiteSpace(courseId)) { queryString += $"&courseCode={courseId}"; } if (!string.IsNullOrWhiteSpace(journeyData)) { queryString += $"&journeyData={journeyData}"; } var isLevyAccount = string.IsNullOrWhiteSpace(courseId) && !startDate.HasValue; if (isLevyAccount) { queryString += "&autocreated=true"; } if (!string.IsNullOrEmpty(transferSenderId)) { queryString += $"&transferSenderId={transferSenderId}"; } string controller = "unapproved", action, id; if (ukPrn.HasValue && !isEmptyEmployerCohort) { action = "add/apprentice"; id = ukPrn.ToString(); } else if (ukPrn.HasValue) { action = "add/apprentice"; id = accountHashedId; } else { action = "add"; id = accountHashedId; } if (!string.IsNullOrEmpty(cohortRef)) { controller += $"/{cohortRef}"; action = "apprentices/add"; } var urlParameters = new UrlParameters { Id = id, Controller = controller, Action = action, QueryString = queryString }; return GenerateAddApprenticeUrl(urlParameters); } /// <summary> /// usage https://subDomain.baseUrl/folder/id/controller/action?queryString /// </summary> /// <param name="urlParameters"></param> /// <returns></returns> public string GenerateAddApprenticeUrl(UrlParameters urlParameters) { var baseUrl = _configuration["AuthType"].Equals("employer", StringComparison.CurrentCultureIgnoreCase) ? _options.EmployerApprenticeUrl : _options.ApprenticeUrl; return FormatUrl(baseUrl, urlParameters); } public string GenerateCohortDetailsUrl(uint? ukprn, string accountId, string cohortRef, bool isEmptyCohort = false, string journeyData = "") { var queryString = isEmptyCohort && ukprn.HasValue ? $"?providerId={ukprn}" : ""; if (!string.IsNullOrWhiteSpace(journeyData)) { if (string.IsNullOrWhiteSpace(journeyData)) { queryString = $"?journeyData={journeyData}"; } else { queryString += $"&journeyData={journeyData}"; } } var urlParameters = new UrlParameters { Id = ukprn.HasValue && !isEmptyCohort ? ukprn.Value.ToString() : accountId, Controller = string.IsNullOrEmpty(cohortRef) ? "unapproved/add" : $"apprentices/{cohortRef}", Action = isEmptyCohort ? "" : string.IsNullOrEmpty(cohortRef) ? "assign" : "details", Folder = ukprn.HasValue && !isEmptyCohort ? "" : "commitments/accounts", QueryString = queryString }; var baseUrl = GetBaseUrl(); return FormatUrl(baseUrl, urlParameters); } private static string FormatUrl(string baseUrl, UrlParameters urlParameters) { var urlString = new StringBuilder(); urlString.Append(FormatBaseUrl(baseUrl, urlParameters.SubDomain, urlParameters.Folder)); if (!string.IsNullOrEmpty(urlParameters.Id)) { urlString.Append($"{urlParameters.Id}/"); } if (!string.IsNullOrEmpty(urlParameters.Controller)) { urlString.Append($"{urlParameters.Controller}/"); } if (!string.IsNullOrEmpty(urlParameters.Action)) { urlString.Append($"{urlParameters.Action}/"); } if (!string.IsNullOrEmpty(urlParameters.QueryString)) { return $"{urlString.ToString().TrimEnd('/')}{urlParameters.QueryString}"; } return urlString.ToString().TrimEnd('/'); } private static string FormatBaseUrl(string url, string subDomain = "", string folder = "") { var returnUrl = url.EndsWith("/") ? url : url + "/"; if (!string.IsNullOrEmpty(subDomain)) { returnUrl = returnUrl.Replace("https://", $"https://{subDomain}."); } if (!string.IsNullOrEmpty(folder)) { returnUrl = $"{returnUrl}{folder}/"; } return returnUrl; } private string GetBaseUrl() { return _configuration["AuthType"].Equals("employer", StringComparison.CurrentCultureIgnoreCase) ? _options.EmployerDashboardUrl : _options.DashboardUrl; } public string GenerateDashboardUrl(string accountId = null) { return string.IsNullOrEmpty(accountId) ? GenerateUrl(new UrlParameters {Controller = "Account"}) : GenerateUrl(new UrlParameters { Controller = "teams", SubDomain = "accounts", Folder = "accounts", Id = accountId }); } } }
33.652174
124
0.538243
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-reservations
src/SFA.DAS.Reservations.Infrastructure/TagHelpers/ExternalUrlHelper.cs
7,742
C#
using CMEETracker.Core; using CMEETracker.ViewModels; using System; using System.Configuration; using System.Windows; using System.Windows.Media; namespace CMEETracker { /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { private CMEECore _cmee; private CMEESetting _cmeeSetting; public MainWindow() { InitializeComponent(); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException); LoadConfigToUI(); Init(); } private void UnhandledException(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception)args.ExceptionObject; lblMsg.Text = e.Message; } private void LoadConfigToUI() { //txtQueueName.Text = ConfigurationManager.AppSettings["ServerQueue"]; txtQueueName.Text = "VA7_test"; txtIP.Text = ConfigurationManager.AppSettings["IPAddress"]; txtPort.Text = ConfigurationManager.AppSettings["PortNumber"]; txtMaxSize.Text = ConfigurationManager.AppSettings["maxSize"]; txtMaxCount.Text = ConfigurationManager.AppSettings["maxCount"]; txtTimeOut.Text = (3 * 10000).ToString(); } private void Init() { _cmeeSetting = new CMEESetting { //QueueName = txtQueueName.Text, //QueueName = ConfigurationManager.AppSettings["ServerQueue"], QueueName = "ken1", IPAddress = txtIP.Text, PortNumber = Convert.ToInt32(txtPort.Text), McmqMaxSize = Convert.ToInt32(txtMaxSize.Text), McmqMaxCount = Convert.ToInt32(txtMaxCount.Text), McmqTimeOut = Convert.ToInt32(txtTimeOut.Text), }; } private void InitCMEE() { string QueueName = _cmeeSetting.QueueName; string IPAddress = _cmeeSetting.IPAddress; int PortNumber = _cmeeSetting.PortNumber; int McmqMaxSize = _cmeeSetting.McmqMaxSize; int McmqMaxCount = _cmeeSetting.McmqMaxCount; int McmqTimeOut = _cmeeSetting.McmqTimeOut; _cmee = new CMEECore(); _cmee.Init(QueueName, IPAddress, PortNumber, McmqMaxSize, McmqMaxCount, McmqTimeOut); } private void btnConnect_Click(object sender, RoutedEventArgs e) { if (_cmee != null && _cmee.IsConnected) { _cmee.Close(); _cmee.Disconnect(); } else { Init(); InitCMEE(); _cmee.Connect(); _cmee.Open(); } ChangeConnectStatus(); } private void ChangeConnectStatus() { if (_cmee.IsConnected) { lblConnectTip.Text = "Connected"; lblConnectTip.Background = new SolidColorBrush(Colors.Lime); } else { lblConnectTip.Text = "Disconnected"; lblConnectTip.Background = new SolidColorBrush(Colors.Red); } } private void btnPut_Click(object sender, RoutedEventArgs e) { string message = txtPut.Text; _cmee.Put(txtQueueName.Text, message); } private void btnGet_Click(object sender, RoutedEventArgs e) { string message = _cmee.Get(); txtGet.Text = message; } } }
31.369748
103
0.562818
[ "MIT" ]
DevTainan/CMEETracker
CMEETracker/MainWindow.xaml.cs
3,745
C#
using FluentAssertions; using Xer.Cqrs.CommandStack; using Xer.Cqrs.CommandStack.Tests.Entities; using Xer.Delegator; using Xer.Delegator.Registration; using Xunit; using Xunit.Abstractions; namespace Xer.Cqrs.CommandStack.Tests.Registration { public class SimpleRegistrationTests { #region RegisterCommandHandlerMethod Method public class RegisterCommandHandlerMethod { private readonly ITestOutputHelper _outputHelper; public RegisterCommandHandlerMethod(ITestOutputHelper outputHelper) { _outputHelper = outputHelper; } [Fact] public void ShouldRegisterCommandHandler() { var commandHandler = new TestCommandHandler(_outputHelper); var registration = new SingleMessageHandlerRegistration(); registration.RegisterCommandHandler(() => commandHandler.AsCommandSyncHandler<TestCommand>()); IMessageHandlerResolver resolver = registration.BuildMessageHandlerResolver(); MessageHandlerDelegate commandHandlerDelegate = resolver.ResolveMessageHandler(typeof(TestCommand)); commandHandlerDelegate.Should().NotBeNull(); // Delegate should invoke the actual command handler - TestCommandHandler. commandHandlerDelegate.Invoke(new TestCommand()); commandHandler.HandledCommands.Should().HaveCount(1); commandHandler.HasHandledCommand<TestCommand>().Should().BeTrue(); } [Fact] public void ShouldRegisterCommandAsyncHandler() { var commandHandler = new TestCommandHandler(_outputHelper); var registration = new SingleMessageHandlerRegistration(); registration.RegisterCommandHandler(() => commandHandler.AsCommandAsyncHandler<TestCommand>()); IMessageHandlerResolver resolver = registration.BuildMessageHandlerResolver(); MessageHandlerDelegate commandHandlerDelegate = resolver.ResolveMessageHandler(typeof(TestCommand)); commandHandlerDelegate.Should().NotBeNull(); // Delegate should invoke the actual command handler - TestCommandHandler. commandHandlerDelegate.Invoke(new TestCommand()); commandHandler.HandledCommands.Should().HaveCount(1); commandHandler.HasHandledCommand<TestCommand>().Should().BeTrue(); } } #endregion RegisterCommandHandlerMethod Method } }
37.3
116
0.667177
[ "MIT" ]
XerProjects/Xer.Cqrs.CommandStack
Tests/Xer.Cqrs.CommandStack.Tests/Registration/SimpleRegistrationTests.cs
2,613
C#
using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using AngleSharp; using AngleSharp.Dom; using AngleSharp.Dom.Events; using AngleSharp.Html.Dom; using AngleSharp.Io; namespace AngleSharpWrappers { #nullable enable /// <summary> /// Represents a wrapper class around <see cref="IHtmlFormElement"/> type. /// </summary> [DebuggerDisplay("{OuterHtml,nq}")] public sealed class HtmlFormElementWrapper : Wrapper<IHtmlFormElement>, IHtmlFormElement { /// <summary> /// Creates an instance of the <see cref="HtmlFormElementWrapper"/> type; /// </summary> public HtmlFormElementWrapper(IElementFactory<IHtmlFormElement> elementFactory) : base(elementFactory) { } /// <inheritdoc/> #region Events public event DomEventHandler Aborted { add => WrappedElement.Aborted += value; remove => WrappedElement.Aborted -= value; } /// <inheritdoc/> public event DomEventHandler Blurred { add => WrappedElement.Blurred += value; remove => WrappedElement.Blurred -= value; } /// <inheritdoc/> public event DomEventHandler Cancelled { add => WrappedElement.Cancelled += value; remove => WrappedElement.Cancelled -= value; } /// <inheritdoc/> public event DomEventHandler CanPlay { add => WrappedElement.CanPlay += value; remove => WrappedElement.CanPlay -= value; } /// <inheritdoc/> public event DomEventHandler CanPlayThrough { add => WrappedElement.CanPlayThrough += value; remove => WrappedElement.CanPlayThrough -= value; } /// <inheritdoc/> public event DomEventHandler Changed { add => WrappedElement.Changed += value; remove => WrappedElement.Changed -= value; } /// <inheritdoc/> public event DomEventHandler Clicked { add => WrappedElement.Clicked += value; remove => WrappedElement.Clicked -= value; } /// <inheritdoc/> public event DomEventHandler CueChanged { add => WrappedElement.CueChanged += value; remove => WrappedElement.CueChanged -= value; } /// <inheritdoc/> public event DomEventHandler DoubleClick { add => WrappedElement.DoubleClick += value; remove => WrappedElement.DoubleClick -= value; } /// <inheritdoc/> public event DomEventHandler Drag { add => WrappedElement.Drag += value; remove => WrappedElement.Drag -= value; } /// <inheritdoc/> public event DomEventHandler DragEnd { add => WrappedElement.DragEnd += value; remove => WrappedElement.DragEnd -= value; } /// <inheritdoc/> public event DomEventHandler DragEnter { add => WrappedElement.DragEnter += value; remove => WrappedElement.DragEnter -= value; } /// <inheritdoc/> public event DomEventHandler DragExit { add => WrappedElement.DragExit += value; remove => WrappedElement.DragExit -= value; } /// <inheritdoc/> public event DomEventHandler DragLeave { add => WrappedElement.DragLeave += value; remove => WrappedElement.DragLeave -= value; } /// <inheritdoc/> public event DomEventHandler DragOver { add => WrappedElement.DragOver += value; remove => WrappedElement.DragOver -= value; } /// <inheritdoc/> public event DomEventHandler DragStart { add => WrappedElement.DragStart += value; remove => WrappedElement.DragStart -= value; } /// <inheritdoc/> public event DomEventHandler Dropped { add => WrappedElement.Dropped += value; remove => WrappedElement.Dropped -= value; } /// <inheritdoc/> public event DomEventHandler DurationChanged { add => WrappedElement.DurationChanged += value; remove => WrappedElement.DurationChanged -= value; } /// <inheritdoc/> public event DomEventHandler Emptied { add => WrappedElement.Emptied += value; remove => WrappedElement.Emptied -= value; } /// <inheritdoc/> public event DomEventHandler Ended { add => WrappedElement.Ended += value; remove => WrappedElement.Ended -= value; } /// <inheritdoc/> public event DomEventHandler Error { add => WrappedElement.Error += value; remove => WrappedElement.Error -= value; } /// <inheritdoc/> public event DomEventHandler Focused { add => WrappedElement.Focused += value; remove => WrappedElement.Focused -= value; } /// <inheritdoc/> public event DomEventHandler Input { add => WrappedElement.Input += value; remove => WrappedElement.Input -= value; } /// <inheritdoc/> public event DomEventHandler Invalid { add => WrappedElement.Invalid += value; remove => WrappedElement.Invalid -= value; } /// <inheritdoc/> public event DomEventHandler KeyDown { add => WrappedElement.KeyDown += value; remove => WrappedElement.KeyDown -= value; } /// <inheritdoc/> public event DomEventHandler KeyPress { add => WrappedElement.KeyPress += value; remove => WrappedElement.KeyPress -= value; } /// <inheritdoc/> public event DomEventHandler KeyUp { add => WrappedElement.KeyUp += value; remove => WrappedElement.KeyUp -= value; } /// <inheritdoc/> public event DomEventHandler Loaded { add => WrappedElement.Loaded += value; remove => WrappedElement.Loaded -= value; } /// <inheritdoc/> public event DomEventHandler LoadedData { add => WrappedElement.LoadedData += value; remove => WrappedElement.LoadedData -= value; } /// <inheritdoc/> public event DomEventHandler LoadedMetadata { add => WrappedElement.LoadedMetadata += value; remove => WrappedElement.LoadedMetadata -= value; } /// <inheritdoc/> public event DomEventHandler Loading { add => WrappedElement.Loading += value; remove => WrappedElement.Loading -= value; } /// <inheritdoc/> public event DomEventHandler MouseDown { add => WrappedElement.MouseDown += value; remove => WrappedElement.MouseDown -= value; } /// <inheritdoc/> public event DomEventHandler MouseEnter { add => WrappedElement.MouseEnter += value; remove => WrappedElement.MouseEnter -= value; } /// <inheritdoc/> public event DomEventHandler MouseLeave { add => WrappedElement.MouseLeave += value; remove => WrappedElement.MouseLeave -= value; } /// <inheritdoc/> public event DomEventHandler MouseMove { add => WrappedElement.MouseMove += value; remove => WrappedElement.MouseMove -= value; } /// <inheritdoc/> public event DomEventHandler MouseOut { add => WrappedElement.MouseOut += value; remove => WrappedElement.MouseOut -= value; } /// <inheritdoc/> public event DomEventHandler MouseOver { add => WrappedElement.MouseOver += value; remove => WrappedElement.MouseOver -= value; } /// <inheritdoc/> public event DomEventHandler MouseUp { add => WrappedElement.MouseUp += value; remove => WrappedElement.MouseUp -= value; } /// <inheritdoc/> public event DomEventHandler MouseWheel { add => WrappedElement.MouseWheel += value; remove => WrappedElement.MouseWheel -= value; } /// <inheritdoc/> public event DomEventHandler Paused { add => WrappedElement.Paused += value; remove => WrappedElement.Paused -= value; } /// <inheritdoc/> public event DomEventHandler Played { add => WrappedElement.Played += value; remove => WrappedElement.Played -= value; } /// <inheritdoc/> public event DomEventHandler Playing { add => WrappedElement.Playing += value; remove => WrappedElement.Playing -= value; } /// <inheritdoc/> public event DomEventHandler Progress { add => WrappedElement.Progress += value; remove => WrappedElement.Progress -= value; } /// <inheritdoc/> public event DomEventHandler RateChanged { add => WrappedElement.RateChanged += value; remove => WrappedElement.RateChanged -= value; } /// <inheritdoc/> public event DomEventHandler Resetted { add => WrappedElement.Resetted += value; remove => WrappedElement.Resetted -= value; } /// <inheritdoc/> public event DomEventHandler Resized { add => WrappedElement.Resized += value; remove => WrappedElement.Resized -= value; } /// <inheritdoc/> public event DomEventHandler Scrolled { add => WrappedElement.Scrolled += value; remove => WrappedElement.Scrolled -= value; } /// <inheritdoc/> public event DomEventHandler Seeked { add => WrappedElement.Seeked += value; remove => WrappedElement.Seeked -= value; } /// <inheritdoc/> public event DomEventHandler Seeking { add => WrappedElement.Seeking += value; remove => WrappedElement.Seeking -= value; } /// <inheritdoc/> public event DomEventHandler Selected { add => WrappedElement.Selected += value; remove => WrappedElement.Selected -= value; } /// <inheritdoc/> public event DomEventHandler Shown { add => WrappedElement.Shown += value; remove => WrappedElement.Shown -= value; } /// <inheritdoc/> public event DomEventHandler Stalled { add => WrappedElement.Stalled += value; remove => WrappedElement.Stalled -= value; } /// <inheritdoc/> public event DomEventHandler Submitted { add => WrappedElement.Submitted += value; remove => WrappedElement.Submitted -= value; } /// <inheritdoc/> public event DomEventHandler Suspended { add => WrappedElement.Suspended += value; remove => WrappedElement.Suspended -= value; } /// <inheritdoc/> public event DomEventHandler TimeUpdated { add => WrappedElement.TimeUpdated += value; remove => WrappedElement.TimeUpdated -= value; } /// <inheritdoc/> public event DomEventHandler Toggled { add => WrappedElement.Toggled += value; remove => WrappedElement.Toggled -= value; } /// <inheritdoc/> public event DomEventHandler VolumeChanged { add => WrappedElement.VolumeChanged += value; remove => WrappedElement.VolumeChanged -= value; } /// <inheritdoc/> public event DomEventHandler Waiting { add => WrappedElement.Waiting += value; remove => WrappedElement.Waiting -= value; } /// <inheritdoc/> #endregion #region Properties and indexers [DebuggerHidden] public IElement? this[Int32 index] { get => WrappedElement[index]; } /// <inheritdoc/> [DebuggerHidden] public IElement? this[String name] { get => WrappedElement[name]; } /// <inheritdoc/> [DebuggerHidden] public String? AcceptCharset { get => WrappedElement.AcceptCharset; set => WrappedElement.AcceptCharset = value;} /// <inheritdoc/> [DebuggerHidden] public String? AccessKey { get => WrappedElement.AccessKey; set => WrappedElement.AccessKey = value;} /// <inheritdoc/> [DebuggerHidden] public String? AccessKeyLabel { get => WrappedElement.AccessKeyLabel; } /// <inheritdoc/> [DebuggerHidden] public String Action { get => WrappedElement.Action; set => WrappedElement.Action = value;} /// <inheritdoc/> [DebuggerHidden] public IElement? AssignedSlot { get => WrappedElement.AssignedSlot; } /// <inheritdoc/> [DebuggerHidden] public INamedNodeMap Attributes { get => WrappedElement.Attributes; } /// <inheritdoc/> [DebuggerHidden] public String? Autocomplete { get => WrappedElement.Autocomplete; set => WrappedElement.Autocomplete = value;} /// <inheritdoc/> [DebuggerHidden] public String BaseUri { get => WrappedElement.BaseUri; } /// <inheritdoc/> [DebuggerHidden] public Url? BaseUrl { get => WrappedElement.BaseUrl; } /// <inheritdoc/> [DebuggerHidden] public Int32 ChildElementCount { get => WrappedElement.ChildElementCount; } /// <inheritdoc/> [DebuggerHidden] public INodeList ChildNodes { get => WrappedElement.ChildNodes; } /// <inheritdoc/> [DebuggerHidden] public IHtmlCollection<IElement> Children { get => WrappedElement.Children; } /// <inheritdoc/> [DebuggerHidden] public ITokenList ClassList { get => WrappedElement.ClassList; } /// <inheritdoc/> [DebuggerHidden] public String? ClassName { get => WrappedElement.ClassName; set => WrappedElement.ClassName = value;} /// <inheritdoc/> [DebuggerHidden] public String? ContentEditable { get => WrappedElement.ContentEditable; set => WrappedElement.ContentEditable = value;} /// <inheritdoc/> [DebuggerHidden] public IHtmlMenuElement? ContextMenu { get => WrappedElement.ContextMenu; set => WrappedElement.ContextMenu = value;} /// <inheritdoc/> [DebuggerHidden] public IStringMap Dataset { get => WrappedElement.Dataset; } /// <inheritdoc/> [DebuggerHidden] public String? Direction { get => WrappedElement.Direction; set => WrappedElement.Direction = value;} /// <inheritdoc/> [DebuggerHidden] public ISettableTokenList DropZone { get => WrappedElement.DropZone; } /// <inheritdoc/> [DebuggerHidden] public IHtmlFormControlsCollection Elements { get => WrappedElement.Elements; } /// <inheritdoc/> [DebuggerHidden] public String Encoding { get => WrappedElement.Encoding; set => WrappedElement.Encoding = value;} /// <inheritdoc/> [DebuggerHidden] public String? Enctype { get => WrappedElement.Enctype; set => WrappedElement.Enctype = value;} /// <inheritdoc/> [DebuggerHidden] public INode? FirstChild { get => WrappedElement.FirstChild; } /// <inheritdoc/> [DebuggerHidden] public IElement? FirstElementChild { get => WrappedElement.FirstElementChild; } /// <inheritdoc/> [DebuggerHidden] public NodeFlags Flags { get => WrappedElement.Flags; } /// <inheritdoc/> [DebuggerHidden] public Boolean HasChildNodes { get => WrappedElement.HasChildNodes; } /// <inheritdoc/> [DebuggerHidden] public String? Id { get => WrappedElement.Id; set => WrappedElement.Id = value;} /// <inheritdoc/> [DebuggerHidden] public String InnerHtml { get => WrappedElement.InnerHtml; set => WrappedElement.InnerHtml = value;} /// <inheritdoc/> [DebuggerHidden] public Boolean IsContentEditable { get => WrappedElement.IsContentEditable; } /// <inheritdoc/> [DebuggerHidden] public Boolean IsDraggable { get => WrappedElement.IsDraggable; set => WrappedElement.IsDraggable = value;} /// <inheritdoc/> [DebuggerHidden] public Boolean IsFocused { get => WrappedElement.IsFocused; } /// <inheritdoc/> [DebuggerHidden] public Boolean IsHidden { get => WrappedElement.IsHidden; set => WrappedElement.IsHidden = value;} /// <inheritdoc/> [DebuggerHidden] public Boolean IsSpellChecked { get => WrappedElement.IsSpellChecked; set => WrappedElement.IsSpellChecked = value;} /// <inheritdoc/> [DebuggerHidden] public Boolean IsTranslated { get => WrappedElement.IsTranslated; set => WrappedElement.IsTranslated = value;} /// <inheritdoc/> [DebuggerHidden] public String? Language { get => WrappedElement.Language; set => WrappedElement.Language = value;} /// <inheritdoc/> [DebuggerHidden] public INode? LastChild { get => WrappedElement.LastChild; } /// <inheritdoc/> [DebuggerHidden] public IElement? LastElementChild { get => WrappedElement.LastElementChild; } /// <inheritdoc/> [DebuggerHidden] public Int32 Length { get => WrappedElement.Length; } /// <inheritdoc/> [DebuggerHidden] public String LocalName { get => WrappedElement.LocalName; } /// <inheritdoc/> [DebuggerHidden] public String Method { get => WrappedElement.Method; set => WrappedElement.Method = value;} /// <inheritdoc/> [DebuggerHidden] public String? Name { get => WrappedElement.Name; set => WrappedElement.Name = value;} /// <inheritdoc/> [DebuggerHidden] public String? NamespaceUri { get => WrappedElement.NamespaceUri; } /// <inheritdoc/> [DebuggerHidden] public IElement? NextElementSibling { get => WrappedElement.NextElementSibling; } /// <inheritdoc/> [DebuggerHidden] public INode? NextSibling { get => WrappedElement.NextSibling; } /// <inheritdoc/> [DebuggerHidden] public String NodeName { get => WrappedElement.NodeName; } /// <inheritdoc/> [DebuggerHidden] public NodeType NodeType { get => WrappedElement.NodeType; } /// <inheritdoc/> [DebuggerHidden] public String NodeValue { get => WrappedElement.NodeValue; set => WrappedElement.NodeValue = value;} /// <inheritdoc/> [DebuggerHidden] public Boolean NoValidate { get => WrappedElement.NoValidate; set => WrappedElement.NoValidate = value;} /// <inheritdoc/> [DebuggerHidden] public String OuterHtml { get => WrappedElement.OuterHtml; set => WrappedElement.OuterHtml = value;} /// <inheritdoc/> [DebuggerHidden] public IDocument? Owner { get => WrappedElement.Owner; } /// <inheritdoc/> [DebuggerHidden] public INode? Parent { get => WrappedElement.Parent; } /// <inheritdoc/> [DebuggerHidden] public IElement? ParentElement { get => WrappedElement.ParentElement; } /// <inheritdoc/> [DebuggerHidden] public String? Prefix { get => WrappedElement.Prefix; } /// <inheritdoc/> [DebuggerHidden] public IElement? PreviousElementSibling { get => WrappedElement.PreviousElementSibling; } /// <inheritdoc/> [DebuggerHidden] public INode? PreviousSibling { get => WrappedElement.PreviousSibling; } /// <inheritdoc/> [DebuggerHidden] public IShadowRoot? ShadowRoot { get => WrappedElement.ShadowRoot; } /// <inheritdoc/> [DebuggerHidden] public String? Slot { get => WrappedElement.Slot; set => WrappedElement.Slot = value;} /// <inheritdoc/> [DebuggerHidden] public ISourceReference? SourceReference { get => WrappedElement.SourceReference; } /// <inheritdoc/> [DebuggerHidden] public Int32 TabIndex { get => WrappedElement.TabIndex; set => WrappedElement.TabIndex = value;} /// <inheritdoc/> [DebuggerHidden] public String TagName { get => WrappedElement.TagName; } /// <inheritdoc/> [DebuggerHidden] public String Target { get => WrappedElement.Target; set => WrappedElement.Target = value;} /// <inheritdoc/> [DebuggerHidden] public String TextContent { get => WrappedElement.TextContent; set => WrappedElement.TextContent = value;} /// <inheritdoc/> [DebuggerHidden] public String? Title { get => WrappedElement.Title; set => WrappedElement.Title = value;} /// <inheritdoc/> #endregion #region Methods [DebuggerHidden] public void AddEventListener(String type, DomEventHandler? callback, Boolean capture) => WrappedElement.AddEventListener(type, callback, capture); /// <inheritdoc/> [DebuggerHidden] public void After(INode[] nodes) => WrappedElement.After(nodes); /// <inheritdoc/> [DebuggerHidden] public void Append(INode[] nodes) => WrappedElement.Append(nodes); /// <inheritdoc/> [DebuggerHidden] public INode AppendChild(INode child) => WrappedElement.AppendChild(child); /// <inheritdoc/> [DebuggerHidden] public IShadowRoot AttachShadow(ShadowRootMode mode) => WrappedElement.AttachShadow(mode); /// <inheritdoc/> [DebuggerHidden] public void Before(INode[] nodes) => WrappedElement.Before(nodes); /// <inheritdoc/> [DebuggerHidden] public Boolean CheckValidity() => WrappedElement.CheckValidity(); /// <inheritdoc/> [DebuggerHidden] public INode Clone(Boolean deep) => WrappedElement.Clone(deep); /// <inheritdoc/> [DebuggerHidden] public IElement? Closest(String selectors) => WrappedElement.Closest(selectors); /// <inheritdoc/> [DebuggerHidden] public DocumentPositions CompareDocumentPosition(INode otherNode) => WrappedElement.CompareDocumentPosition(otherNode); /// <inheritdoc/> [DebuggerHidden] public Boolean Contains(INode otherNode) => WrappedElement.Contains(otherNode); /// <inheritdoc/> [DebuggerHidden] public Boolean Dispatch(Event ev) => WrappedElement.Dispatch(ev); /// <inheritdoc/> [DebuggerHidden] public void DoBlur() => WrappedElement.DoBlur(); /// <inheritdoc/> [DebuggerHidden] public void DoClick() => WrappedElement.DoClick(); /// <inheritdoc/> [DebuggerHidden] public void DoFocus() => WrappedElement.DoFocus(); /// <inheritdoc/> [DebuggerHidden] public void DoSpellCheck() => WrappedElement.DoSpellCheck(); /// <inheritdoc/> [DebuggerHidden] public Boolean Equals(INode otherNode) => WrappedElement.Equals(otherNode); /// <inheritdoc/> [DebuggerHidden] public String? GetAttribute(String name) => WrappedElement.GetAttribute(name); /// <inheritdoc/> [DebuggerHidden] public String? GetAttribute(String? namespaceUri, String localName) => WrappedElement.GetAttribute(namespaceUri, localName); /// <inheritdoc/> [DebuggerHidden] public IHtmlCollection<IElement> GetElementsByClassName(String classNames) => WrappedElement.GetElementsByClassName(classNames); /// <inheritdoc/> [DebuggerHidden] public IHtmlCollection<IElement> GetElementsByTagName(String tagName) => WrappedElement.GetElementsByTagName(tagName); /// <inheritdoc/> [DebuggerHidden] public IHtmlCollection<IElement> GetElementsByTagNameNS(String namespaceUri, String tagName) => WrappedElement.GetElementsByTagNameNS(namespaceUri, tagName); /// <inheritdoc/> [DebuggerHidden] public DocumentRequest? GetSubmission() => WrappedElement.GetSubmission(); /// <inheritdoc/> [DebuggerHidden] public DocumentRequest? GetSubmission(IHtmlElement sourceElement) => WrappedElement.GetSubmission(sourceElement); /// <inheritdoc/> [DebuggerHidden] public Boolean HasAttribute(String name) => WrappedElement.HasAttribute(name); /// <inheritdoc/> [DebuggerHidden] public Boolean HasAttribute(String? namespaceUri, String localName) => WrappedElement.HasAttribute(namespaceUri, localName); /// <inheritdoc/> [DebuggerHidden] public void Insert(AdjacentPosition position, String html) => WrappedElement.Insert(position, html); /// <inheritdoc/> [DebuggerHidden] public INode InsertBefore(INode newElement, INode? referenceElement) => WrappedElement.InsertBefore(newElement, referenceElement); /// <inheritdoc/> [DebuggerHidden] public void InvokeEventListener(Event ev) => WrappedElement.InvokeEventListener(ev); /// <inheritdoc/> [DebuggerHidden] public Boolean IsDefaultNamespace(String namespaceUri) => WrappedElement.IsDefaultNamespace(namespaceUri); /// <inheritdoc/> [DebuggerHidden] public String? LookupNamespaceUri(String prefix) => WrappedElement.LookupNamespaceUri(prefix); /// <inheritdoc/> [DebuggerHidden] public String? LookupPrefix(String namespaceUri) => WrappedElement.LookupPrefix(namespaceUri); /// <inheritdoc/> [DebuggerHidden] public Boolean Matches(String selectors) => WrappedElement.Matches(selectors); /// <inheritdoc/> [DebuggerHidden] public void Normalize() => WrappedElement.Normalize(); /// <inheritdoc/> [DebuggerHidden] public void Prepend(INode[] nodes) => WrappedElement.Prepend(nodes); /// <inheritdoc/> [DebuggerHidden] public IElement? QuerySelector(String selectors) => WrappedElement.QuerySelector(selectors); /// <inheritdoc/> [DebuggerHidden] public IHtmlCollection<IElement> QuerySelectorAll(String selectors) => WrappedElement.QuerySelectorAll(selectors); /// <inheritdoc/> [DebuggerHidden] public void Remove() => WrappedElement.Remove(); /// <inheritdoc/> [DebuggerHidden] public Boolean RemoveAttribute(String name) => WrappedElement.RemoveAttribute(name); /// <inheritdoc/> [DebuggerHidden] public Boolean RemoveAttribute(String namespaceUri, String localName) => WrappedElement.RemoveAttribute(namespaceUri, localName); /// <inheritdoc/> [DebuggerHidden] public INode RemoveChild(INode child) => WrappedElement.RemoveChild(child); /// <inheritdoc/> [DebuggerHidden] public void RemoveEventListener(String type, DomEventHandler? callback, Boolean capture) => WrappedElement.RemoveEventListener(type, callback, capture); /// <inheritdoc/> [DebuggerHidden] public void Replace(INode[] nodes) => WrappedElement.Replace(nodes); /// <inheritdoc/> [DebuggerHidden] public INode ReplaceChild(INode newChild, INode oldChild) => WrappedElement.ReplaceChild(newChild, oldChild); /// <inheritdoc/> [DebuggerHidden] public Boolean ReportValidity() => WrappedElement.ReportValidity(); /// <inheritdoc/> [DebuggerHidden] public void RequestAutocomplete() => WrappedElement.RequestAutocomplete(); /// <inheritdoc/> [DebuggerHidden] public void Reset() => WrappedElement.Reset(); /// <inheritdoc/> [DebuggerHidden] public void SetAttribute(String name, String value) => WrappedElement.SetAttribute(name, value); /// <inheritdoc/> [DebuggerHidden] public void SetAttribute(String namespaceUri, String name, String value) => WrappedElement.SetAttribute(namespaceUri, name, value); /// <inheritdoc/> [DebuggerHidden] public Task<IDocument> SubmitAsync() => WrappedElement.SubmitAsync(); /// <inheritdoc/> [DebuggerHidden] public Task<IDocument> SubmitAsync(IHtmlElement sourceElement) => WrappedElement.SubmitAsync(sourceElement); /// <inheritdoc/> [DebuggerHidden] public void ToHtml(TextWriter writer, IMarkupFormatter formatter) => WrappedElement.ToHtml(writer, formatter); #endregion } }
53.849206
165
0.649116
[ "MIT" ]
egil/razor-component-testing-library
src/AngleSharpWrappers/Generated/HtmlFormElementWrapper.g.cs
27,140
C#
using NittyGritty.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NittyGritty.Uwp.Activation.Operations.Configurations { public class ActionLaunchConfiguration { public ActionLaunchConfiguration(string action, MultiViewConfiguration<QueryString> view) { if (string.IsNullOrWhiteSpace(action)) { throw new ArgumentException("Action cannot be null, empty, or whitespace", nameof(action)); } Action = action; View = view ?? throw new ArgumentNullException(nameof(view)); } public string Action { get; } public MultiViewConfiguration<QueryString> View { get; } } }
27.857143
107
0.666667
[ "MIT" ]
MarkIvanDev/NittyGritty
NittyGritty/NittyGritty.Uwp.Activation/Operations/Configurations/ActionLaunchConfiguration.cs
782
C#
using Nursery.Utility; using System; using System.Threading.Tasks; namespace Nursery { delegate void TickHandler(); class Timer { public int TickMilliSeconds { get; set; } = 100; private bool Watching = false; private TickHandler Handler = null; public Timer(TickHandler handler) { this.Handler = handler; } public void Start() { if (!this.Watching) { this.Watching = true; var t = Task.Run(WatchLoop); // run in other thread } } public void Stop() { this.Watching = false; } private async Task WatchLoop() { Logger.DebugLog("*** Timer started."); while (true) { if (!Watching) { break; } try { this.Handler(); } catch (Exception e) { Logger.DebugLog("*** ERROR ON TIMER ***"); Logger.DebugLog(e.ToString()); } // wait to next loop await Task.Delay(TickMilliSeconds).ConfigureAwait(false); } Logger.DebugLog("*** Timer stopped."); } } }
21.911111
62
0.600406
[ "MIT" ]
noonworks/Nursery
Nursery/Timer.cs
988
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace UnoContoso.Service { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.925926
70
0.647143
[ "Apache-2.0" ]
MartinZikmund/Uno.Samples
UI/UnoContoso/UnoContoso.Service/Program.cs
700
C#
using System; using System.Collections.Generic; namespace ParkingLot { class Program { static void Main(string[] args) { HashSet<string> cars = new HashSet<string>(); while (true) { string input = Console.ReadLine(); if (input == "END") { break; } string[] parts = input.Split(", "); string command = parts[0]; string car = parts[1]; if (command == "IN") { cars.Add(car); } else { cars.Remove(car); } } if (cars.Count > 0) { foreach (var car in cars) { Console.WriteLine(car); } } else { Console.WriteLine("Parking Lot is Empty"); } } } }
23.840909
58
0.341277
[ "MIT" ]
Siafarikas/SoftUni
Advanced/SetsAndDictionaries/ParkingLot/Program.cs
1,051
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.AppService.Models; using Azure.ResourceManager.Core; namespace Azure.ResourceManager.AppService { internal partial class KubeEnvironmentsRestOperations { private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of KubeEnvironmentsRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="options"> The client options used to construct the current client. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception> public KubeEnvironmentsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ArmClientOptions options, Uri endpoint = null, string apiVersion = default) { this.endpoint = endpoint ?? new Uri("https://management.azure.com"); this.apiVersion = apiVersion ?? "2021-02-01"; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = HttpMessageUtilities.GetUserAgentName(this, options); } internal HttpMessage CreateListBySubscriptionRequest(string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Get all Kubernetes Environments for a subscription. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<Models.KubeEnvironmentCollection>> ListBySubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListBySubscriptionRequest(subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Get all Kubernetes Environments for a subscription. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public Response<Models.KubeEnvironmentCollection> ListBySubscription(string subscriptionId, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListBySubscriptionRequest(subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Get all the Kubernetes Environments in a resource group. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<Models.KubeEnvironmentCollection>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Get all the Kubernetes Environments in a resource group. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public Response<Models.KubeEnvironmentCollection> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string name) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments/", false); uri.AppendPath(name, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Get the properties of a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="name"/> is null. </exception> public async Task<Response<KubeEnvironmentData>> GetAsync(string subscriptionId, string resourceGroupName, string name, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, name); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { KubeEnvironmentData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = KubeEnvironmentData.DeserializeKubeEnvironmentData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((KubeEnvironmentData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Get the properties of a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="name"/> is null. </exception> public Response<KubeEnvironmentData> Get(string subscriptionId, string resourceGroupName, string name, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, name); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { KubeEnvironmentData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = KubeEnvironmentData.DeserializeKubeEnvironmentData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((KubeEnvironmentData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentData kubeEnvironmentEnvelope) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments/", false); uri.AppendPath(name, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(kubeEnvironmentEnvelope); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Creates or updates a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="kubeEnvironmentEnvelope"> Configuration details of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="name"/>, or <paramref name="kubeEnvironmentEnvelope"/> is null. </exception> public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentData kubeEnvironmentEnvelope, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (kubeEnvironmentEnvelope == null) { throw new ArgumentNullException(nameof(kubeEnvironmentEnvelope)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, name, kubeEnvironmentEnvelope); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Creates or updates a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="kubeEnvironmentEnvelope"> Configuration details of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="name"/>, or <paramref name="kubeEnvironmentEnvelope"/> is null. </exception> public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentData kubeEnvironmentEnvelope, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (kubeEnvironmentEnvelope == null) { throw new ArgumentNullException(nameof(kubeEnvironmentEnvelope)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, name, kubeEnvironmentEnvelope); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string name) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments/", false); uri.AppendPath(name, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Delete a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="name"/> is null. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string name, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, name); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Delete a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="name"/> is null. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string name, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, name); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentPatchResource kubeEnvironmentEnvelope) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Web/kubeEnvironments/", false); uri.AppendPath(name, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(kubeEnvironmentEnvelope); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Creates or updates a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="kubeEnvironmentEnvelope"> Configuration details of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="name"/>, or <paramref name="kubeEnvironmentEnvelope"/> is null. </exception> public async Task<Response<KubeEnvironmentData>> UpdateAsync(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentPatchResource kubeEnvironmentEnvelope, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (kubeEnvironmentEnvelope == null) { throw new ArgumentNullException(nameof(kubeEnvironmentEnvelope)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, name, kubeEnvironmentEnvelope); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { KubeEnvironmentData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = KubeEnvironmentData.DeserializeKubeEnvironmentData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Creates or updates a Kubernetes Environment. </summary> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="name"> Name of the Kubernetes Environment. </param> /// <param name="kubeEnvironmentEnvelope"> Configuration details of the Kubernetes Environment. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="name"/>, or <paramref name="kubeEnvironmentEnvelope"/> is null. </exception> public Response<KubeEnvironmentData> Update(string subscriptionId, string resourceGroupName, string name, KubeEnvironmentPatchResource kubeEnvironmentEnvelope, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (kubeEnvironmentEnvelope == null) { throw new ArgumentNullException(nameof(kubeEnvironmentEnvelope)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, name, kubeEnvironmentEnvelope); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { KubeEnvironmentData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = KubeEnvironmentData.DeserializeKubeEnvironmentData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListBySubscriptionNextPageRequest(string nextLink, string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Get all Kubernetes Environments for a subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<Models.KubeEnvironmentCollection>> ListBySubscriptionNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Get all Kubernetes Environments for a subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public Response<Models.KubeEnvironmentCollection> ListBySubscriptionNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Description for Get all the Kubernetes Environments in a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<Models.KubeEnvironmentCollection>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Description for Get all the Kubernetes Environments in a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). </param> /// <param name="resourceGroupName"> Name of the resource group to which the resource belongs. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public Response<Models.KubeEnvironmentCollection> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { Models.KubeEnvironmentCollection value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = Models.KubeEnvironmentCollection.DeserializeKubeEnvironmentCollection(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
54.906824
231
0.625158
[ "MIT" ]
BaherAbdullah/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Generated/RestOperations/KubeEnvironmentsRestOperations.cs
41,839
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Xml; using System.IO; using Xamarin.Android.Binder; namespace MonoDroid.Generation { public class ParameterList : IEnumerable<Parameter> { public static bool Equals (ParameterList l1, ParameterList l2) { if (l1.Count != l2.Count) return false; for (int i = 0; i < l1.Count; i++) if (!l1 [i].Equals (l2 [i])) return false; return true; } List<Parameter> items = new List<Parameter> (); public Parameter this [int idx] { get { return items [idx]; } } public IEnumerator<Parameter> GetEnumerator () { return items.GetEnumerator (); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return GetEnumerator (); } public string GetCall (CodeGenerationOptions opt) { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (sb.Length > 0) sb.Append (", "); sb.Append (opt.GetSafeIdentifier (p.Name)); } return sb.ToString (); } public string CallDropSender { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (p.IsSender) continue; else if (sb.Length > 0) sb.Append (", "); sb.Append (p.Name); } return sb.ToString (); } } public string JavaCall { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (sb.Length > 0) sb.Append (", "); sb.Append (p.JavaName); } return sb.ToString (); } } public string GetCallArgs (CodeGenerationOptions opt, bool invoker) { if (items.Count != 0) return ", __args"; if (opt.CodeGenerationTarget == CodeGenerationTarget.XamarinAndroid || invoker) return ""; return ", null"; } public StringCollection GetCallCleanup (CodeGenerationOptions opt) { StringCollection result = new StringCollection (); foreach (Parameter p in items) foreach (string s in p.GetPostCall (opt)) result.Add (s); return result; } public StringCollection GetCallPrep (CodeGenerationOptions opt) { StringCollection result = new StringCollection (); foreach (Parameter p in items) foreach (string s in p.GetPreCall (opt)) result.Add (s); return result; } public StringCollection GetCallbackCleanup (CodeGenerationOptions opt) { StringCollection result = new StringCollection (); foreach (Parameter p in items) foreach (string s in p.GetPostCallback (opt)) result.Add (s); return result; } public StringCollection GetCallbackPrep (CodeGenerationOptions opt) { StringCollection result = new StringCollection (); foreach (Parameter p in items) foreach (string s in p.GetPreCallback (opt)) result.Add (s); return result; } public string GetCallbackSignature (CodeGenerationOptions opt) { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { sb.Append (", "); sb.Append (p.NativeType); sb.Append (" "); sb.Append (opt.GetSafeIdentifier (p.UnsafeNativeName)); } return sb.ToString (); } public int Count { get { return items.Count; } } public string DelegateTypeParams { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { sb.Append (", "); sb.Append (p.NativeType); } return sb.ToString (); } } public bool HasCharSequence { get { foreach (Parameter p in items) if (p.JavaType.StartsWith("java.lang.CharSequence")) return true; return false; } } public bool HasCleanup { get { foreach (Parameter p in items) if (p.NeedsPrep) return true; return false; } } public bool HasGeneric { get { foreach (Parameter p in items) if (p.IsGeneric) return true; return false; } } public bool HasSender { get { foreach (Parameter p in items) if (p.IsSender) return true; return false; } } public string JavaSignature { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (sb.Length > 0) sb.Append (", "); sb.Append (p.JavaType); sb.Append (" "); sb.Append (p.JavaName); } return sb.ToString (); } } public string JniSignature { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) sb.Append (p.JniType); return sb.ToString (); } } public string JniNestedDerivedSignature { get { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (p.Name == "__self") { sb.Append ("L\" + global::Android.Runtime.JNIEnv.GetJniName (GetType ().DeclaringType) + \";"); continue; } sb.Append (p.JniType); } return sb.ToString (); } } public string SenderName { get { foreach (Parameter p in items) if (p.IsSender) return p.Name; return String.Empty; } } public string GetSignatureDropSender (CodeGenerationOptions opt) { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (p.IsSender) continue; else if (sb.Length > 0) sb.Append (", "); sb.Append (opt.GetOutputName (p.Type)); sb.Append (" "); sb.Append (p.Name); } return sb.ToString (); } public void Add (Parameter parm) { items.Add (parm); } public void AddFirst (Parameter parm) { items.Insert (0, parm); } public string GetGenericCall (CodeGenerationOptions opt, Dictionary<string, string> mappings) { StringBuilder sb = new StringBuilder (); foreach (Parameter p in items) { if (sb.Length > 0) sb.Append (", "); sb.Append (p.GetGenericCall (opt, mappings)); } return sb.ToString (); } public string GetMethodXPathPredicate () { if (items.Count == 0) return " and count(parameter)=0"; var sb = new StringBuilder (); sb.Append (" and count(parameter)=").Append (items.Count); for (int i = 0; i < items.Count; ++i) { sb.Append (" and parameter[").Append (i+1).Append ("]") .Append ("[@type='").Append (items [i].RawNativeType.Replace ("<", "&lt;").Replace (">","&gt;")).Append ("']"); } return sb.ToString (); } public bool Validate (CodeGenerationOptions opt, GenericParameterDefinitionList type_params, CodeGeneratorContext context) { foreach (Parameter p in items) if (!p.Validate (opt, type_params, context)) return false; return true; } } }
22.737931
124
0.631483
[ "MIT" ]
dellis1972/Java.Interop
tools/generator/Java.Interop.Tools.Generator.ObjectModel/ParameterList.cs
6,594
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using NewLife.Data; using NewLife.Net.Sockets; using System.Linq; namespace NewLife.Net.Stun { /// <summary>Stun客户端。Simple Traversal of UDP over NATs,NAT 的UDP简单穿越。RFC 3489</summary> /// <remarks> /// <a target="_blank" href="http://baike.baidu.com/view/884586.htm">STUN</a> /// /// 国内STUN服务器:220.181.126.73、220.181.126.74,位于北京电信,但不清楚是哪家公司 /// </remarks> /// <example> /// <code> /// var result = new StunClient().Query(); /// if(result.Type != StunNetType.UdpBlocked){ /// /// } /// else{ /// var publicEP = result.Public; /// } /// </code> /// </example> public class StunClient : Netbase { #region 工作原理 /* In test I, the client sends a STUN Binding Request to a server, without any flags set in the CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. This causes the server to send the response back to the address and port that the request came from. In test II, the client sends a Binding Request with both the "change IP" and "change port" flags from the CHANGE-REQUEST attribute set. In test III, the client sends a Binding Request with only the "change port" flag set. +--------+ | Test | | I | +--------+ | | V /\ /\ N / \ Y / \ Y +--------+ UDP <-------/Resp\--------->/ IP \------------->| Test | Blocked \ ? / \Same/ | II | \ / \? / +--------+ \/ \/ | | N | | V V /\ +--------+ Sym. N / \ | Test | UDP <---/Resp\ | II | Firewall \ ? / +--------+ \ / | \/ V |Y /\ /\ | Symmetric N / \ +--------+ N / \ V NAT <--- / IP \<-----| Test |<--- /Resp\ Open \Same/ | I | \ ? / Internet \? / +--------+ \ / \/ \/ | |Y | | | V | Full | Cone V /\ +--------+ / \ Y | Test |------>/Resp\---->Restricted | III | \ ? / +--------+ \ / \/ |N | Port +------>Restricted */ #endregion #region 服务器 //static String[] servers = new String[] { "stun.NewLifeX.com", "stun.sipgate.net:10000", "stunserver.org", "stun.xten.com", "stun.fwdnet.net", "stun.iptel.org", "220.181.126.73" }; static readonly String[] servers = new String[] { "stun.NewLifeX.com", "stun.sipgate.net:10000", "stun.xten.com", "stun.iptel.org", "220.181.126.73" }; private List<String> _Servers; /// <summary>Stun服务器</summary> public List<String> Servers { get { if (_Servers == null) { var list = new List<String>(); //var ss = Config.GetConfigSplit<String>("NewLife.Net.StunServers", null); //if (ss != null && ss.Length > 0) list.AddRange(ss); list.AddRange(servers); _Servers = list; } return _Servers; } } #endregion #region 属性 private ISocketClient _Socket; /// <summary>套接字</summary> public ISocketClient Socket { get { return _Socket; } set { _Socket = value; } } private ISocketClient _Socket2; /// <summary>用于测试更换本地套接字的第二套接字</summary> public ISocketClient Socket2 { get { return _Socket2; } set { _Socket2 = value; } } private NetType _ProtocolType = NetType.Udp; /// <summary>协议,默认Udp</summary> public NetType ProtocolType { get { return _ProtocolType; } set { _ProtocolType = value; } } private Int32 _Port; /// <summary>本地端口</summary> public Int32 Port { get { return _Port; } set { _Port = value; } } private Int32 _Timeout = 2000; /// <summary>超时时间,默认2000ms</summary> public Int32 Timeout { get { return _Timeout; } set { _Timeout = value; } } #endregion #region 构造 /// <summary>实例化</summary> public StunClient() { } /// <summary>在指定协议上执行查询</summary> /// <param name="protocol"></param> /// <returns></returns> public StunClient(NetType protocol) : this(protocol, 0) { } /// <summary>在指定协议和本地端口上执行查询</summary> /// <param name="protocol"></param> /// <param name="port"></param> /// <returns></returns> public StunClient(NetType protocol, Int32 port) { ProtocolType = protocol; Port = port; } /// <summary>在指定套接字上执行查询</summary> /// <param name="socket"></param> /// <returns></returns> public StunClient(ISocket socket) { // UDP可以直接使用,而Tcp需要另外处理 Socket = socket as ISocketClient; if (Socket == null) { //var client = NetService.Container.Resolve<ISocketClient>(socket.Local.ProtocolType); //var tcp = new TcpClient(); //tcp.Client = socket.Client; Socket = new TcpSession(socket.Client); } } // 如果是外部传进来的Socket,也销毁,就麻烦大了 ///// <summary>子类重载实现资源释放逻辑时必须首先调用基类方法</summary> ///// <param name="disposing">从Dispose调用(释放所有资源)还是析构函数调用(释放非托管资源)</param> //protected override void OnDispose(bool disposing) //{ // base.OnDispose(disposing); // if (_Socket != null) // { // _Socket.Dispose(); // _Socket = null; // } // if (_Socket2 != null) // { // _Socket2.Dispose(); // _Socket2 = null; // } //} #endregion #region 方法 void EnsureSocket() { if (_Socket == null) { //var client = NetService.Container.Resolve<ISocketClient>(ProtocolType); //client.Port = Port; var client = new NetUri(ProtocolType, "", Port).CreateClient(); client.Open(); client.Client.SendTimeout = Timeout; client.Client.ReceiveTimeout = Timeout; _Socket = client; } } void EnsureSocket2() { if (_Socket2 == null) { var socket = Socket.Client; var ep = socket.LocalEndPoint as IPEndPoint; var sto = socket.SendTimeout; var rto = socket.ReceiveTimeout; // 如果原端口没有启用地址重用,则关闭它 var value = socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress); if (!Convert.ToBoolean(value)) socket.Close(); //var sk = NetService.Container.Resolve<ISocketClient>(socket.ProtocolType); ////sk.Address = ep.Address; ////sk.Port = ep.Port; //sk.Local.EndPoint = ep; var sk = new NetUri((NetType)socket.ProtocolType, ep).CreateClient(); sk.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //sk.Bind(); sk.Client.SendTimeout = sto; sk.Client.ReceiveTimeout = rto; _Socket2 = sk; } } #endregion #region 查询 /// <summary>按服务器列表执行查询</summary> /// <returns></returns> public StunResult Query() { foreach (var result in QueryByServers()) { if (result != null && result.Type != StunNetType.Blocked) return result; } return null; } IEnumerable<StunResult> QueryByServers() { // 如果是被屏蔽,很有可能是因为服务器没有响应,可以通过轮换服务器来测试 StunResult result = null; foreach (var item in Servers) { WriteLog("使用服务器:{0}", item); //Int32 p = item.IndexOf(":"); //if (p > 0) // result = QueryWithServer(item.Substring(0, p), Int32.Parse(item.Substring(p + 1))); //else // result = QueryWithServer(item, 3478); var ep = NetHelper.ParseEndPoint(item, 3478); try { result = QueryWithServer(ep.Address, ep.Port); } catch { result = null; } yield return result; } } ///// <summary>在指定服务器上执行查询</summary> ///// <param name="host"></param> ///// <param name="port"></param> ///// <returns></returns> //public StunResult QueryWithServer(String host, Int32 port = 3478) //{ // try // { // return QueryWithServer(NetHelper.ParseAddress(host), port); // } // catch { return null; } //} /// <summary>在指定服务器上执行查询</summary> /// <param name="address"></param> /// <param name="port"></param> /// <returns></returns> public StunResult QueryWithServer(IPAddress address, Int32 port) { EnsureSocket(); var client = Socket as ISocketClient; var remote = new IPEndPoint(address, port); // Test I // 测试网络是否畅通 var msg = new StunMessage { Type = StunMessageType.BindingRequest }; var rs = Query(client, msg, remote); // UDP blocked. if (rs == null) return new StunResult(StunNetType.Blocked, null); WriteLog("服务器:{0}", rs.ServerName); WriteLog("映射地址:{0}", rs.MappedAddress); WriteLog("源地址:{0}", rs.SourceAddress); WriteLog("新地址:{0}", rs.ChangedAddress); var remote2 = rs.ChangedAddress; // Test II // 要求改变IP和端口 msg.ChangeIP = true; msg.ChangePort = true; msg.ResetTransactionID(); // 如果本地地址就是映射地址,表示没有NAT。这里的本地地址应该有问题,永远都会是0.0.0.0 //if (client.LocalEndPoint.Equals(test1response.MappedAddress)) var pub = rs.MappedAddress; if (pub != null && client.Local.Port == pub.Port && pub.Address.IsLocal()) { // 要求STUN服务器从另一个地址和端口向当前映射端口发送消息。如果收到,表明是完全开放网络;如果没收到,可能是防火墙阻止了。 rs = Query(client, msg, remote); // Open Internet. if (rs != null) return new StunResult(StunNetType.OpenInternet, pub); // Symmetric UDP firewall. return new StunResult(StunNetType.SymmetricUdpFirewall, pub); } else { rs = Query(client, msg, remote); if (rs != null && pub == null) pub = rs.MappedAddress; // Full cone NAT. if (rs != null) return new StunResult(StunNetType.FullCone, pub); // Test II msg.ChangeIP = false; msg.ChangePort = false; msg.ResetTransactionID(); // 如果是Tcp,这里需要准备第二个重用的Socket if (client.Local.IsTcp) { EnsureSocket2(); client = Socket2 as ISocketClient; } rs = Query(client, msg, remote2); // 如果第二服务器没响应,重试 if (rs == null) rs = Query(client, msg, remote2); if (rs != null && pub == null) pub = rs.MappedAddress; if (rs == null) return new StunResult(StunNetType.Blocked, pub); // 两次映射地址不一样,对称网络 if (!rs.MappedAddress.Equals(pub)) return new StunResult(StunNetType.Symmetric, pub); // Test III msg.ChangeIP = false; msg.ChangePort = true; msg.ResetTransactionID(); rs = Query(client, msg, remote2); if (rs != null && pub == null) pub = rs.MappedAddress; // 受限 if (rs != null) return new StunResult(StunNetType.AddressRestrictedCone, pub); // 端口受限 return new StunResult(StunNetType.PortRestrictedCone, pub); } } #endregion #region 获取公网地址 /// <summary>获取公网地址</summary> /// <returns></returns> public IPEndPoint GetPublic() { EnsureSocket(); //var socket = Socket.Socket; var msg = new StunMessage { Type = StunMessageType.BindingRequest }; IPEndPoint ep = null; foreach (var item in Servers) { try { ep = NetHelper.ParseEndPoint(item, 3478); } catch { continue; } //Int32 p = item.IndexOf(":"); //if (p > 0) // ep = new IPEndPoint(NetHelper.ParseAddress(item.Substring(0, p)), Int32.Parse(item.Substring(p + 1))); //else // ep = new IPEndPoint(NetHelper.ParseAddress(item), 3478); var rs = Query(Socket, msg, ep); if (rs != null && rs.MappedAddress != null) return rs.MappedAddress; } return null; } #endregion #region 业务 /// <summary>查询</summary> /// <param name="request"></param> /// <param name="remoteEndPoint"></param> /// <returns></returns> public StunMessage Query(StunMessage request, IPEndPoint remoteEndPoint) { EnsureSocket(); return Query(Socket, request, remoteEndPoint); } StunMessage Query(ISocketClient client, StunMessage request, IPEndPoint remoteEndPoint) { Packet pk = null; try { if (client.Local.IsTcp) { // Tcp协议不支持更换IP或者端口 if (request.ChangeIP || request.ChangePort) return null; //if (!client.Connected) client.Connect(remoteEndPoint); //client.Send(request.ToArray()); } //else // client.SendTo(request.ToArray(), remoteEndPoint); WriteLog("查询 {0} =>{1}", request, remoteEndPoint); client.Remote.EndPoint = remoteEndPoint; client.Send(request.ToArray()); pk = client.Receive(); if (pk == null || pk.Count == 0) return null; } catch { return null; } var rs = StunMessage.Read(pk.GetStream()); //if (rs != null && rs.Type != StunMessageType.BindingResponse) return null; if (rs == null) return null; // 不是同一个会话不要 if (!rs.TransactionID.SequenceEqual(request.TransactionID)) return null; // 不是期望的响应不要 if (rs.Type != (StunMessageType)((UInt16)request.Type | 0x0100)) return null; return rs; } #endregion } }
38.76392
190
0.42867
[ "MIT" ]
NewLifeX/NewLife.Net
NewLife.Net/Stun/StunClient.cs
18,453
C#
namespace LambdaText { partial class GotoForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GotoForm)); this.txtGotoText = new System.Windows.Forms.TextBox(); this.btnCancel = new System.Windows.Forms.Button(); this.btnReplace = new System.Windows.Forms.Button(); this.SuspendLayout(); // // txtGotoText // this.txtGotoText.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtGotoText.Location = new System.Drawing.Point(13, 13); this.txtGotoText.Name = "txtGotoText"; this.txtGotoText.Size = new System.Drawing.Size(271, 24); this.txtGotoText.TabIndex = 0; // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(60, 51); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(84, 31); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnReplace // this.btnReplace.Location = new System.Drawing.Point(162, 51); this.btnReplace.Name = "btnReplace"; this.btnReplace.Size = new System.Drawing.Size(84, 31); this.btnReplace.TabIndex = 2; this.btnReplace.Text = "Go"; this.btnReplace.UseVisualStyleBackColor = true; this.btnReplace.Click += new System.EventHandler(this.btnFind_Click); // // GotoForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(297, 105); this.Controls.Add(this.btnReplace); this.Controls.Add(this.btnCancel); this.Controls.Add(this.txtGotoText); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "GotoForm"; this.Text = "Go To Line"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtGotoText; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnReplace; } }
41.747126
162
0.568282
[ "MIT" ]
Xangis/ZetaWord
GotoForm.Designer.cs
3,634
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Yomiage.GUI.Dialog.Views { /// <summary> /// PauseEditDialog.xaml の相互作用ロジック /// </summary> public partial class PauseEditDialog : UserControl { public PauseEditDialog() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { this.InputTextBox.Focus(); Task.Run(async () => { await Task.Delay(300); this.Dispatcher.Invoke(() => { this.InputTextBox.Focus(); this.InputTextBox.SelectAll(); }); }); } } }
24.906977
73
0.602241
[ "MIT" ]
InochiPM/YomiageLibrary
Yomiage.GUI/Dialog/Views/PauseEditDialog.xaml.cs
1,091
C#
// Note: this script has to be on an always-active UI parent, so that we can // always find it from other code. (GameObject.Find doesn't find inactive ones) using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; public partial class UILoot : MonoBehaviour { public GameObject panel; public GameObject goldSlot; public Text goldText; public UILootSlot itemSlotPrefab; public Transform content; void Update() { Player player = Utils.ClientLocalPlayer(); if (!player) return; // use collider point(s) to also work with big entities if (panel.activeSelf && player.target != null && player.target.health == 0 && Utils.ClosestDistance(player.collider, player.target.collider) <= player.interactionRange && player.target is Monster && ((Monster)player.target).HasLoot()) { // gold slot if (player.target.gold > 0) { goldSlot.SetActive(true); goldSlot.GetComponentInChildren<Button>().onClick.SetListener(() => { player.CmdTakeLootGold(); }); goldText.text = player.target.gold.ToString(); } else goldSlot.SetActive(false); // instantiate/destroy enough slots // (we only want to show the non-empty slots) List<ItemSlot> items = player.target.inventory.Where(slot => slot.amount > 0).ToList(); UIUtils.BalancePrefabs(itemSlotPrefab.gameObject, items.Count, content); // refresh all valid items for (int i = 0; i < items.Count; ++i) { UILootSlot slot = content.GetChild(i).GetComponent<UILootSlot>(); slot.dragAndDropable.name = i.ToString(); // drag and drop index int itemIndex = player.target.inventory.FindIndex( // note: .Equals because name AND dynamic variables matter (petLevel etc.) itemSlot => itemSlot.amount > 0 && itemSlot.item.Equals(items[i].item) ); // refresh slot.button.interactable = player.InventoryCanAdd(items[i].item, items[i].amount); slot.button.onClick.SetListener(() => { player.CmdTakeLootItem(itemIndex); }); slot.tooltip.text = items[i].ToolTip(); slot.image.color = Color.white; slot.image.sprite = items[i].item.image; slot.nameText.text = items[i].item.name; slot.amountOverlay.SetActive(items[i].amount > 1); slot.amountText.text = items[i].amount.ToString(); } } else panel.SetActive(false); // hide } public void Show() { panel.SetActive(true); } }
39.726027
104
0.573103
[ "MIT" ]
thoang126/RPG2D-10-6-18-Morning-Working-Saved
Assets/uMMORPG/Scripts/_UI/UILoot.cs
2,902
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.ContentManagement.Metadata; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Menu.Models; using YesSql; namespace OrchardCore.Menu.Controllers { public class AdminController : Controller, IUpdateModel { private readonly IContentManager _contentManager; private readonly IAuthorizationService _authorizationService; private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISession _session; private readonly INotifier _notifier; public AdminController( ISession session, IContentManager contentManager, IAuthorizationService authorizationService, IContentItemDisplayManager contentItemDisplayManager, IContentDefinitionManager contentDefinitionManager, INotifier notifier, IHtmlLocalizer<AdminController> h) { _contentManager = contentManager; _authorizationService = authorizationService; _contentItemDisplayManager = contentItemDisplayManager; _contentDefinitionManager = contentDefinitionManager; _session = session; _notifier = notifier; H = h; } public IHtmlLocalizer H { get; set; } public async Task<IActionResult> Create(string id, string menuContentItemId, string menuItemId) { if (String.IsNullOrWhiteSpace(id)) { return NotFound(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu)) { return Unauthorized(); } var contentItem = _contentManager.New(id); dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, this, true); model.MenuContentItemId = menuContentItemId; model.MenuItemId = menuItemId; return View(model); } [HttpPost] [ActionName("Create")] public async Task<IActionResult> CreatePost(string id, string menuContentItemId, string menuItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu)) { return Unauthorized(); } ContentItem menu; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu"); if (!contentTypeDefinition.Settings.ToObject<ContentTypeSettings>().Draftable) { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest); } else { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired); } if (menu == null) { return NotFound(); } var contentItem = _contentManager.New(id); var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this, true); if (!ModelState.IsValid) { return View(model); } if (menuItemId == null) { // Use the menu as the parent if no target is specified menu.Alter<MenuItemsListPart>(part => part.MenuItems.Add(contentItem)); } else { // Look for the target menu item in the hierarchy var parentMenuItem = FindMenuItem(menu.Content, menuItemId); // Couldn't find targetted menu item if (parentMenuItem == null) { return NotFound(); } var menuItems = parentMenuItem?.MenuItemsListPart?.MenuItems as JArray; if (menuItems == null) { parentMenuItem["MenuItemsListPart"] = new JObject( new JProperty("MenuItems", menuItems = new JArray()) ); } menuItems.Add(JObject.FromObject(contentItem)); } _session.Save(menu); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId }); } public async Task<IActionResult> Edit(string menuContentItemId, string menuItemId) { var menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest); if (menu == null) { return NotFound(); } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu, menu)) { return Unauthorized(); } // Look for the target menu item in the hierarchy JObject menuItem = FindMenuItem(menu.Content, menuItemId); // Couldn't find targetted menu item if (menuItem == null) { return NotFound(); } var contentItem = menuItem.ToObject<ContentItem>(); dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, this, false); model.MenuContentItemId = menuContentItemId; model.MenuItemId = menuItemId; return View(model); } [HttpPost] [ActionName("Edit")] public async Task<IActionResult> EditPost(string menuContentItemId, string menuItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu)) { return Unauthorized(); } ContentItem menu; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu"); if (!contentTypeDefinition.Settings.ToObject<ContentTypeSettings>().Draftable) { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest); } else { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired); } if (menu == null) { return NotFound(); } // Look for the target menu item in the hierarchy JObject menuItem = FindMenuItem(menu.Content, menuItemId); // Couldn't find targetted menu item if (menuItem == null) { return NotFound(); } var contentItem = menuItem.ToObject<ContentItem>(); var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this, false); if (!ModelState.IsValid) { return View(model); } menuItem.Merge(contentItem.Content, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); _session.Save(menu); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId }); } [HttpPost] public async Task<IActionResult> Delete(string menuContentItemId, string menuItemId) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu)) { return Unauthorized(); } ContentItem menu; var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu"); if (!contentTypeDefinition.Settings.ToObject<ContentTypeSettings>().Draftable) { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest); } else { menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired); } if (menu == null) { return NotFound(); } // Look for the target menu item in the hierarchy var menuItem = FindMenuItem(menu.Content, menuItemId); // Couldn't find targetted menu item if (menuItem == null) { return NotFound(); } menuItem.Remove(); _session.Save(menu); _notifier.Success(H["Menu item deleted successfully"]); return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId }); } private JObject FindMenuItem(JObject contentItem, string menuItemId) { if (contentItem["ContentItemId"]?.Value<string>() == menuItemId) { return contentItem; } if (contentItem.GetValue("MenuItemsListPart") == null) { return null; } var menuItems = (JArray) contentItem["MenuItemsListPart"]["MenuItems"]; JObject result; foreach(JObject menuItem in menuItems) { // Search in inner menu items result = FindMenuItem(menuItem, menuItemId); if (result != null) { return result; } } return null; } } }
33.013468
127
0.580316
[ "BSD-3-Clause" ]
codeyu/OrchardCore
src/OrchardCore.Modules/OrchardCore.Menu/Controllers/AdminController.cs
9,805
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Abp.AutoMapper; using Don.SportsStoreCore.Authorization.Roles; using Abp.Authorization.Roles; namespace Don.SportsStoreCore.Roles.Dto { [AutoMapTo(typeof(Role))] public class CreateRoleDto { [Required] [StringLength(AbpRoleBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpRoleBase.MaxDisplayNameLength)] public string DisplayName { get; set; } public string NormalizedName { get; set; } [StringLength(Role.MaxDescriptionLength)] public string Description { get; set; } public bool IsStatic { get; set; } public List<string> Permissions { get; set; } } }
26.6
56
0.666667
[ "MIT" ]
antgerasim/Don.SportsStoreCore
aspnet-core/src/Don.SportsStoreCore.Application/Roles/Dto/CreateRoleDto.cs
798
C#
/* * Created by: Miguel Angel Medina Pérez (migue.cu@gmail.com) * Created: June 8, 2010 * Comments by: Miguel Angel Medina Pérez (migue.cu@gmail.com) */ using System; using System.IO; namespace PatternRecognition.FingerprintRecognition.Core { /// <summary> /// Allows saving and retrieving instances of <see cref="SkeletonImage"/>. /// </summary> public static class SkeletonImageSerializer { /// <summary> /// Save the specified <see cref="SkeletonImage"/> to the specified file name. /// </summary> /// <remarks> /// Before saving, the <see cref="SkeletonImage"/> is encoded using the method <see cref="ToByteArray"/>. /// </remarks> /// <param name="fileName">The file name where the specified <see cref="SkeletonImage"/> will be saved.</param> /// <param name="skImg">The <see cref="SkeletonImage"/> to be saved.</param> public static void Serialize(string fileName, SkeletonImage skImg) { var byteArr = ToByteArray(skImg); File.WriteAllBytes(fileName, byteArr); } /// <summary> /// Load the <see cref="SkeletonImage"/> saved in the specified file name. /// </summary> /// <remarks> /// The <see cref="SkeletonImage"/> are decoded using method <see cref="FromByteArray"/>. /// </remarks> /// <param name="fileName">The file name where the<see cref="SkeletonImage"/> is saved.</param> /// <returns>The <see cref="SkeletonImage"/> loaded from file.</returns> public static SkeletonImage Deserialize(string fileName) { var byteArr = File.ReadAllBytes(fileName); return FromByteArray(byteArr); } /// <summary> /// Decodes a <see cref="SkeletonImage"/> object from a byte array. /// </summary> /// <remarks> /// This codification uses two bytes to store <see cref="SkeletonImage.Width"/>; two more bytes to store <see cref="SkeletonImage.Height"/>; and one bit for each pixel of the <see cref="SkeletonImage"/>. Therefore, this method is ineffective for values of <see cref="SkeletonImage.Width"/> and <see cref="SkeletonImage.Height"/> greater than 65535. /// </remarks> /// <param name="bytes">The byte array containing the encoded <see cref="SkeletonImage"/> object.</param> /// <returns>The <see cref="SkeletonImage"/> object decoded from the specified byte array.</returns> public static SkeletonImage FromByteArray(byte[] bytes) { int width = bytes[0]; width |= bytes[1] << 8; int height = bytes[2]; height |= bytes[3] << 8; int counter = 0; int cursor = 4; byte[,] imageData = new byte[height, width]; for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { int value = 1 & (bytes[cursor] >> counter); imageData[i, j] = (byte)(value == 1 ? 255 : 0); if (counter == 7) { counter = 0; cursor++; } else counter++; } return new SkeletonImage(imageData, width, height); } /// <summary> /// Encodes the specified <see cref="SkeletonImage"/> into a byte array. /// </summary> /// <remarks> /// This codification uses two bytes to store <see cref="SkeletonImage.Width"/>; two more bytes to store <see cref="SkeletonImage.Height"/>; and one bit for each pixel of the <see cref="SkeletonImage"/>. Therefore, this method is ineffective for values of <see cref="SkeletonImage.Width"/> and <see cref="SkeletonImage.Height"/> greater than 65535. /// </remarks> /// <param name="skImg">The <see cref="SkeletonImage"/> object which is going to be encoded to a byte array.</param> /// <returns>The byte array containing the encoded <see cref="SkeletonImage"/> object.</returns> public static byte[] ToByteArray(SkeletonImage skImg) { int length = (int)Math.Ceiling(skImg.Width * skImg.Height / 8.0); byte[] raw = new byte[length + 4]; raw[0] = (byte)(255 & skImg.Width); raw[1] = (byte)(255 & (skImg.Width >> 8)); raw[2] = (byte)(255 & skImg.Height); raw[3] = (byte)(255 & (skImg.Height >> 8)); int counter = 0; int cursor = 4; int currValue = 0; for (int i = 0; i < skImg.Height; i++) for (int j = 0; j < skImg.Width; j++) { currValue |= (skImg[i, j] == 255 ? 1 : 0) << counter; if (counter == 7) { raw[cursor++] = (byte)currValue; currValue = 0; counter = 0; } else counter++; } return raw; } } }
44.672269
361
0.518811
[ "MIT" ]
dbayoxy/keyGenApp
KeygenApp/KeygenApp/bin/Debug/FR.Core/SkeletonImageSerializer.cs
5,320
C#
using System; using NUnit.Framework; using Unity.Collections; using Unity.Jobs; namespace Unity.Entities.Tests { [TestFixture] public class ComponentGroupDelta : ECSTestsFixture { // * TODO: using out of date version cached ComponentDataArray should give exception... (We store the System order version in it...) // * TODO: Using monobehaviour as delta inputs? // * TODO: Self-delta-mutation doesn't trigger update (ComponentDataFromEntity.cs) // /////@TODO: GlobalSystemVersion can't be pulled from m_Entities... indeterministic // * TODO: Chained delta works // How can this work? Need to use specialized job type because the number of entities to be // processed isn't known until running the job... Need some kind of late binding of parallel for length etc... // How do we prevent incorrect usage / default... [DisableAutoCreation] public class DeltaCheckSystem : ComponentSystem { public Entity[] Expected; protected override void OnUpdate() { var group = GetComponentGroup(typeof(EcsTestData)); group.SetFilterChanged(typeof(EcsTestData)); CollectionAssert.AreEqual(Expected, group.GetEntityArray().ToArray()); } public void UpdateExpect(Entity[] expected) { Expected = expected; Update(); } } [Test] public void CreateEntityDoesNotTriggerChange() { m_Manager.CreateEntity(typeof(EcsTestData)); var deltaCheckSystem = World.CreateManager<DeltaCheckSystem>(); deltaCheckSystem.UpdateExpect(new Entity[0]); } public enum ChangeMode { SetComponentData, SetComponentDataFromEntity, ComponentDataArray, ComponentGroupArray } #pragma warning disable 649 unsafe struct GroupRW { public EcsTestData* Data; } unsafe struct GroupRO { [ReadOnly] public EcsTestData* Data; } #pragma warning restore 649 unsafe void SetValue(int index, int value, ChangeMode mode) { EmptySystem.Update(); var entityArray = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetEntityArray(); var entity = entityArray[index]; if (mode == ChangeMode.ComponentDataArray) { var array = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetComponentDataArray<EcsTestData>(); array[index] = new EcsTestData(value); } else if (mode == ChangeMode.SetComponentData) { m_Manager.SetComponentData(entity, new EcsTestData(value)); } else if (mode == ChangeMode.SetComponentDataFromEntity) { //@TODO: Chaining correctness... Definately not implemented right now... var array = EmptySystem.GetComponentDataFromEntity<EcsTestData>(false); array[entity] = new EcsTestData(value); } else if (mode == ChangeMode.ComponentGroupArray) { *(EmptySystem.GetEntities<GroupRW>()[index].Data) = new EcsTestData(value); } } void GetValue(ChangeMode mode) { EmptySystem.Update(); var entityArray = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetEntityArray(); if (mode == ChangeMode.ComponentDataArray) { var array = EmptySystem.GetComponentGroup(typeof(EcsTestData)).GetComponentDataArray<EcsTestData>(); for (int i = 0; i != array.Length; i++) { var val = array[i]; } } else if (mode == ChangeMode.SetComponentData) { for(int i = 0;i != entityArray.Length;i++) m_Manager.GetComponentData<EcsTestData>(entityArray[i]); } else if (mode == ChangeMode.SetComponentDataFromEntity) { for(int i = 0;i != entityArray.Length;i++) m_Manager.GetComponentData<EcsTestData>(entityArray[i]); } else if (mode == ChangeMode.ComponentGroupArray) { foreach (var e in EmptySystem.GetEntities<GroupRO>()) ; } } [Test] public void ChangeEntity([Values]ChangeMode mode) { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var deltaCheckSystem0 = World.CreateManager<DeltaCheckSystem>(); var deltaCheckSystem1 = World.CreateManager<DeltaCheckSystem>(); SetValue(0, 2, mode); deltaCheckSystem0.UpdateExpect(new Entity[] { entity0 }); SetValue(1, 2, mode); deltaCheckSystem0.UpdateExpect(new Entity[] { entity1 }); deltaCheckSystem1.UpdateExpect(new Entity[] { entity0, entity1 }); deltaCheckSystem0.UpdateExpect(new Entity[0]); deltaCheckSystem1.UpdateExpect(new Entity[0]); } [Test] public void GetEntityDataDoesNotChange([Values]ChangeMode mode) { m_Manager.CreateEntity(typeof(EcsTestData)); m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var deltaCheckSystem = World.CreateManager<DeltaCheckSystem>(); GetValue(mode); deltaCheckSystem.UpdateExpect(new Entity[] { }); } [Test] public void ChangeEntityWrap() { m_Manager.Debug.SetGlobalSystemVersion(uint.MaxValue-3); var entity = m_Manager.CreateEntity(typeof(EcsTestData)); var deltaCheckSystem = World.CreateManager<DeltaCheckSystem>(); for (int i = 0; i != 7; i++) { SetValue(0, 1, ChangeMode.SetComponentData); deltaCheckSystem.UpdateExpect(new Entity[] { entity }); } deltaCheckSystem.UpdateExpect(new Entity[0]); } [Test] public void NoChangeEntityWrap() { m_Manager.Debug.SetGlobalSystemVersion(uint.MaxValue - 3); var entity = m_Manager.CreateEntity(typeof(EcsTestData)); SetValue(0, 2, ChangeMode.SetComponentData); var deltaCheckSystem = World.CreateManager<DeltaCheckSystem>(); deltaCheckSystem.UpdateExpect(new Entity[] { entity }); for (int i = 0; i != 7; i++) deltaCheckSystem.UpdateExpect(new Entity[0]); } [DisableAutoCreation] public class DeltaProcessComponentSystem : JobComponentSystem { struct DeltaJob : IJobProcessComponentData<EcsTestData, EcsTestData2> { public void Execute([ChangedFilter][ReadOnly]ref EcsTestData input, ref EcsTestData2 output) { output.value0 += input.value + 100; } } protected override JobHandle OnUpdate(JobHandle deps) { return new DeltaJob().Schedule(this, deps); } } [Test] public void IJobProcessComponentDeltaWorks() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var deltaSystem = World.CreateManager<DeltaProcessComponentSystem>(); SetValue(0, 2, ChangeMode.SetComponentData); deltaSystem.Update(); Assert.AreEqual(100 + 2, m_Manager.GetComponentData<EcsTestData2>(entity0).value0); Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData2>(entity1).value0); } [DisableAutoCreation] public class DeltaProcessComponentSystemUsingRun : ComponentSystem { struct DeltaJob : IJobProcessComponentData<EcsTestData, EcsTestData2> { public void Execute([ChangedFilter][ReadOnly]ref EcsTestData input, ref EcsTestData2 output) { output.value0 += input.value + 100; } } protected override void OnUpdate() { new DeltaJob().Run(this); } } [Test] public void IJobProcessComponentDeltaWorksWhenUsingRun() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var deltaSystem = World.CreateManager<DeltaProcessComponentSystemUsingRun>(); SetValue(0, 2, ChangeMode.SetComponentData); deltaSystem.Update(); Assert.AreEqual(100 + 2, m_Manager.GetComponentData<EcsTestData2>(entity0).value0); Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData2>(entity1).value0); } #if false [Test] public void IJobProcessComponentDeltaWorksWhenSetSharedComponent() { var entity0 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3), typeof(EcsTestSharedComp)); var entity1 = m_Manager.CreateEntity(typeof(EcsTestData), typeof(EcsTestData2)); var deltaSystem = World.CreateManager<DeltaProcessComponentSystem>(); SetValue(0, 2, ChangeMode.SetComponentData); m_Manager.SetSharedComponentData(entity0,new EcsTestSharedComp(50)); deltaSystem.Update(); Assert.AreEqual(100 + 2, m_Manager.GetComponentData<EcsTestData2>(entity0).value0); Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData2>(entity1).value0); } #endif [DisableAutoCreation] public class ModifyComponentSystem1Comp : JobComponentSystem { public ComponentGroup m_Group; public EcsTestSharedComp m_sharedComp; struct DeltaJob : IJobParallelFor { public ComponentDataArray<EcsTestData> data; public void Execute(int index) { data[index] = new EcsTestData(100); } } protected override JobHandle OnUpdate(JobHandle deps) { m_Group = GetComponentGroup( typeof(EcsTestData), ComponentType.ReadOnly(typeof(EcsTestSharedComp))); m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); job.data = m_Group.GetComponentDataArray<EcsTestData>(); return job.Schedule(job.data.Length, 1, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem1Comp : JobComponentSystem { struct DeltaJob : IJobProcessComponentData<EcsTestData> { public void Execute([ChangedFilter]ref EcsTestData output) { output.value += 150; } } protected override JobHandle OnUpdate(JobHandle deps) { return new DeltaJob().Schedule(this, deps); } } [Test] public void ChangedFilterJobAfterAnotherJob1Comp() { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestSharedComp)); var entities = new NativeArray<Entity>(10000, Allocator.Persistent); m_Manager.CreateEntity(archetype, entities); var modifSystem = World.CreateManager<ModifyComponentSystem1Comp>(); var deltaSystem = World.CreateManager<DeltaModifyComponentSystem1Comp>(); modifSystem.m_sharedComp = new EcsTestSharedComp(456); for (int i = 123; i < entities.Length; i += 345) { m_Manager.SetSharedComponentData(entities[i], modifSystem.m_sharedComp); } modifSystem.Update(); deltaSystem.Update(); foreach (var entity in entities) { if (m_Manager.GetSharedComponentData<EcsTestSharedComp>(entity).value == 456) { Assert.AreEqual(250, m_Manager.GetComponentData<EcsTestData>(entity).value); } else { Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData>(entity).value); } } entities.Dispose(); } [DisableAutoCreation] public class ModifyComponentSystem2Comp : JobComponentSystem { public ComponentGroup m_Group; public EcsTestSharedComp m_sharedComp; struct DeltaJob : IJobParallelFor { public ComponentDataArray<EcsTestData> data; public ComponentDataArray<EcsTestData2> data2; public void Execute(int index) { data[index] = new EcsTestData(100); data2[index] = new EcsTestData2(102); } } protected override JobHandle OnUpdate(JobHandle deps) { m_Group = GetComponentGroup( typeof(EcsTestData), typeof(EcsTestData2), ComponentType.ReadOnly(typeof(EcsTestSharedComp))); m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); job.data = m_Group.GetComponentDataArray<EcsTestData>(); job.data2 = m_Group.GetComponentDataArray<EcsTestData2>(); return job.Schedule(job.data.Length, 1, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem2Comp : JobComponentSystem { struct DeltaJobChanged0 : IJobProcessComponentData<EcsTestData, EcsTestData2> { public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 output2) { output.value += 150; output2.value0 += 152; } } struct DeltaJobChanged1 : IJobProcessComponentData<EcsTestData, EcsTestData2> { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2) { output.value += 150; output2.value0 += 152; } } public enum Variant { FirstComponentChanged, SecondComponentChanged, } public Variant variant; protected override JobHandle OnUpdate(JobHandle deps) { switch (variant) { case Variant.FirstComponentChanged: return new DeltaJobChanged0().Schedule(this, deps); case Variant.SecondComponentChanged: return new DeltaJobChanged1().Schedule(this, deps); } throw new NotImplementedException(); } } [Test] public void ChangedFilterJobAfterAnotherJob2Comp([Values]DeltaModifyComponentSystem2Comp.Variant variant) { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestSharedComp)); var entities = new NativeArray<Entity>(10000, Allocator.Persistent); m_Manager.CreateEntity(archetype, entities); var modifSystem = World.CreateManager<ModifyComponentSystem2Comp>(); var deltaSystem = World.CreateManager<DeltaModifyComponentSystem2Comp>(); deltaSystem.variant = variant; modifSystem.m_sharedComp = new EcsTestSharedComp(456); for (int i = 123; i < entities.Length; i += 345) { m_Manager.SetSharedComponentData(entities[i], modifSystem.m_sharedComp); } modifSystem.Update(); deltaSystem.Update(); foreach (var entity in entities) { if (m_Manager.GetSharedComponentData<EcsTestSharedComp>(entity).value == 456) { Assert.AreEqual(250, m_Manager.GetComponentData<EcsTestData>(entity).value); Assert.AreEqual(254, m_Manager.GetComponentData<EcsTestData2>(entity).value0); } else { Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData>(entity).value); } } entities.Dispose(); } [DisableAutoCreation] public class ModifyComponentSystem3Comp : JobComponentSystem { public ComponentGroup m_Group; public EcsTestSharedComp m_sharedComp; struct DeltaJob : IJobParallelFor { public ComponentDataArray<EcsTestData> data; public ComponentDataArray<EcsTestData2> data2; public ComponentDataArray<EcsTestData3> data3; public void Execute(int index) { data[index] = new EcsTestData(100); data2[index] = new EcsTestData2(102); data3[index] = new EcsTestData3(103); } } protected override JobHandle OnUpdate(JobHandle deps) { m_Group = GetComponentGroup( typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3), ComponentType.ReadOnly(typeof(EcsTestSharedComp))); m_Group.SetFilter(m_sharedComp); DeltaJob job = new DeltaJob(); job.data = m_Group.GetComponentDataArray<EcsTestData>(); job.data2 = m_Group.GetComponentDataArray<EcsTestData2>(); job.data3 = m_Group.GetComponentDataArray<EcsTestData3>(); return job.Schedule(job.data.Length, 1, deps); } } [DisableAutoCreation] public class DeltaModifyComponentSystem3Comp : JobComponentSystem { struct DeltaJobChanged0 : IJobProcessComponentData<EcsTestData, EcsTestData2, EcsTestData3> { public void Execute([ChangedFilter]ref EcsTestData output, ref EcsTestData2 output2, ref EcsTestData3 output3) { output.value += 150; output2.value0 += 152; output3.value0 += 153; } } struct DeltaJobChanged1 : IJobProcessComponentData<EcsTestData, EcsTestData2, EcsTestData3> { public void Execute(ref EcsTestData output, [ChangedFilter]ref EcsTestData2 output2, ref EcsTestData3 output3) { output.value += 150; output2.value0 += 152; output3.value0 += 153; } } struct DeltaJobChanged2 : IJobProcessComponentData<EcsTestData, EcsTestData2, EcsTestData3> { public void Execute(ref EcsTestData output, ref EcsTestData2 output2, [ChangedFilter]ref EcsTestData3 output3) { output.value += 150; output2.value0 += 152; output3.value0 += 153; } } public enum Variant { FirstComponentChanged, SecondComponentChanged, ThirdComponentChanged, } public Variant variant; protected override JobHandle OnUpdate(JobHandle deps) { switch (variant) { case Variant.FirstComponentChanged: return new DeltaJobChanged0().Schedule(this, deps); case Variant.SecondComponentChanged: return new DeltaJobChanged1().Schedule(this, deps); case Variant.ThirdComponentChanged: return new DeltaJobChanged2().Schedule(this, deps); } throw new NotImplementedException(); } } public void ChangedFilterJobAfterAnotherJob3Comp([Values]DeltaModifyComponentSystem3Comp.Variant variant) { var archetype = m_Manager.CreateArchetype(typeof(EcsTestData), typeof(EcsTestData2), typeof(EcsTestData3), typeof(EcsTestSharedComp)); var entities = new NativeArray<Entity>(10000, Allocator.Persistent); m_Manager.CreateEntity(archetype, entities); var modifSystem = World.CreateManager<ModifyComponentSystem3Comp>(); var deltaSystem = World.CreateManager<DeltaModifyComponentSystem3Comp>(); deltaSystem.variant = variant; modifSystem.m_sharedComp = new EcsTestSharedComp(456); for (int i = 123; i < entities.Length; i += 345) { m_Manager.SetSharedComponentData(entities[i], modifSystem.m_sharedComp); } modifSystem.Update(); deltaSystem.Update(); foreach (var entity in entities) { if (m_Manager.GetSharedComponentData<EcsTestSharedComp>(entity).value == 456) { Assert.AreEqual(250, m_Manager.GetComponentData<EcsTestData>(entity).value); Assert.AreEqual(254, m_Manager.GetComponentData<EcsTestData2>(entity).value0); Assert.AreEqual(256, m_Manager.GetComponentData<EcsTestData3>(entity).value0); } else { Assert.AreEqual(0, m_Manager.GetComponentData<EcsTestData>(entity).value); } } entities.Dispose(); } } }
36.898361
146
0.569531
[ "MIT" ]
renBuWen/UnityMMO
Packages/com.unity.entities/Unity.Entities.Tests/ComponentGroupDelta.cs
22,510
C#
namespace Mccole.Geodesy { /// <summary> /// Represents 2 dimensional a point on the earth's surface. /// </summary> public interface ICoordinate { /// <summary> /// The angular distance of a place north or south of the earth's equator. /// </summary> double Latitude { get; set; } /// <summary> /// The angular distance of a place east or west of the Greenwich meridian. /// </summary> double Longitude { get; set; } } }
28.388889
83
0.569472
[ "MIT" ]
dungeym/Mccole.Geodesy
Mccole.Geodesy/_Interface/ICoordinate.cs
513
C#
using System; namespace RBS.Messages.actionlib { [System.Serializable] public class TwoIntsFeedback : ExtendMessage { public override string Type() { return "actionlib/TwoIntsFeedback"; } public TwoIntsFeedback() { } } }
20.692308
77
0.639405
[ "MIT" ]
yuyaushiro/ARviz_unity
Assets/ROSBridgeSharp/Assets/RBSocket/Message/DefaultMsgs/actionlib/TwoIntsFeedback.cs
269
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 sesv2-2019-09-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SimpleEmailV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations { /// <summary> /// ListTagsForResource Request Marshaller /// </summary> public class ListTagsForResourceRequestMarshaller : IMarshaller<IRequest, ListTagsForResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListTagsForResourceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListTagsForResourceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleEmailV2"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-09-27"; request.HttpMethod = "GET"; if (publicRequest.IsSetResourceArn()) request.Parameters.Add("ResourceArn", StringUtils.FromString(publicRequest.ResourceArn)); request.ResourcePath = "/v2/email/tags"; request.UseQueryString = true; return request; } private static ListTagsForResourceRequestMarshaller _instance = new ListTagsForResourceRequestMarshaller(); internal static ListTagsForResourceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListTagsForResourceRequestMarshaller Instance { get { return _instance; } } } }
33.965909
153
0.659083
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/ListTagsForResourceRequestMarshaller.cs
2,989
C#
using AsmResolver.PE.DotNet.Metadata; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; namespace AsmResolver.DotNet.Builder.Metadata.Tables { /// <summary> /// Provides a mutable buffer for building up a tables stream in a .NET portable executable. /// </summary> public class TablesStreamBuffer : IMetadataStreamBuffer { private static readonly TableIndex[] EncTables = { TableIndex.FieldPtr, TableIndex.MethodPtr, TableIndex.ParamPtr, TableIndex.EventPtr, TableIndex.PropertyPtr, TableIndex.EncLog, TableIndex.EncMap, }; private readonly TablesStream _tablesStream = new(); private readonly IMetadataTableBuffer[] _tableBuffers; /// <summary> /// Creates a new mutable tables stream buffer. /// </summary> public TablesStreamBuffer() { _tableBuffers = new IMetadataTableBuffer[] { Unsorted<ModuleDefinitionRow>(TableIndex.Module), Distinct<TypeReferenceRow>(TableIndex.TypeRef), Unsorted<TypeDefinitionRow>(TableIndex.TypeDef), Unsorted<FieldPointerRow>(TableIndex.FieldPtr), Unsorted<FieldDefinitionRow>(TableIndex.Field), Unsorted<MethodPointerRow>(TableIndex.MethodPtr), Unsorted<MethodDefinitionRow>(TableIndex.Method), Unsorted<ParameterPointerRow>(TableIndex.ParamPtr), Unsorted<ParameterDefinitionRow>(TableIndex.Param), Sorted<InterfaceImplementation, InterfaceImplementationRow>(TableIndex.InterfaceImpl, 0), Distinct<MemberReferenceRow>(TableIndex.MemberRef), Sorted<Constant, ConstantRow>(TableIndex.Constant, 2), Sorted<CustomAttribute, CustomAttributeRow>(TableIndex.CustomAttribute, 0), Sorted<IHasFieldMarshal, FieldMarshalRow>(TableIndex.FieldMarshal, 0), Sorted<SecurityDeclaration, SecurityDeclarationRow>(TableIndex.DeclSecurity, 1), Sorted<ClassLayout, ClassLayoutRow>(TableIndex.ClassLayout, 2), Sorted<FieldDefinition, FieldLayoutRow>(TableIndex.FieldLayout, 1), Distinct<StandAloneSignatureRow>(TableIndex.StandAloneSig), Sorted<TypeDefinition, EventMapRow>(TableIndex.EventMap, 0, 1), Unsorted<EventPointerRow>(TableIndex.EventPtr), Unsorted<EventDefinitionRow>(TableIndex.Event), Sorted<TypeDefinition, PropertyMapRow>(TableIndex.PropertyMap, 0, 1), Unsorted<PropertyPointerRow>(TableIndex.PropertyPtr), Unsorted<PropertyDefinitionRow>(TableIndex.Property), Sorted<MethodSemantics, MethodSemanticsRow>(TableIndex.MethodSemantics, 2), Sorted<MethodImplementation, MethodImplementationRow>(TableIndex.MethodImpl, 0), Distinct<ModuleReferenceRow>(TableIndex.ModuleRef), Distinct<TypeSpecificationRow>(TableIndex.TypeSpec), Sorted<ImplementationMap, ImplementationMapRow>(TableIndex.ImplMap, 1), Sorted<FieldDefinition, FieldRvaRow>(TableIndex.FieldRva, 1), Unsorted<EncLogRow>(TableIndex.EncLog), Unsorted<EncMapRow>(TableIndex.EncMap), Unsorted<AssemblyDefinitionRow>(TableIndex.Assembly), Unsorted<AssemblyProcessorRow>(TableIndex.AssemblyProcessor), Unsorted<AssemblyOSRow>(TableIndex.AssemblyOS), Distinct<AssemblyReferenceRow>(TableIndex.AssemblyRef), Unsorted<AssemblyRefProcessorRow>(TableIndex.AssemblyRefProcessor), Unsorted<AssemblyRefOSRow>(TableIndex.AssemblyRefOS), Distinct<FileReferenceRow>(TableIndex.File), Distinct<ExportedTypeRow>(TableIndex.ExportedType), Distinct<ManifestResourceRow>(TableIndex.ManifestResource), Sorted<TypeDefinition, NestedClassRow>(TableIndex.NestedClass, 0), Sorted<GenericParameter, GenericParameterRow>(TableIndex.GenericParam, 2, 0), Distinct<MethodSpecificationRow>(TableIndex.MethodSpec), Distinct<GenericParameterConstraintRow>(TableIndex.GenericParamConstraint), }; } /// <inheritdoc /> public string Name => HasEnCData ? TablesStream.EncStreamName : TablesStream.CompressedStreamName; /// <inheritdoc /> public bool IsEmpty { get { for (int i = 0; i < _tableBuffers.Length; i++) { if (_tableBuffers[i].Count > 0) return false; } return true; } } /// <summary> /// Gets a value indicating whether the buffer contains edit-and-continue data. /// </summary> public bool HasEnCData { get { for (int i = 0; i < EncTables.Length; i++) { if (_tableBuffers[(int) EncTables[i]].Count > 0) return true; } return false; } } /// <summary> /// Gets a table buffer by its table index. /// </summary> /// <param name="table">The index of the table to get.</param> /// <typeparam name="TRow">The type of rows the table stores.</typeparam> /// <returns>The metadata table.</returns> public IMetadataTableBuffer<TRow> GetTable<TRow>(TableIndex table) where TRow : struct, IMetadataRow { return (IMetadataTableBuffer<TRow>) _tableBuffers[(int) table]; } /// <summary> /// Gets a table buffer by its table index. /// </summary> /// <param name="table">The index of the table to get.</param> /// <typeparam name="TRow">The type of rows the table stores.</typeparam> /// <returns>The metadata table.</returns> public DistinctMetadataTableBuffer<TRow> GetDistinctTable<TRow>(TableIndex table) where TRow : struct, IMetadataRow { return (DistinctMetadataTableBuffer<TRow>) _tableBuffers[(int) table]; } /// <summary> /// Gets a table buffer by its table index. /// </summary> /// <param name="table">The index of the table to get.</param> /// <typeparam name="TKey">The type of members that are assigned new metadata rows.</typeparam> /// <typeparam name="TRow">The type of rows the table stores.</typeparam> /// <returns>The metadata table.</returns> public ISortedMetadataTableBuffer<TKey, TRow> GetSortedTable<TKey, TRow>(TableIndex table) where TRow : struct, IMetadataRow { return (ISortedMetadataTableBuffer<TKey, TRow>) _tableBuffers[(int) table]; } /// <summary> /// Gets an encoder/decoder for a particular coded index. /// </summary> /// <param name="codedIndex">The coded index.</param> /// <returns>The encoder/decoder object.</returns> public IndexEncoder GetIndexEncoder(CodedIndex codedIndex) { return _tablesStream.GetIndexEncoder(codedIndex); } /// <summary> /// Serializes the tables stream buffer to a metadata stream. /// </summary> /// <returns>The stream.</returns> public TablesStream CreateStream() { foreach (var tableBuffer in _tableBuffers) tableBuffer.FlushToTable(); _tablesStream.Name = Name; return _tablesStream; } /// <inheritdoc /> IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream(); private IMetadataTableBuffer<TRow> Unsorted<TRow>(TableIndex table) where TRow : struct, IMetadataRow { return new UnsortedMetadataTableBuffer<TRow>((MetadataTable<TRow>) _tablesStream.GetTable(table)); } private IMetadataTableBuffer<TRow> Distinct<TRow>(TableIndex table) where TRow : struct, IMetadataRow { return new DistinctMetadataTableBuffer<TRow>(Unsorted<TRow>(table)); } private ISortedMetadataTableBuffer<TKey, TRow> Sorted<TKey, TRow>(TableIndex table, int primaryColumn) where TKey : notnull where TRow : struct, IMetadataRow { return new SortedMetadataTableBuffer<TKey, TRow>( (MetadataTable<TRow>) _tablesStream.GetTable(table), primaryColumn); } private ISortedMetadataTableBuffer<TKey, TRow> Sorted<TKey, TRow>(TableIndex table, int primaryColumn, int secondaryColumn) where TKey : notnull where TRow : struct, IMetadataRow { return new SortedMetadataTableBuffer<TKey, TRow>( (MetadataTable<TRow>) _tablesStream.GetTable(table), primaryColumn, secondaryColumn); } } }
44.892683
131
0.615017
[ "MIT" ]
CrackerCat/AsmResolver
src/AsmResolver.DotNet/Builder/Metadata/Tables/TablesStreamBuffer.cs
9,205
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Subjects; using System.Text; using System.Threading.Tasks; namespace Samples.Services.Impl { public class AppStateImpl : IAppState, IAppLifecycle { readonly Subject<object> resumeSubject = new Subject<object>(); readonly Subject<object> bgSubject = new Subject<object>(); public IObservable<object> WhenBackgrounding() { return this.bgSubject; } public IObservable<object> WhenResuming() { return this.resumeSubject; } public void OnForeground() { this.resumeSubject.OnNext(null); } public void OnBackground() { this.bgSubject.OnNext(null); } } }
20.948718
71
0.614443
[ "MIT" ]
alexstrong29/BluetoothTesting
Samples/Samples/Services/Impl/AppStateImpl.cs
819
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 iot-2015-05-28.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.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeThingRegistrationTask operation /// </summary> public class DescribeThingRegistrationTaskResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeThingRegistrationTaskResponse response = new DescribeThingRegistrationTaskResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("creationDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; response.CreationDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("failureCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; response.FailureCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("inputFileBucket", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.InputFileBucket = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("inputFileKey", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.InputFileKey = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("lastModifiedDate", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; response.LastModifiedDate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("message", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Message = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("percentageProgress", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; response.PercentageProgress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("roleArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.RoleArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("successCount", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; response.SuccessCount = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("taskId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.TaskId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("templateBody", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.TemplateBody = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException")) { return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return UnauthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonIoTException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeThingRegistrationTaskResponseUnmarshaller _instance = new DescribeThingRegistrationTaskResponseUnmarshaller(); internal static DescribeThingRegistrationTaskResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeThingRegistrationTaskResponseUnmarshaller Instance { get { return _instance; } } } }
42.880208
186
0.592251
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/DescribeThingRegistrationTaskResponseUnmarshaller.cs
8,233
C#
namespace Nancy.Testing { using System; using System.Collections.Generic; using System.IO; /// <summary> /// Defines the context that a <see cref="Browser"/> instance should run under. /// </summary> public class BrowserContext : IBrowserContextValues { /// <summary> /// Initializes a new instance of the <see cref="BrowserContext"/> class. /// </summary> public BrowserContext() { this.Values.Headers = new Dictionary<string, IEnumerable<string>>(); this.Values.Protocol = "http"; this.Values.QueryString = String.Empty; this.Values.BodyString = String.Empty; this.Values.FormValues = String.Empty; } /// <summary> /// Gets or sets the that should be sent with the HTTP request. /// </summary> /// <value>A <see cref="Stream"/> that contains the body that should be sent with the HTTP request.</value> Stream IBrowserContextValues.Body { get; set; } /// <summary> /// Gets or sets the protocol that should be sent with the HTTP request. /// </summary> /// <value>A <see cref="string"/> contains the the protocol that should be sent with the HTTP request..</value> string IBrowserContextValues.Protocol { get; set; } /// <summary> /// Gets or sets the querystring /// </summary> string IBrowserContextValues.QueryString { get; set; } /// <summary> /// Gets or sets the body string /// </summary> string IBrowserContextValues.BodyString { get; set; } /// <summary> /// Gets or sets the form values string /// </summary> string IBrowserContextValues.FormValues { get; set; } /// <summary> /// Gets or sets the headers that should be sent with the HTTP request. /// </summary> /// <value>An <see cref="IDictionary{TKey,TValue}"/> instance that contains the headers that should be sent with the HTTP request.</value> IDictionary<string, IEnumerable<string>> IBrowserContextValues.Headers { get; set; } /// <summary> /// Adds a body to the HTTP request. /// </summary> /// <param name="body">A string that should be used as the HTTP request body.</param> public void Body(string body) { this.Values.BodyString = body; } /// <summary> /// Adds a body to the HTTP request. /// </summary> /// <param name="body">A stream that should be used as the HTTP request body.</param> /// <param name="contentType">Content type of the HTTP request body. Defaults to 'application/octet-stream'</param> public void Body(Stream body, string contentType = null) { this.Values.Body = body; this.Header("Content-Type", contentType ?? "application/octet-stream"); } /// <summary> /// Adds an application/x-www-form-urlencoded form value. /// </summary> /// <param name="key">The name of the form element.</param> /// <param name="value">The value of the form element.</param> public void FormValue(string key, string value) { if (!String.IsNullOrEmpty(this.Values.BodyString)) { throw new InvalidOperationException("Form value cannot be set as well as body string"); } this.Values.FormValues += String.Format( "{0}{1}={2}", this.Values.FormValues.Length == 0 ? String.Empty : "&", key, value); } /// <summary> /// Adds a header to the HTTP request. /// </summary> /// <param name="name">The name of the header.</param> /// <param name="value">The value of the header.</param> public void Header(string name, string value) { if (!this.Values.Headers.ContainsKey(name)) { this.Values.Headers.Add(name, new List<string>()); } var values = (List<string>)this.Values.Headers[name]; values.Add(value); this.Values.Headers[name] = values; } /// <summary> /// Configures the request to be sent over HTTP. /// </summary> public void HttpRequest() { this.Values.Protocol = "http"; } /// <summary> /// Configures the request to be sent over HTTPS. /// </summary> public void HttpsRequest() { this.Values.Protocol = "https"; } /// <summary> /// Adds a query string entry /// </summary> public void Query(string key, string value) { this.Values.QueryString += String.Format( "{0}{1}={2}", this.Values.QueryString.Length == 0 ? String.Empty : "&", key, value); } private IBrowserContextValues Values { get { return this; } } } }
36.027211
147
0.532666
[ "MIT" ]
bendetat/Nancy
src/Nancy.Testing/BrowserContext.cs
5,298
C#
using System; using System.Text.RegularExpressions; namespace DotJEM.Json.Index.Util { public class AdvConvert { private static readonly Regex timeSpanExpression = new Regex(@"((?'d'[0-9]+)\s?d(ay(s)?)?)?\s?" + @"((?'h'[0-9]+)\s?h(our(s)?)?)?\s?" + @"((?'m'[0-9]+)\s?m(in(ute(s)?)?)?)?\s?" + @"((?'s'[0-9]+)\s?s(ec(ond(s)?)?)?)?\s?" + @"((?'f'[0-9]+)\s?f(rac(tion(s)?)?)?|ms|millisecond(s)?)?\s?", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex byteCountExpression = new Regex(@"((?'g'[0-9]+)\s?gb|gigabyte(s)?)?\s?" + @"((?'m'[0-9]+)\s?mb|megabyte(s)?)?\s?" + @"((?'k'[0-9]+)\s?kb|kilobyte(s)?)?\s?" + @"((?'b'[0-9]+)\s?b|byte(s)?)?\s?", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary> /// Atempts to convert a string to a <see cref="TimeSpan"/>. /// </summary> /// <remarks> /// The method first attempts to use the normal <see cref="TimeSpan.Parse"/> method, if that fails it then usesuses a range of wellknown formats /// to atempt a conversion of a string representing a <see cref="TimeSpan"/>. /// <p/>The order of which the values are defined must always be "Days, Hours, Minutes, Seconds and Fractions" But non of them are required, /// that means that a valid format could be '5 days 30 min' as well as '3h', and spaces are alowed between each value and it's unit definition. /// <p/>The folowing units are known. /// <table> /// <tr><td>Days</td><td>d, day, days</td></tr> /// <tr><td>Hours</td><td>h, hour, hours</td></tr> /// <tr><td>Minutes</td><td>m, min, minute, minutes</td></tr> /// <tr><td>Seconds</td><td>s, sec, second, seconds</td></tr> /// <tr><td>Fractions</td><td>f, frac, fraction. fractions, ms, millisecond, milliseconds</td></tr> /// </table> /// <p/>All Unit definitions ignores any casing. /// </remarks> /// <param name="input">A string representing a <see cref="TimeSpan"/>.</param> /// <returns>A TimeSpan from the given input.</returns> /// <example> /// This piece of code first parses the string "2m 30s" to a <see cref="TimeSpan"/> and then uses that <see cref="TimeSpan"/> to sleep for 2 minutes and 30 seconds. /// <code> /// public void SleepForSomeTime() /// { /// //Two and a half minute. /// TimeSpan sleep = Convert.ToTimeSpan("2m 30s"); /// Thread.Spleep(sleep); /// } /// </code> /// </example> /// <exception cref="ArgumentNullException">Input was null</exception> /// <exception cref="FormatException">The given input could not be converted to a <see cref="TimeSpan"/> because the format was invalid.</exception> public static TimeSpan ConvertToTimeSpan(string input) { TimeSpan outPut; if (TryConvertToTimeSpan(input, out outPut)) return outPut; throw new FormatException("Input string was not in a correct format."); } public static bool TryConvertToTimeSpan(string input, out TimeSpan value) { if (input == null) throw new ArgumentNullException(nameof(input)); if (TimeSpan.TryParse(input, out value)) return true; Match match = timeSpanExpression.Match(input); if (!match.Success) return false; int days = ParseGroup(match.Groups["d"]); int hours = ParseGroup(match.Groups["h"]); int minutes = ParseGroup(match.Groups["m"]); int seconds = ParseGroup(match.Groups["s"]); int milliseconds = ParseGroup(match.Groups["f"]); value = new TimeSpan(days, hours, minutes, seconds, milliseconds); return true; } /// <summary> /// Atempts to convert a string to <see cref="long"/> value as a number of bytes. /// </summary> /// <remarks> /// The method usesuses a range of wellknown formats to atempt a conversion of a string representing a size in bytes. /// <p/>The order of which the values are defined must always be "Gigabytes, Megabytes, Kilobytes, and Bytes" But non of them are required, /// that means that a valid format could be '5 gigabytes 512 bytes' as well as '3kb', and spaces are alowed between each value and it's unit definition. /// <p/>The folowing units are known. /// <table> /// <tr><td>Gigabytes</td><td>gb, gigabyte, gigabytes</td></tr> /// <tr><td>Megabytes</td><td>mb, megabyte, megabytes</td></tr> /// <tr><td>Kilobytes</td><td>kb, kilobyte, kilobytes</td></tr> /// <tr><td>Bytes</td><td>b, byte, bytes</td></tr> /// </table> /// <p/>All Unit definitions ignores any casing. /// </remarks> /// <param name="input">A string representing a total number of bytes as Gigabytes, Megabytes, Kilobytes and Bytes.</param> /// <returns>A <see cref="long"/> calculated as the total number of bytes from the given input.</returns> /// <example> /// This piece of code first parses the string "25mb 512kb" to a long and then uses to write an empty file in the "C:\Temp" folder. /// <code> /// public void WriteSomeFile() /// { /// long lenght = Convert.ToByteCount("25mb 512kb"); /// FileHelper.CreateTextFile("C:\temp", new byte[lenght], true); /// } /// </code> /// </example> /// <exception cref="FormatException">The given input could not be converted because the format was invalid.</exception> /// <exception cref="ArgumentNullException">Input was null</exception> public static long ConvertToByteCount(string input) { if (input == null) throw new ArgumentNullException(nameof(input)); Match match = byteCountExpression.Match(input); if (match == null || !match.Success) throw new FormatException("Input string was not in a correct format."); long gigaBytes = ParseGroup(match.Groups["g"]); long megaBytes = ParseGroup(match.Groups["m"]); ; long kiloBytes = ParseGroup(match.Groups["k"]); ; long bytes = ParseGroup(match.Groups["b"]); ; return bytes + (1024L * (kiloBytes + (1024L * (megaBytes + (1024L * gigaBytes))))); } /// <summary> /// Parses an enum genericly. /// </summary> /// <remarks> /// See Enum.Parse for details on exception behavior etc. /// </remarks> /// <typeparam name="TEnumeration">Target enum type</typeparam> /// <param name="state">value to parse</param> /// <returns>Parsed value</returns> public static TEnumeration ConvertToEnum<TEnumeration>(string state) { return (TEnumeration)Enum.Parse(typeof(TEnumeration), state, true); } private static int ParseGroup(Group group) { return string.IsNullOrEmpty(@group?.Value) ? 0 : int.Parse(@group.Value); } } }
51.919463
172
0.540977
[ "MIT" ]
dotJEM/json-index
DotJEM.Json.Index/Util/AdvConvert.cs
7,738
C#
using Dna; using Fasetto.Word.Core; namespace Fasetto.Word { /// <summary> /// A shorthand access class to get DI services with nice clean short code /// </summary> public static class DI { /// <summary> /// A shortcut to access the <see cref="IUIManager"/> /// </summary> public static IUIManager UI => Framework.Service<IUIManager>(); /// <summary> /// A shortcut to access the <see cref="ApplicationViewModel"/> /// </summary> public static ApplicationViewModel ViewModelApplication => Framework.Service<ApplicationViewModel>(); /// <summary> /// A shortcut to access the <see cref="SettingsViewModel"/> /// </summary> public static SettingsViewModel ViewModelSettings => Framework.Service<SettingsViewModel>(); /// <summary> /// A shortcut to access toe <see cref="IClientDataStore"/> service /// </summary> public static IClientDataStore ClientDataStore => Framework.Service<IClientDataStore>(); } }
33.1875
109
0.626177
[ "MIT" ]
Drumahota/fasetto-word
Source/Fasetto.Word/DI/DI.cs
1,064
C#
/*<copyright> Mo+ Solution Builder is a model oriented programming language and IDE, used for building models and generating code and other documents in a model driven development process. Copyright (C) 2013 Dave Clemmer, Intelligent Coding Solutions, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. </copyright>*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows; using MoPlus.ViewModel; using MoPlus.SolutionBuilder.WpfClient.Resources; using System.Windows.Input; using System.Text.RegularExpressions; using MoPlus.ViewModel.Interpreter; using Irony.Interpreter.Ast; using Irony.Interpreter; using Irony.Parsing; using MoPlus.SolutionBuilder.WpfClient.UserControls.Interpreter; using MoPlus.Interpreter.BLL.Interpreter; namespace MoPlus.SolutionBuilder.WpfClient.Library { ///-------------------------------------------------------------------------------- /// <summary>This class provides base functionality for edit user controls.</summary> ///-------------------------------------------------------------------------------- public class EditControl : UserControl { ///-------------------------------------------------------------------------------- /// <summary>This method handles the textbox loaded event to set focus.</summary> /// /// <param name="sender">Sender of the event.</param> /// <param name="e">Event arguments.</param> ///-------------------------------------------------------------------------------- protected void TextBox_Loaded(object sender, RoutedEventArgs e) { if (sender != null && sender is TextBox) { (sender as TextBox).Focus(); } } ///-------------------------------------------------------------------------------- /// <summary>This method enforces input to be numeric only.</summary> /// /// <param name="sender">Sender of the event.</param> /// <param name="e">Event arguments.</param> ///-------------------------------------------------------------------------------- protected void TextBox_PreviewNumericInput(object sender, TextCompositionEventArgs e) { e.Handled = !String.IsNullOrEmpty(e.Text) && !IsTextNumeric(e.Text); } ///-------------------------------------------------------------------------------- /// <summary>This method determines whether the input text is numeric.</summary> /// /// <param name="text">Input text to test.</param> ///-------------------------------------------------------------------------------- private bool IsTextNumeric(string text) { Regex regex = new Regex("[^0-9.-]+"); return !regex.IsMatch(text); } ///-------------------------------------------------------------------------------- /// <summary>This method enforces input to be numeric only.</summary> /// /// <param name="sender">Sender of the event.</param> /// <param name="e">Event arguments.</param> ///-------------------------------------------------------------------------------- protected void TextBox_NumericPasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(String))) { String text = (String)e.DataObject.GetData(typeof(String)); if (!IsTextNumeric(text)) e.CancelCommand(); } else e.CancelCommand(); } ///-------------------------------------------------------------------------------- /// <summary>This method subscribes to the event to confirm closes if thre are any /// outstanding changes, and to the event to force closes.</summary> ///-------------------------------------------------------------------------------- protected void Grid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (DataContext is IEditWorkspaceViewModel) { (DataContext as IEditWorkspaceViewModel).ConfirmClose -= new EventHandler(Control_ConfirmClose); (DataContext as IEditWorkspaceViewModel).ForceClose -= new EventHandler(Control_ForceClose); (DataContext as IEditWorkspaceViewModel).ConfirmClose += new EventHandler(Control_ConfirmClose); (DataContext as IEditWorkspaceViewModel).ForceClose += new EventHandler(Control_ForceClose); } } ///-------------------------------------------------------------------------------- /// <summary>This method forces the close of the control.</summary> ///-------------------------------------------------------------------------------- private void Control_ForceClose(object sender, EventArgs e) { if (sender is IEditWorkspaceViewModel) { if (MessageBox.Show(DisplayValues.Message_ForceClosingItemIntro + (sender as IEditWorkspaceViewModel).TabTitle + DisplayValues.Message_ForceClosingItemEnd, DisplayValues.Message_CloseCaption, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { (sender as IEditWorkspaceViewModel).UpdateCommand.Execute(null); } (sender as IEditWorkspaceViewModel).CloseCommand.Execute(null); } } ///-------------------------------------------------------------------------------- /// <summary>This method confirms the close of the control.</summary> ///-------------------------------------------------------------------------------- private void Control_ConfirmClose(object sender, EventArgs e) { if (sender is IEditWorkspaceViewModel) { if (MessageBox.Show(DisplayValues.Message_ClosingItemIntro + (sender as IEditWorkspaceViewModel).TabTitle + DisplayValues.Message_ClosingItemEnd, DisplayValues.Message_CloseCaption, MessageBoxButton.OKCancel) == MessageBoxResult.OK) { (sender as IEditWorkspaceViewModel).CloseCommand.Execute(null); } } } } }
46.729323
244
0.586967
[ "BSD-2-Clause" ]
moplus/modelorientedplus
MoPlus.SolutionBuilder.WpfClient/Library/EditControl.cs
6,217
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SystemIntegrated.Controllers.Operacao { public class OperEstornoVendaController : Controller { // GET: OperEstornoVenda public ActionResult Index() { return View(); } } }
20.294118
56
0.663768
[ "MIT" ]
NilsonFPereira/SystemIntegrated
SystemIntegrated/Controllers/Operacao/OperEstornoVendaController.cs
347
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsharpGame.Engine.Base { /// <summary> /// This is a layer to draw sprites in it /// Every scene have at least one layer /// </summary> public class Layer { public int z_order { get; set; } public string Name { get; set; } /// <summary> /// Regroups all the game object /// </summary> private List<GameObject> _GameObjects; public Layer(string name) { Name = name; _GameObjects = new List<GameObject>(); } /// <summary> /// Get the list of the registred objects /// </summary> /// <returns></returns> public List<GameObject> RegistredObjects() { return _GameObjects; } /// <summary> /// Add a Game object to the list, to be draw, and rules applied automatically /// </summary> /// <param name="gameObject"></param> /// <returns></returns> public bool RegisterGameObject(GameObject gameObject) { if (gameObject == null) return false; if (_GameObjects.Contains(gameObject)) return false; _GameObjects.Add(gameObject); return true; } } }
24.666667
86
0.541963
[ "MIT" ]
MohKamal/CsharpGame
src/CsharpGame.Engine/Base/Layer.cs
1,408
C#
using System; namespace HanumanInstitute.OntraportApi.Converters { /// <summary> /// Converts a "0" or "1" field into a boolean property. /// </summary> public class JsonConverterIntBool : JsonConverterBase<bool?> { public override bool? Parse(string? value) { // Different forms may use either a binary integer or boolean value for deleted field. int? valueInt = null; if (value == "true" || value == "True") { valueInt = 1; } else if (value == "false" || value == "False") { valueInt = 0; } else if (!IsNullValue(value)) { valueInt = value?.Convert<int?>(); } return valueInt.HasValue ? valueInt == 1 : (bool?)null; } public override string Format(bool? value) => value.HasValue ? (value == true ? "1" : "0") : ""; } }
29.818182
98
0.494919
[ "BSD-2-Clause" ]
mysteryx93/OntraportApi.NET
OntraportApi/Converters/JsonConverterIntBool.cs
986
C#
namespace TemporalTwist.Model { using System.Collections.Generic; using TagLib; public class Preset : IPreset { private string customExtension; public Preset() : this("New Preset") { } public Preset(string name) { this.TagTypes = new List<TagTypes>(0); this.BitRate = 64000; this.SampleRate = 44100; this.Extension = "None"; this.Name = name; } public string Extension { get; set; } public string CustomExtension { get { return string.IsNullOrEmpty(this.customExtension) ? this.Extension : this.customExtension; } set { this.customExtension = value; } } public int BitRate { get; set; } public int SampleRate { get; set; } public string Name { get; set; } public IList<TagTypes> TagTypes { get; set; } public bool Equals(IPreset other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return other.Name.Equals( this.Name); } public object Clone() { var newFormat = (Preset)this.MemberwiseClone(); newFormat.TagTypes = new List<TagTypes>(); foreach (var tagType in this.TagTypes) { newFormat.TagTypes.Add(tagType); } return newFormat; } public override bool Equals(object obj) { return this.Equals(obj as Preset); } public override int GetHashCode() { var name = this.Name; return name?.GetHashCode() ?? 0; } } }
22.534884
106
0.48194
[ "BSD-3-Clause" ]
blacktau/temporaltwist
TemporalTwist/Model/Preset.cs
1,940
C#
using System; using System.IO; using System.Net.Sockets; using System.Text; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using FluentFTP.Proxy; using SysSslProtocols = System.Security.Authentication.SslProtocols; using FluentFTP.Servers; using FluentFTP.Helpers; #if !CORE using System.Web; #endif #if (CORE || NETFX) using System.Threading; #endif #if ASYNC using System.Threading.Tasks; #endif namespace FluentFTP { /// <summary> /// A connection to a single FTP server. Interacts with any FTP/FTPS server and provides a high-level and low-level API to work with files and folders. /// /// Debugging problems with FTP is much easier when you enable logging. See the FAQ on our Github project page for more info. /// </summary> public partial class FtpClient : IDisposable { #region Constructor / Destructor /// <summary> /// Creates a new instance of an FTP Client. /// </summary> public FtpClient() { m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host. /// </summary> public FtpClient(string host) { Host = host ?? throw new ArgumentNullException("Host must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(string host, NetworkCredential credentials) { Host = host ?? throw new ArgumentNullException("Host must be provided"); Credentials = credentials ?? throw new ArgumentNullException("Credentials must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(string host, int port, NetworkCredential credentials) { Host = host ?? throw new ArgumentNullException("Host must be provided"); Port = port; Credentials = credentials ?? throw new ArgumentNullException("Credentials must be provided"); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, username and password. /// </summary> public FtpClient(string host, string user, string pass) { Host = host; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, username, password and account /// </summary> public FtpClient(string host, string user, string pass, string account) { Host = host; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port, username and password. /// </summary> public FtpClient(string host, int port, string user, string pass) { Host = host; Port = port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port, username, password and account /// </summary> public FtpClient(string host, int port, string user, string pass, string account) { Host = host; Port = port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host. /// </summary> public FtpClient(Uri host) { Host = ValidateHost(host); Port = host.Port; m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, NetworkCredential credentials) { Host = ValidateHost(host); Port = host.Port; Credentials = credentials; m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, string user, string pass) { Host = ValidateHost(host); Port = host.Port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host and credentials. /// </summary> public FtpClient(Uri host, string user, string pass, string account) { Host = ValidateHost(host); Port = host.Port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(Uri host, int port, string user, string pass) { Host = ValidateHost(host); Port = port; Credentials = new NetworkCredential(user, pass); m_listParser = new FtpListParser(this); } /// <summary> /// Creates a new instance of an FTP Client, with the given host, port and credentials. /// </summary> public FtpClient(Uri host, int port, string user, string pass, string account) { Host = ValidateHost(host); Port = port; Credentials = new NetworkCredential(user, pass, account); m_listParser = new FtpListParser(this); } /// <summary> /// Check if the host parameter is valid /// </summary> /// <param name="host"></param> private static string ValidateHost(Uri host) { if (host == null) { throw new ArgumentNullException("Host is required"); } #if !CORE if (host.Scheme != Uri.UriSchemeFtp) { throw new ArgumentException("Host is not a valid FTP path"); } #endif return host.Host; } /// <summary> /// Creates a new instance of this class. Useful in FTP proxy classes. /// </summary> /// <returns></returns> protected virtual FtpClient Create() { return new FtpClient(); } /// <summary> /// Disconnects from the server, releases resources held by this /// object. /// </summary> public virtual void Dispose() { #if !CORE14 lock (m_lock) { #endif if (IsDisposed) { return; } // Fix: Hard catch and suppress all exceptions during disposing as there are constant issues with this method try { LogFunc(nameof(Dispose)); LogStatus(FtpTraceLevel.Verbose, "Disposing FtpClient object..."); } catch (Exception ex) { } try { if (IsConnected) { Disconnect(); } } catch (Exception ex) { } if (m_stream != null) { try { m_stream.Dispose(); } catch (Exception ex) { } m_stream = null; } try { m_credentials = null; m_textEncoding = null; m_host = null; m_asyncmethods.Clear(); } catch (Exception ex) { } IsDisposed = true; GC.SuppressFinalize(this); #if !CORE14 } #endif } /// <summary> /// Finalizer /// </summary> ~FtpClient() { Dispose(); } #endregion #region Clone /// <summary> /// Clones the control connection for opening multiple data streams /// </summary> /// <returns>A new control connection with the same property settings as this one</returns> protected FtpClient CloneConnection() { var conn = Create(); conn.m_isClone = true; // configure new connection as clone of self conn.InternetProtocolVersions = InternetProtocolVersions; conn.SocketPollInterval = SocketPollInterval; conn.StaleDataCheck = StaleDataCheck; conn.EnableThreadSafeDataConnections = EnableThreadSafeDataConnections; conn.NoopInterval = NoopInterval; conn.Encoding = Encoding; conn.Host = Host; conn.Port = Port; conn.Credentials = Credentials; conn.MaximumDereferenceCount = MaximumDereferenceCount; conn.ClientCertificates = ClientCertificates; conn.DataConnectionType = DataConnectionType; conn.UngracefullDisconnection = UngracefullDisconnection; conn.ConnectTimeout = ConnectTimeout; conn.ReadTimeout = ReadTimeout; conn.DataConnectionConnectTimeout = DataConnectionConnectTimeout; conn.DataConnectionReadTimeout = DataConnectionReadTimeout; conn.SocketKeepAlive = SocketKeepAlive; conn.m_capabilities = m_capabilities; conn.EncryptionMode = EncryptionMode; conn.DataConnectionEncryption = DataConnectionEncryption; conn.SslProtocols = SslProtocols; conn.SslBuffering = SslBuffering; conn.TransferChunkSize = TransferChunkSize; conn.LocalFileBufferSize = LocalFileBufferSize; conn.ListingDataType = ListingDataType; conn.ListingParser = ListingParser; conn.ListingCulture = ListingCulture; conn.ListingCustomParser = ListingCustomParser; conn.TimeZone = TimeZone; conn.TimeConversion = TimeConversion; conn.RetryAttempts = RetryAttempts; conn.UploadRateLimit = UploadRateLimit; conn.DownloadZeroByteFiles = DownloadZeroByteFiles; conn.DownloadRateLimit = DownloadRateLimit; conn.DownloadDataType = DownloadDataType; conn.UploadDataType = UploadDataType; conn.ActivePorts = ActivePorts; conn.PassiveBlockedPorts = PassiveBlockedPorts; conn.PassiveMaxAttempts = PassiveMaxAttempts; conn.SendHost = SendHost; conn.SendHostDomain = SendHostDomain; conn.FXPDataType = FXPDataType; conn.FXPProgressInterval = FXPProgressInterval; conn.ServerHandler = ServerHandler; conn.UploadDirectoryDeleteExcluded = UploadDirectoryDeleteExcluded; conn.DownloadDirectoryDeleteExcluded = DownloadDirectoryDeleteExcluded; // configure new connection as clone of self (newer version .NET only) #if ASYNC && !CORE14 && !CORE16 conn.SocketLocalIp = SocketLocalIp; #endif // configure new connection as clone of self (.NET core props only) #if CORE conn.LocalTimeZone = LocalTimeZone; #endif // fix for #428: OpenRead with EnableThreadSafeDataConnections always uses ASCII conn.CurrentDataType = CurrentDataType; conn.ForceSetDataType = true; // configure new connection as clone of self (.NET framework props only) #if !CORE conn.PlainTextEncryption = PlainTextEncryption; #endif // always accept certificate no matter what because if code execution ever // gets here it means the certificate on the control connection object being // cloned was already accepted. conn.ValidateCertificate += new FtpSslValidation( delegate (FtpClient obj, FtpSslValidationEventArgs e) { e.Accept = true; }); return conn; } #endregion #region Connect private FtpListParser m_listParser; /// <summary> /// Connect to the server /// </summary> /// <exception cref="ObjectDisposedException">Thrown if this object has been disposed.</exception> public virtual void Connect() { FtpReply reply; #if !CORE14 lock (m_lock) { #endif LogFunc(nameof(Connect)); if (IsDisposed) { throw new ObjectDisposedException("This FtpClient object has been disposed. It is no longer accessible."); } if (m_stream == null) { m_stream = new FtpSocketStream(this); m_stream.ValidateCertificate += new FtpSocketStreamSslValidation(FireValidateCertficate); } else { if (IsConnected) { Disconnect(); } } if (Host == null) { throw new FtpException("No host has been specified"); } if (m_capabilities == null) { m_capabilities = new List<FtpCapability>(); } ResetStateFlags(); m_hashAlgorithms = FtpHashAlgorithm.NONE; m_stream.ConnectTimeout = m_connectTimeout; m_stream.SocketPollInterval = m_socketPollInterval; Connect(m_stream); m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_keepAlive); #if !NO_SSL if (EncryptionMode == FtpEncryptionMode.Implicit) { m_stream.ActivateEncryption(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } #endif Handshake(); m_serverType = FtpServerSpecificHandler.DetectFtpServer(this, HandshakeReply); if (SendHost) { if (!(reply = Execute("HOST " + (SendHostDomain != null ? SendHostDomain : Host))).Success) { throw new FtpException("HOST command failed."); } } #if !NO_SSL // try to upgrade this connection to SSL if supported by the server if (EncryptionMode == FtpEncryptionMode.Explicit || EncryptionMode == FtpEncryptionMode.Auto) { reply = Execute("AUTH TLS"); if (!reply.Success){ _ConnectionFTPSFailure = true; if (EncryptionMode == FtpEncryptionMode.Explicit) { throw new FtpSecurityNotAvailableException("AUTH TLS command failed."); } } else if (reply.Success) { m_stream.ActivateEncryption(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } } #endif if (m_credentials != null) { Authenticate(); } // configure the default FTPS settings if (IsEncrypted && DataConnectionEncryption) { if (!(reply = Execute("PBSZ 0")).Success) { throw new FtpCommandException(reply); } if (!(reply = Execute("PROT P")).Success) { throw new FtpCommandException(reply); } } // if this is a clone these values should have already been loaded // so save some bandwidth and CPU time and skip executing this again. // otherwise clear the capabilities in case connection is reused to // a different server if (!m_isClone && m_checkCapabilities) { m_capabilities.Clear(); } bool assumeCaps = false; if (m_capabilities.IsBlank() && m_checkCapabilities) { if ((reply = Execute("FEAT")).Success && reply.InfoMessages != null) { GetFeatures(reply); } else { assumeCaps = true; } } // Enable UTF8 if the encoding is ASCII and UTF8 is supported if (m_textEncodingAutoUTF && m_textEncoding == Encoding.ASCII && HasFeature(FtpCapability.UTF8)) { m_textEncoding = Encoding.UTF8; } LogStatus(FtpTraceLevel.Info, "Text encoding: " + m_textEncoding.ToString()); if (m_textEncoding == Encoding.UTF8) { // If the server supports UTF8 it should already be enabled and this // command should not matter however there are conflicting drafts // about this so we'll just execute it to be safe. if ((reply = Execute("OPTS UTF8 ON")).Success) { _ConnectionUTF8Success = true; } } // Get the system type - Needed to auto-detect file listing parser if ((reply = Execute("SYST")).Success) { m_systemType = reply.Message; m_serverType = FtpServerSpecificHandler.DetectFtpServerBySyst(this); m_serverOS = FtpServerSpecificHandler.DetectFtpOSBySyst(this); } // Set a FTP server handler if a custom handler has not already been set if (ServerHandler == null) { ServerHandler = FtpServerSpecificHandler.GetServerHandler(m_serverType); } // Assume the system's capabilities if FEAT command not supported by the server if (assumeCaps) { FtpServerSpecificHandler.AssumeCapabilities(this, ServerHandler, m_capabilities, ref m_hashAlgorithms); } #if !NO_SSL && !CORE if (IsEncrypted && PlainTextEncryption) { if (!(reply = Execute("CCC")).Success) { throw new FtpSecurityNotAvailableException("Failed to disable encryption with CCC command. Perhaps your server does not support it or is not configured to allow it."); } else { // close the SslStream and send close_notify command to server m_stream.DeactivateEncryption(); // read stale data (server's reply?) ReadStaleData(false, true, false); } } #endif // Unless a custom list parser has been set, // Detect the listing parser and prefer machine listings over any other type // FIX : #739 prefer using machine listings to fix issues with GetListing and DeleteDirectory if (ListingParser != FtpParser.Custom) { ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto; if (HasFeature(FtpCapability.MLSD)) { ListingParser = FtpParser.Machine; } } // Create the parser even if the auto-OS detection failed m_listParser.Init(m_serverOS, ListingParser); // FIX : #318 always set the type when we create a new connection ForceSetDataType = true; if (ServerType == FtpServer.IBMzOSFTP && ServerOS == FtpOperatingSystem.IBMzOS) { if (!(reply = Execute("SITE DATASETMODE")).Success) { throw new FtpCommandException(reply); } if (!(reply = Execute("SITE QUOTESOVERRIDE")).Success) { throw new FtpCommandException(reply); } } #if !CORE14 } #endif } #if ASYNC // TODO: add example /// <summary> /// Connect to the server /// </summary> /// <exception cref="ObjectDisposedException">Thrown if this object has been disposed.</exception> public virtual async Task ConnectAsync(CancellationToken token = default(CancellationToken)) { FtpReply reply; LogFunc(nameof(ConnectAsync)); if (IsDisposed) { throw new ObjectDisposedException("This FtpClient object has been disposed. It is no longer accessible."); } if (m_stream == null) { m_stream = new FtpSocketStream(this); m_stream.ValidateCertificate += new FtpSocketStreamSslValidation(FireValidateCertficate); } else { if (IsConnected) { Disconnect(); } } if (Host == null) { throw new FtpException("No host has been specified"); } if (m_capabilities == null) { m_capabilities = new List<FtpCapability>(); } ResetStateFlags(); m_hashAlgorithms = FtpHashAlgorithm.NONE; m_stream.ConnectTimeout = m_connectTimeout; m_stream.SocketPollInterval = m_socketPollInterval; await ConnectAsync(m_stream, token); m_stream.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_keepAlive); #if !NO_SSL if (EncryptionMode == FtpEncryptionMode.Implicit) { await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } #endif await HandshakeAsync(token); m_serverType = FtpServerSpecificHandler.DetectFtpServer(this, HandshakeReply); if (SendHost) { if (!(reply = await ExecuteAsync("HOST " + (SendHostDomain != null ? SendHostDomain : Host), token)).Success) { throw new FtpException("HOST command failed."); } } #if !NO_SSL // try to upgrade this connection to SSL if supported by the server if (EncryptionMode == FtpEncryptionMode.Explicit || EncryptionMode == FtpEncryptionMode.Auto) { reply = await ExecuteAsync("AUTH TLS", token); if (!reply.Success) { _ConnectionFTPSFailure = true; if (EncryptionMode == FtpEncryptionMode.Explicit) { throw new FtpSecurityNotAvailableException("AUTH TLS command failed."); } } else if (reply.Success) { await m_stream.ActivateEncryptionAsync(Host, m_clientCerts.Count > 0 ? m_clientCerts : null, m_SslProtocols); } } #endif if (m_credentials != null) { await AuthenticateAsync(token); } // configure the default FTPS settings if (IsEncrypted && DataConnectionEncryption) { if (!(reply = await ExecuteAsync("PBSZ 0", token)).Success) { throw new FtpCommandException(reply); } if (!(reply = await ExecuteAsync("PROT P", token)).Success) { throw new FtpCommandException(reply); } } // if this is a clone these values should have already been loaded // so save some bandwidth and CPU time and skip executing this again. // otherwise clear the capabilities in case connection is reused to // a different server if (!m_isClone && m_checkCapabilities) { m_capabilities.Clear(); } bool assumeCaps = false; if (m_capabilities.IsBlank() && m_checkCapabilities) { if ((reply = await ExecuteAsync("FEAT", token)).Success && reply.InfoMessages != null) { GetFeatures(reply); } else { assumeCaps = true; } } // Enable UTF8 if the encoding is ASCII and UTF8 is supported if (m_textEncodingAutoUTF && m_textEncoding == Encoding.ASCII && HasFeature(FtpCapability.UTF8)) { m_textEncoding = Encoding.UTF8; } LogStatus(FtpTraceLevel.Info, "Text encoding: " + m_textEncoding.ToString()); if (m_textEncoding == Encoding.UTF8) { // If the server supports UTF8 it should already be enabled and this // command should not matter however there are conflicting drafts // about this so we'll just execute it to be safe. if ((reply = await ExecuteAsync("OPTS UTF8 ON", token)).Success) { _ConnectionUTF8Success = true; } } // Get the system type - Needed to auto-detect file listing parser if ((reply = await ExecuteAsync("SYST", token)).Success) { m_systemType = reply.Message; m_serverType = FtpServerSpecificHandler.DetectFtpServerBySyst(this); m_serverOS = FtpServerSpecificHandler.DetectFtpOSBySyst(this); } // Set a FTP server handler if a custom handler has not already been set if (ServerHandler == null) { ServerHandler = FtpServerSpecificHandler.GetServerHandler(m_serverType); } // Assume the system's capabilities if FEAT command not supported by the server if (assumeCaps) { FtpServerSpecificHandler.AssumeCapabilities(this, ServerHandler, m_capabilities, ref m_hashAlgorithms); } #if !NO_SSL && !CORE if (IsEncrypted && PlainTextEncryption) { if (!(reply = await ExecuteAsync("CCC", token)).Success) { throw new FtpSecurityNotAvailableException("Failed to disable encryption with CCC command. Perhaps your server does not support it or is not configured to allow it."); } else { // close the SslStream and send close_notify command to server m_stream.DeactivateEncryption(); // read stale data (server's reply?) await ReadStaleDataAsync(false, true, false, token); } } #endif // Unless a custom list parser has been set, // Detect the listing parser and prefer machine listings over any other type // FIX : #739 prefer using machine listings to fix issues with GetListing and DeleteDirectory if (ListingParser != FtpParser.Custom) { ListingParser = ServerHandler != null ? ServerHandler.GetParser() : FtpParser.Auto; if (HasFeature(FtpCapability.MLSD)) { ListingParser = FtpParser.Machine; } } // Create the parser even if the auto-OS detection failed m_listParser.Init(m_serverOS, ListingParser); // FIX : #318 always set the type when we create a new connection ForceSetDataType = true; if (ServerType == FtpServer.IBMzOSFTP && ServerOS == FtpOperatingSystem.IBMzOS) { if (!(reply = await ExecuteAsync("SITE DATASETMODE", token)).Success) { throw new FtpCommandException(reply); } if (!(reply = await ExecuteAsync("SITE QUOTESOVERRIDE", token)).Success) { throw new FtpCommandException(reply); } } } #endif /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> /// <param name="stream"></param> protected virtual void Connect(FtpSocketStream stream) { stream.Connect(Host, Port, InternetProtocolVersions); } #if ASYNC /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> /// <param name="stream"></param> /// <param name="token"></param> protected virtual async Task ConnectAsync(FtpSocketStream stream, CancellationToken token) { await stream.ConnectAsync(Host, Port, InternetProtocolVersions, token); } #endif /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> protected virtual void Connect(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions) { stream.Connect(host, port, ipVersions); } #if ASYNC /// <summary> /// Connect to the FTP server. Overridden in proxy classes. /// </summary> protected virtual Task ConnectAsync(FtpSocketStream stream, string host, int port, FtpIpVersion ipVersions, CancellationToken token) { return stream.ConnectAsync(host, port, ipVersions, token); } #endif protected FtpReply HandshakeReply; /// <summary> /// Called during Connect(). Typically extended by FTP proxies. /// </summary> protected virtual void Handshake() { FtpReply reply; if (!(reply = GetReply()).Success) { if (reply.Code == null) { throw new IOException("The connection was terminated before a greeting could be read."); } else { throw new FtpCommandException(reply); } } HandshakeReply = reply; } #if ASYNC /// <summary> /// Called during <see cref="ConnectAsync()"/>. Typically extended by FTP proxies. /// </summary> protected virtual async Task HandshakeAsync(CancellationToken token = default(CancellationToken)) { FtpReply reply; if (!(reply = await GetReplyAsync(token)).Success) { if (reply.Code == null) { throw new IOException("The connection was terminated before a greeting could be read."); } else { throw new FtpCommandException(reply); } } HandshakeReply = reply; } #endif /// <summary> /// Populates the capabilities flags based on capabilities /// supported by this server. This method is overridable /// so that new features can be supported /// </summary> /// <param name="reply">The reply object from the FEAT command. The InfoMessages property will /// contain a list of the features the server supported delimited by a new line '\n' character.</param> protected virtual void GetFeatures(FtpReply reply) { FtpServerSpecificHandler.GetFeatures(this, m_capabilities, ref m_hashAlgorithms, reply.InfoMessages.Split('\n')); } #if !ASYNC private delegate void AsyncConnect(); /// <summary> /// Initiates a connection to the server /// </summary> /// <param name="callback">AsyncCallback method</param> /// <param name="state">State object</param> /// <returns>IAsyncResult</returns> public IAsyncResult BeginConnect(AsyncCallback callback, object state) { AsyncConnect func; IAsyncResult ar; lock (m_asyncmethods) { ar = (func = Connect).BeginInvoke(callback, state); m_asyncmethods.Add(ar, func); } return ar; } /// <summary> /// Ends an asynchronous connection attempt to the server from <see cref="BeginConnect"/> /// </summary> /// <param name="ar"><see cref="IAsyncResult"/> returned from <see cref="BeginConnect"/></param> public void EndConnect(IAsyncResult ar) { GetAsyncDelegate<AsyncConnect>(ar).EndInvoke(ar); } #endif #endregion #region Login /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> protected virtual void Authenticate() { Authenticate(Credentials.UserName, Credentials.Password, Credentials.Domain); } #if ASYNC /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> protected virtual async Task AuthenticateAsync(CancellationToken token) { await AuthenticateAsync(Credentials.UserName, Credentials.Password, Credentials.Domain, token); } #endif /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> /// <exception cref="FtpAuthenticationException">On authentication failures</exception> /// <remarks> /// To handle authentication failures without retries, catch FtpAuthenticationException. /// </remarks> protected virtual void Authenticate(string userName, string password, string account) { // mark that we are not authenticated m_IsAuthenticated = false; // send the USER command along with the FTP username FtpReply reply = Execute("USER " + userName); // check the reply to the USER command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // if it was accepted else if (reply.Type == FtpResponseType.PositiveIntermediate) { // send the PASS command along with the FTP password reply = Execute("PASS " + password); // fix for #620: some servers send multiple responses that must be read and decoded, // otherwise the connection is aborted and remade and it goes into an infinite loop var staleData = ReadStaleData(false, true, true); if (staleData != null) { var staleReply = new FtpReply(); if (DecodeStringToReply(staleData, ref staleReply) && !staleReply.Success) { throw new FtpAuthenticationException(staleReply); } } // check the first reply to the PASS command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // only possible 3** here is `332 Need account for login` if (reply.Type == FtpResponseType.PositiveIntermediate) { reply = Execute("ACCT " + account); if (!reply.Success) { throw new FtpAuthenticationException(reply); } } // mark that we are authenticated m_IsAuthenticated = true; } } #if ASYNC /// <summary> /// Performs a login on the server. This method is overridable so /// that the login procedure can be changed to support, for example, /// a FTP proxy. /// </summary> /// <exception cref="FtpAuthenticationException">On authentication failures</exception> /// <remarks> /// To handle authentication failures without retries, catch FtpAuthenticationException. /// </remarks> protected virtual async Task AuthenticateAsync(string userName, string password, string account, CancellationToken token) { // send the USER command along with the FTP username FtpReply reply = await ExecuteAsync("USER " + userName, token); // check the reply to the USER command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // if it was accepted else if (reply.Type == FtpResponseType.PositiveIntermediate) { // send the PASS command along with the FTP password reply = await ExecuteAsync("PASS " + password, token); // fix for #620: some servers send multiple responses that must be read and decoded, // otherwise the connection is aborted and remade and it goes into an infinite loop var staleData = await ReadStaleDataAsync(false, true, true, token); if (staleData != null) { var staleReply = new FtpReply(); if (DecodeStringToReply(staleData, ref staleReply) && !staleReply.Success) { throw new FtpAuthenticationException(staleReply); } } // check the first reply to the PASS command if (!reply.Success) { throw new FtpAuthenticationException(reply); } // only possible 3** here is `332 Need account for login` if (reply.Type == FtpResponseType.PositiveIntermediate) { reply = await ExecuteAsync("ACCT " + account, token); if (!reply.Success) { throw new FtpAuthenticationException(reply); } } } } #endif #endregion #region Disconnect /// <summary> /// Disconnects from the server /// </summary> public virtual void Disconnect() { #if !CORE14 lock (m_lock) { #endif if (m_stream != null && m_stream.IsConnected) { try { if (!UngracefullDisconnection) { Execute("QUIT"); } } catch (Exception ex) { LogStatus(FtpTraceLevel.Warn, "FtpClient.Disconnect(): Exception caught and discarded while closing control connection: " + ex.ToString()); } finally { m_stream.Close(); } } #if !CORE14 } #endif } #if !ASYNC private delegate void AsyncDisconnect(); /// <summary> /// Initiates a disconnection on the server /// </summary> /// <param name="callback"><see cref="AsyncCallback"/> method</param> /// <param name="state">State object</param> /// <returns>IAsyncResult</returns> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { IAsyncResult ar; AsyncDisconnect func; lock (m_asyncmethods) { ar = (func = Disconnect).BeginInvoke(callback, state); m_asyncmethods.Add(ar, func); } return ar; } /// <summary> /// Ends a call to <see cref="BeginDisconnect"/> /// </summary> /// <param name="ar"><see cref="IAsyncResult"/> returned from <see cref="BeginDisconnect"/></param> public void EndDisconnect(IAsyncResult ar) { GetAsyncDelegate<AsyncDisconnect>(ar).EndInvoke(ar); } #endif #if ASYNC /// <summary> /// Disconnects from the server asynchronously /// </summary> public async Task DisconnectAsync(CancellationToken token = default(CancellationToken)) { if (m_stream != null && m_stream.IsConnected) { try { if (!UngracefullDisconnection) { await ExecuteAsync("QUIT", token); } } catch (Exception ex) { LogStatus(FtpTraceLevel.Warn, "FtpClient.Disconnect(): Exception caught and discarded while closing control connection: " + ex.ToString()); } finally { m_stream.Close(); } } } #endif #endregion #region FTPS /// <summary> /// Catches the socket stream ssl validation event and fires the event handlers /// attached to this object for validating SSL certificates /// </summary> /// <param name="stream">The stream that fired the event</param> /// <param name="e">The event args used to validate the certificate</param> private void FireValidateCertficate(FtpSocketStream stream, FtpSslValidationEventArgs e) { OnValidateCertficate(e); } /// <summary> /// Fires the SSL validation event /// </summary> /// <param name="e">Event Args</param> private void OnValidateCertficate(FtpSslValidationEventArgs e) { // automatically validate if ValidateAnyCertificate is set if (ValidateAnyCertificate) { e.Accept = true; return; } // fallback to manual validation using the ValidateCertificate event m_ValidateCertificate?.Invoke(this, e); } #endregion } }
31.25943
173
0.692016
[ "MIT" ]
DevDigiAcademy/FluentFTP
FluentFTP/Client/FtpClient_Connection.cs
33,979
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_WebAnalytics_Controls_SelectGraphPeriod { /// <summary> /// pnlRange control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlRange; /// <summary> /// ucRangeDatePicker control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.RangeDateTimePicker ucRangeDatePicker; /// <summary> /// btnUpdate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.LocalizedButton btnUpdate; }
31.756098
81
0.564516
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/WebAnalytics/Controls/SelectGraphPeriod.ascx.designer.cs
1,304
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace PocketBar.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class PlaygroundPage : ContentPage { public PlaygroundPage() { InitializeComponent(); } } }
23.681818
81
0.706334
[ "MIT" ]
BaristaStudio/PocketBar
PocketBar/PocketBar/Views/PlaygroundPage.xaml.cs
523
C#
namespace Netfox.Core.Interfaces.Model.Exports { /// <summary> Distinguishes between different email types behind common interface.</summary> public enum EMailType { /// <summary> An enum constant representing the unknown option.</summary> Unknown, /// <summary> An enum constant representing the raw email option.</summary> RawEmail, /// <summary> An enum constant representing the pop 3 organisation email option.</summary> POP3OrgEmail, /// <summary> An enum constant representing the SMTP organisation email option.</summary> SMTPOrgEmail, /// <summary> An enum constant representing the IMAP organisation email option.</summary> IMAPOrgEmail, // Crypto } /// <summary> Values that represent EMailContentType.</summary> public enum EMailContentType { /// <summary> An enum constant representing the unknown option.</summary> Unknown, /// <summary> An enum constant representing the whole option.</summary> Whole, /// <summary> An enum constant representing the fragment option.</summary> Fragment, /// <summary> An enum constant representing the crypto option.</summary> Crypto } /// <summary> Common email interface - ensures basic functionality.</summary> public interface IEMail : IExportBase { /// <summary> Type of email behind this interface.</summary> /// <value> The type.</value> EMailType EMailType { get; set; } /// <summary> Gets or sets the type of the content.</summary> /// <value> The type of the content.</value> EMailContentType ContentType { get; set; } string From { get; } string To { get; } string Bcc { get; } string Cc { get; } string Subject { get; } string RawContent { get; } } }
33.666667
98
0.625326
[ "Apache-2.0" ]
pokornysimon/NetfoxDetective
NetfoxCore/Common/Core/Interfaces/Model/Exports/IEMail.cs
1,921
C#