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 Chroma.STB.Image.Utility { internal static class MathExtensions { public static int stbi__bitreverse16(int n) { n = (int)(((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1)); n = (int)(((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2)); n = (int)(((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4)); n = (int)(((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8)); return (int)(n); } public static int stbi__bit_reverse(int v, int bits) { return (int)(stbi__bitreverse16((int)(v)) >> (16 - bits)); } public static uint _lrotl(uint x, int y) { return (x << y) | (x >> (32 - y)); } public static int ToReqComp(this ColorComponents? requiredComponents) { return requiredComponents != null ? (int)requiredComponents.Value : 0; } } }
26.068966
73
0.56746
[ "MIT" ]
Chroma-2D/Chroma
Chroma.STB/Image/Utility/MathExtensions.cs
758
C#
using System; using Moq; using NUnit.Framework; using ZeroLog.Appenders; using ZeroLog.Utils; namespace ZeroLog.Tests.Appenders { [TestFixture] public class GuardedAppenderTests { private Mock<IAppender> _appenderMock; private GuardedAppender _guardedAppender; [SetUp] public void SetUp() { _appenderMock = new Mock<IAppender>(); _guardedAppender = new GuardedAppender(_appenderMock.Object, TimeSpan.FromSeconds(15)); } [Test] public void should_append() { var logEvent = new Mock<ILogEvent>().Object; var message = new byte[4]; _guardedAppender.WriteEvent(logEvent, message, message.Length); _appenderMock.Verify(x => x.WriteEvent(logEvent, message, message.Length), Times.Once); } [Test] public void should_not_throw_if_inner_appender_throws() { var logEvent = new Mock<ILogEvent>().Object; var message = new byte[4]; _appenderMock.Setup(x => x.WriteEvent(logEvent, message, message.Length)).Throws<Exception>(); Assert.DoesNotThrow(() => _guardedAppender.WriteEvent(logEvent, message, message.Length)); } [Test] public void should_disable_appender_if_it_throws() { var logEvent = new Mock<ILogEvent>().Object; var message = new byte[4]; _appenderMock.Setup(x => x.WriteEvent(logEvent, message, message.Length)).Throws<Exception>(); _guardedAppender.WriteEvent(logEvent, message, message.Length); _guardedAppender.WriteEvent(logEvent, message, message.Length); _appenderMock.Verify(x => x.WriteEvent(logEvent, message, message.Length), Times.Once); } [Test] public void should_reenable_appender_after_quarantine_delay() { var logEvent = new Mock<ILogEvent>().Object; var message = new byte[4]; _appenderMock.Setup(x => x.WriteEvent(logEvent, message, message.Length)).Throws<Exception>(); SystemDateTime.PauseTime(); _guardedAppender.WriteEvent(logEvent, message, message.Length); _appenderMock.Verify(x => x.WriteEvent(logEvent, message, message.Length), Times.Once); SystemDateTime.AddToPausedTime(TimeSpan.FromSeconds(2)); _guardedAppender.WriteEvent(logEvent, message, message.Length); _appenderMock.Verify(x => x.WriteEvent(logEvent, message, message.Length), Times.Once); SystemDateTime.AddToPausedTime(TimeSpan.FromSeconds(20)); _guardedAppender.WriteEvent(logEvent, message, message.Length); _appenderMock.Verify(x => x.WriteEvent(logEvent, message, message.Length), Times.Exactly(2)); } } }
37.421053
106
0.639944
[ "MIT" ]
Abc-Arbitrage/ZeroLog
src/ZeroLog.Tests/Appenders/GuardedAppenderTests.cs
2,846
C#
// // Copyright © Microsoft Corporation, All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. namespace MessagingSamples { using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.ServiceBus; // IF YOU ARE JUST GETTING STARTED, // THESE ARE NOT THE DROIDS YOU ARE LOOKING FOR // PLEASE REVIEW "Program.cs" IN THE SAMPLE PROJECT // This is a common entry point class for all samples that provides // the Main() method entry point called by the CLR. It loads the properties // stored in the "azure-msg-samples.properties" file from the user profile // and then allows override of the settings from environment variables. class AppEntryPoint { const string RootSampleSendKeyName = "rootsamplesend"; const string RootSampleManageKeyName = "rootsamplemanage"; const string BasicQueueName = "BasicQueue"; const string PartitionedQueueName = "PartitionedQueue"; const string DupdetectQueueName = "DupdetectQueue"; const string BasicTopicName = "BasicTopic"; const string SendKeyName = "samplesend"; const string ReceiveKeyName = "samplelisten"; const string SessionQueueName = "SessionQueue"; const string BasicQueue2Name = "BasicQueue2"; const string ManageKeyName = "samplemanage"; static readonly string servicebusNamespace = "SERVICEBUS_NAMESPACE"; static readonly string servicebusEntityPath = "SERVICEBUS_ENTITY_PATH"; static readonly string servicebusFqdnSuffix = "SERVICEBUS_FQDN_SUFFIX"; static readonly string servicebusSendKey = "SERVICEBUS_SEND_KEY"; static readonly string servicebusListenKey = "SERVICEBUS_LISTEN_KEY"; static readonly string servicebusManageKey = "SERVICEBUS_MANAGE_KEY"; static readonly string samplePropertiesFileName = "azure-msg-config.properties"; #if STA [STAThread] #endif static void Main(string[] args) { Run(); } // [DebuggerStepThrough] static void Run() { var properties = new Dictionary<string, string> { {servicebusNamespace, null}, {servicebusEntityPath, null}, {servicebusFqdnSuffix, null}, {servicebusSendKey, null}, {servicebusListenKey, null}, {servicebusManageKey, null} }; // read the settings file created by the ./setup.ps1 file var settingsFile = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), samplePropertiesFileName); if (File.Exists(settingsFile)) { using (var fs = new StreamReader(settingsFile)) { while (!fs.EndOfStream) { var readLine = fs.ReadLine(); if (readLine != null) { var propl = readLine.Trim(); var cmt = propl.IndexOf('#'); if (cmt > -1) { propl = propl.Substring(0, cmt).Trim(); } if (propl.Length > 0) { var propi = propl.IndexOf('='); if (propi == -1) { continue; } var propKey = propl.Substring(0, propi).Trim(); var propVal = propl.Substring(propi + 1).Trim(); if (properties.ContainsKey(propKey)) { properties[propKey] = propVal; } } } } } } // get overrides from the environment foreach (var prop in properties) { var env = Environment.GetEnvironmentVariable(prop.Key); if (env != null) { properties[prop.Key] = env; } } var hostName = properties[servicebusNamespace] + "." + properties[servicebusFqdnSuffix]; var rootUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, "/").ToString(); var sbUri = new UriBuilder("sb", hostName, -1, "/").ToString(); var program = Activator.CreateInstance(typeof(Program)); if (program is IDynamicSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( RootSampleManageKeyName, properties[servicebusManageKey]) .GetWebTokenAsync(rootUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDynamicSample)program).Run(sbUri, token).GetAwaiter().GetResult(); } else if (program is IDynamicSampleWithKeys) { ((IDynamicSampleWithKeys)program).Run( sbUri, RootSampleManageKeyName, properties[servicebusManageKey], RootSampleSendKeyName, properties[servicebusSendKey], RootSampleSendKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); } else if (program is IBasicQueueSendReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicQueueSendSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is IBasicQueueReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueSendReceiveSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueSendSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueReceiveSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, SessionQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueSendReceiveSample)program).Run(sbUri, SessionQueueName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueSendSample) { var entityName = SessionQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueReceiveSample) { var entityName = SessionQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueSendReceiveSample)program).Run(sbUri, DupdetectQueueName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueSendSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueSendSample)program).Run(sbUri, DupdetectQueueName, sendToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueReceiveSample)program).Run(sbUri, DupdetectQueueName, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicSendReceiveSample)program).Run(sbUri, BasicTopicName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicSendSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicSendSample)program).Run(sbUri, BasicTopicName, sendToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicReceiveSample)program).Run(sbUri, BasicTopicName, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), RootSampleManageKeyName, properties[servicebusManageKey]); ((IBasicTopicConnectionStringSample)program).Run(BasicTopicName, connectionString).GetAwaiter().GetResult(); } else if (program is IConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), RootSampleManageKeyName, properties[servicebusManageKey]); ((IConnectionStringSample)program).Run(connectionString).GetAwaiter().GetResult(); } else if (program is IBasicQueueConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), RootSampleManageKeyName, properties[servicebusManageKey]); ((IBasicQueueConnectionStringSample)program).Run(BasicQueueName, connectionString).GetAwaiter().GetResult(); } else if (program is IDualQueueSendReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueue2Name; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, entity2Name, receiveToken).GetAwaiter().GetResult(); } else if (program is IDualQueueSampleWithFullRights) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var token1 = TokenProvider.CreateSharedAccessSignatureTokenProvider( ManageKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueue2Name; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var token2 = TokenProvider.CreateSharedAccessSignatureTokenProvider( ManageKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSampleWithFullRights)program).Run(sbUri, entityName, token1, entity2Name, token2).GetAwaiter().GetResult(); } else if (program is IDualQueueSendReceiveFlipsideSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicQueue2Name).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueueName; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSendReceiveFlipsideSample)program).Run(sbUri, BasicQueue2Name, sendToken, entity2Name, receiveToken). GetAwaiter(). GetResult(); } else if (program is IBasicQueueSampleWithKeys) { ((IBasicQueueSampleWithKeys)program).Run( sbUri, BasicQueueName, SendKeyName, properties[servicebusSendKey], ReceiveKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); ; } else if (program is IDualBasicQueueSampleWithKeys) { ((IDualBasicQueueSampleWithKeys)program).Run( sbUri, BasicQueueName, BasicQueue2Name, SendKeyName, properties[servicebusSendKey], ReceiveKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); } } } interface IBasicQueueSendReceiveSample { Task Run(string namespaceAddress, string queueName, string sendToken, string receiveToken); } interface IBasicQueueSampleWithKeys { Task Run( string namespaceAddress, string basicQueueName, string sendKeyName, string sendKey, string receiveKeyName, string receiveKey); } interface IBasicQueueSendSample { Task Run(string namespaceAddress, string queueName, string sendToken); } interface IBasicQueueReceiveSample { Task Run(string namespaceAddress, string queueName, string receiveToken); } interface IPartitionedQueueSendReceiveSample { Task Run(string namespaceAddress, string queueName, string sendToken, string receiveToken); } interface IPartitionedQueueSendSample { Task Run(string namespaceAddress, string queueName, string sendToken); } interface IPartitionedQueueReceiveSample { Task Run(string namespaceAddress, string queueName, string receiveToken); } interface ISessionQueueSendReceiveSample { Task Run(string namespaceAddress, string queueName, string sendToken, string receiveToken); } interface ISessionQueueSendSample { Task Run(string namespaceAddress, string queueName, string sendToken); } interface ISessionQueueReceiveSample { Task Run(string namespaceAddress, string queueName, string receiveToken); } interface IBasicTopicSendReceiveSample { Task Run(string namespaceAddress, string TopicName, string sendToken, string receiveToken); } interface IBasicTopicSendSample { Task Run(string namespaceAddress, string TopicName, string sendToken); } interface IBasicTopicReceiveSample { Task Run(string namespaceAddress, string TopicName, string receiveToken); } interface IPartitionedTopicSendReceiveSample { Task Run(string namespaceAddress, string TopicName, string sendToken, string receiveToken); } interface IPartitionedTopicSendSample { Task Run(string namespaceAddress, string TopicName, string sendToken); } interface IPartitionedTopicReceiveSample { Task Run(string namespaceAddress, string TopicName, string receiveToken); } interface IDupdetectQueueSendReceiveSample { Task Run(string namespaceAddress, string queueName, string sendToken, string receiveToken); } interface IDupdetectQueueSendSample { Task Run(string namespaceAddress, string queueName, string sendToken); } interface IDupdetectQueueReceiveSample { Task Run(string namespaceAddress, string queueName, string receiveToken); } interface IConnectionStringSample { Task Run(string connectionString); } interface IBasicQueueConnectionStringSample { Task Run(string queueName, string connectionString); } interface IBasicTopicConnectionStringSample { Task Run(string queueName, string connectionString); } interface IDynamicSample { Task Run(string namespaceAddress, string manageToken); } interface IDynamicSampleWithKeys { Task Run( string namespaceAddress, string manageKeyName, string manageKey, string sendKeyName, string sendKey, string receiveKeyName, string receiveKey); } interface IDualQueueSendReceiveSample { Task Run(string namespaceAddress, string sendQueueName, string sendToken, string receiveQueueName, string receiveToken); } interface IDualQueueSampleWithFullRights { Task Run(string namespaceAddress, string queueName1, string manageToken1, string queueName2, string manageToken2); } interface IDualQueueSendReceiveFlipsideSample { Task Run(string namespaceAddress, string sendQueueName, string sendToken, string receiveQueueName, string receiveToken); } interface IDualBasicQueueSampleWithKeys { Task Run( string namespaceAddress, string basicQueueName, string basicQueue2Name, string sendKeyName, string sendKey, string receiveKeyName, string receiveKey); } }
44.133127
141
0.5886
[ "MIT" ]
pravinrest/azure
samples/DotNet/Microsoft.ServiceBus.Messaging/common/Main.cs
28,513
C#
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using DomainValues.Model; using DomainValues.Util; namespace DomainValues.Processing.Parsing { internal class KeyParser : ParserBase { protected override IEnumerable<ParsedSpan> GetParamTokens(int lineNumber, TextSpan span) { List<TextSpan> parameters = Regex.Matches(span.Text, @"\S+") .Cast<Match>() .Select(a => new TextSpan(span.Start + a.Index, a.Value)) .ToList(); List<TextSpan> duplicates = parameters .GroupBy(a => a.Text.ToLower()) .SelectMany(a => a.Skip(1)) .ToList(); foreach (TextSpan parameter in parameters) { ParsedSpan parsedSpan = new ParsedSpan(lineNumber,TokenType.Key | TokenType.Parameter,parameter); if (duplicates.Any(a=>a.Start==parameter.Start && a.Text == parameter.Text)) { parsedSpan.Errors.Add(new Error(string.Format(Errors.DuplicateValue,"Key",parameter.Text))); } yield return parsedSpan; } } protected override TokenType PrimaryType => TokenType.Key; protected override TokenType? NextType { get; set; } = TokenType.Data | TokenType.Enum; protected override int KeywordLength => 3; } }
36.85
114
0.580733
[ "MIT" ]
dannyquinn/domainvalues
DomainValues/Processing/Parsing/KeyParser.cs
1,476
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.EventHubs.Tests.ServiceFabricProcessor { using System; using System.Collections.Generic; using System.Threading; using Microsoft.Azure.EventHubs.ServiceFabricProcessor; using Microsoft.ServiceFabric.Data; using Microsoft.ServiceFabric.Data.Collections; using Xunit; public class OptionsTests { [Fact] [DisplayTestMethodName] public void SimpleOptionsTest() { TestState state = new TestState(); state.Initialize("SimpleOptions", 1, 0); const int testBatchSize = 42; Assert.False(state.Options.MaxBatchSize == testBatchSize); // make sure new value is not the same as the default state.Options.MaxBatchSize = testBatchSize; const int testPrefetchCount = 444; Assert.False(state.Options.PrefetchCount == testPrefetchCount); state.Options.PrefetchCount = testPrefetchCount; TimeSpan testReceiveTimeout = TimeSpan.FromSeconds(10.0); Assert.False(state.Options.ReceiveTimeout.Equals(testReceiveTimeout)); state.Options.ReceiveTimeout = testReceiveTimeout; ReceiverOptions receiverOptions = new ReceiverOptions(); Assert.Null(receiverOptions.Identifier); const string tag = "SimpleOptions"; receiverOptions.Identifier = tag; state.Options.ClientReceiverOptions = receiverOptions; ServiceFabricProcessor sfp = new ServiceFabricProcessor( state.ServiceUri, state.ServicePartitionId, state.StateManager, state.StatefulServicePartition, state.Processor, state.ConnectionString, "$Default", state.Options); sfp.MockMode = state.PartitionLister; sfp.EventHubClientFactory = new EventHubMocks.EventHubClientFactoryMock(1, tag); state.PrepareToRun(); state.StartRun(sfp); state.VerifyNormalStartup(10); state.CountNBatches(5, 10); // EXPECTED RESULT: Normal processing. Validate that simple options MaxBatchSize, PrefetchCount, ReceiveTimeout, // and ClientReceiverOptions are passed through to EH API. Assert.True(EventHubMocks.PartitionReceiverMock.receivers.ContainsKey(tag), "Cannot find receiver"); EventHubMocks.PartitionReceiverMock testReceiver = EventHubMocks.PartitionReceiverMock.receivers[tag]; Assert.True(testReceiver.HandlerBatchSize == testBatchSize, $"Unexpected batch size {testReceiver.HandlerBatchSize}"); Assert.True(testReceiver.PrefetchCount == testPrefetchCount, $"Unexpected prefetch count {testReceiver.PrefetchCount}"); Assert.True(testReceiver.ReceiveTimeout.Equals(testReceiveTimeout), $"Unexpected receive timeout {testReceiver.ReceiveTimeout}"); Assert.NotNull(testReceiver.Options); Assert.Equal(testReceiver.Options.Identifier, tag); // EnableReceiverRuntimeMetric is false by default. This case is a convenient opportunity to // verify that RuntimeInformation was not updated when the option is false. Assert.True(state.Processor.LatestContext.RuntimeInformation.LastSequenceNumber == 0L, $"RuntimeInformation.LastSequenceNumber is {state.Processor.LatestContext.RuntimeInformation.LastSequenceNumber}"); state.DoNormalShutdown(10); state.WaitRun(); Assert.True(state.Processor.TotalErrors == 0, $"Errors found {state.Processor.TotalErrors}"); Assert.Null(state.ShutdownException); } [Fact] [DisplayTestMethodName] public void UseInitialPositionProviderTest() { TestState state = new TestState(); state.Initialize("UseInitialPositionProvider", 1, 0); const long firstSequenceNumber = 3456L; state.Options.InitialPositionProvider = (partitionId) => { return EventPosition.FromSequenceNumber(firstSequenceNumber); }; ServiceFabricProcessor sfp = new ServiceFabricProcessor( state.ServiceUri, state.ServicePartitionId, state.StateManager, state.StatefulServicePartition, state.Processor, state.ConnectionString, "$Default", state.Options); sfp.MockMode = state.PartitionLister; sfp.EventHubClientFactory = new EventHubMocks.EventHubClientFactoryMock(1); state.PrepareToRun(); state.StartRun(sfp); state.RunForNBatches(20, 10); state.WaitRun(); // EXPECTED RESULT: Normal processing. Sequence number of first event processed should match that // supplied in the InitialPositionProvider. Assert.True(state.Processor.FirstEvent.SystemProperties.SequenceNumber == (firstSequenceNumber + 1L), $"Got unexpected first sequence number {state.Processor.FirstEvent.SystemProperties.SequenceNumber}"); Assert.True(state.Processor.TotalErrors == 0, $"Errors found {state.Processor.TotalErrors}"); Assert.Null(state.ShutdownException); } [Fact] [DisplayTestMethodName] public void IgnoreInitialPositionProviderTest() { TestState state = new TestState(); state.Initialize("IgnoreInitialPositionProvider", 1, 0); const long ippSequenceNumber = 3456L; state.Options.InitialPositionProvider = (partitionId) => { return EventPosition.FromSequenceNumber(ippSequenceNumber); }; // Fake up a checkpoint using code borrowed from ReliableDictionaryCheckpointManager IReliableDictionary<string, Dictionary<string, object>> store = state.StateManager.GetOrAddAsync<IReliableDictionary<string, Dictionary<string, object>>>("EventProcessorCheckpointDictionary").Result; const long checkpointSequenceNumber = 8888L; Checkpoint fake = new Checkpoint((checkpointSequenceNumber * 100L).ToString(), checkpointSequenceNumber); using (ITransaction tx = state.StateManager.CreateTransaction()) { store.SetAsync(tx, "0", fake.ToDictionary(), TimeSpan.FromSeconds(5.0), CancellationToken.None).Wait(); tx.CommitAsync().Wait(); } ServiceFabricProcessor sfp = new ServiceFabricProcessor( state.ServiceUri, state.ServicePartitionId, state.StateManager, state.StatefulServicePartition, state.Processor, state.ConnectionString, "$Default", state.Options); sfp.MockMode = state.PartitionLister; sfp.EventHubClientFactory = new EventHubMocks.EventHubClientFactoryMock(1); state.PrepareToRun(); state.StartRun(sfp); state.RunForNBatches(20, 10); state.WaitRun(); // EXPECTED RESULT: Normal processing. Sequence number of first event processed should match that // supplied in the checkpoint, NOT the InitialPositionProvider. Assert.True(state.Processor.FirstEvent.SystemProperties.SequenceNumber == (checkpointSequenceNumber + 1L), $"Got unexpected first sequence number {state.Processor.FirstEvent.SystemProperties.SequenceNumber}"); Assert.True(state.Processor.TotalErrors == 0, $"Errors found {state.Processor.TotalErrors}"); Assert.Null(state.ShutdownException); } [Fact] [DisplayTestMethodName] public void RuntimeInformationTest() { TestState state = new TestState(); state.Initialize("RuntimeInformation", 1, 0); state.Options.EnableReceiverRuntimeMetric = true; ServiceFabricProcessor sfp = new ServiceFabricProcessor( state.ServiceUri, state.ServicePartitionId, state.StateManager, state.StatefulServicePartition, state.Processor, state.ConnectionString, "$Default", state.Options); sfp.MockMode = state.PartitionLister; sfp.EventHubClientFactory = new EventHubMocks.EventHubClientFactoryMock(1); state.PrepareToRun(); state.StartRun(sfp); state.RunForNBatches(20, 10); state.WaitRun(); // EXPECTED RESULT: Normal processing. Verify that the RuntimeInformation property of the partition // context is updated. Assert.True(state.Processor.LatestContext.RuntimeInformation.LastSequenceNumber == state.Processor.LastEvent.SystemProperties.SequenceNumber); Assert.True(state.Processor.TotalErrors == 0, $"Errors found {state.Processor.TotalErrors}"); Assert.Null(state.ShutdownException); } } }
47.712121
154
0.639251
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/eventhub/Microsoft.Azure.EventHubs/tests/ServiceFabricProcessor/OptionsTests.cs
9,449
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace KuhlEngine { public static class Event { // Render public delegate void RenderHandler(Image aFrame); public static RenderHandler NewFrame; // Collision public delegate void CollisionHandler(CollisionEventArgs e); public static CollisionHandler Collision; } public class CollisionEventArgs { public Item ActiveItem { get; internal set; } public Item PassiveItem { get; internal set; } public int Type { get; internal set; } public bool Cancel { get; set; } } }
23.9
68
0.670851
[ "Artistic-2.0" ]
TeamKuhl/KuhlEngine
KuhlEngine/Event.cs
719
C#
using System; using Xunit; namespace Colaboradix.IntegrationTests { public class UnitTest1 { [Fact] public void Test1() { } } }
11.6
38
0.551724
[ "MIT" ]
lucasrosaalves/Colaboradix
tests/Colaboradix.IntegrationTests/UnitTest1.cs
174
C#
// <auto-generated /> using System; using Equinox.Infra.Data.Context; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace Equinox.Infra.Data.Migrations { [DbContext(typeof(EquinoxContext))] [Migration("20201205064342_ajusteVeterinario2")] partial class ajusteVeterinario2 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) .HasAnnotation("ProductVersion", "3.1.4") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("Equinox.Domain.Models.Cliente", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("Id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Cpf") .IsRequired() .HasColumnType("varchar(20)") .HasMaxLength(20); b.Property<DateTime?>("DataCadastro") .HasColumnType("timestamp"); b.Property<string>("Nome") .HasColumnType("varchar(150)") .HasMaxLength(150); b.Property<string>("Observacao") .HasColumnType("varchar(250)") .HasMaxLength(250); b.HasKey("Id"); b.ToTable("Cliente"); }); modelBuilder.Entity("Equinox.Domain.Models.ClienteAnimal", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("Id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("ClienteId") .HasColumnName("ClienteId") .HasColumnType("integer"); b.Property<DateTime?>("DataCadastro") .HasColumnType("timestamp"); b.Property<int>("Idade") .HasColumnType("int"); b.Property<string>("Nome") .IsRequired() .HasColumnType("varchar(250)") .HasMaxLength(150); b.Property<int>("TipoAnimalId") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ClienteId"); b.ToTable("ClienteAnimal"); }); modelBuilder.Entity("Equinox.Domain.Models.ClienteContato", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("Id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("ClienteId") .HasColumnName("ClienteId") .HasColumnType("integer"); b.Property<string>("NomeContato") .IsRequired() .HasColumnType("varchar(150)") .HasMaxLength(150); b.Property<int>("TipoContatoId") .HasColumnName("TipoContatoId") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ClienteId"); b.ToTable("ClienteContato"); }); modelBuilder.Entity("Equinox.Domain.Models.TipoAnimal", b => { b.Property<int>("Id") .HasColumnType("integer"); b.Property<string>("Nome") .IsRequired() .HasColumnType("varchar(150)") .HasMaxLength(150); b.HasKey("Id"); b.ToTable("TipoAnimal"); b.HasData( new { Id = 1, Nome = "Cão" }, new { Id = 2, Nome = "Gato" }, new { Id = 3, Nome = "Hamster" }); }); modelBuilder.Entity("Equinox.Domain.Models.TipoContato", b => { b.Property<int>("Id") .HasColumnType("integer"); b.Property<string>("Nome") .IsRequired() .HasColumnType("varchar(150)") .HasMaxLength(150); b.HasKey("Id"); b.ToTable("TipoContato"); b.HasData( new { Id = 1, Nome = "Telefone" }, new { Id = 2, Nome = "Celular" }, new { Id = 3, Nome = "E-mail" }); }); modelBuilder.Entity("Equinox.Domain.Models.Veterinario", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("Id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Cpf") .IsRequired() .HasColumnType("varchar(20)") .HasMaxLength(20); b.Property<DateTime?>("DataCadastro") .HasColumnType("timestamp"); b.Property<DateTime?>("DataContratacao") .HasColumnType("timestamp"); b.Property<bool>("Geriatra") .HasColumnType("boolean"); b.Property<string>("Nome") .HasColumnType("varchar(150)") .HasMaxLength(150); b.HasKey("Id"); b.ToTable("Veterinario"); }); modelBuilder.Entity("Equinox.Domain.Models.VeterinarioGrade", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("Id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("DiaSemana") .HasColumnType("integer"); b.Property<DateTime>("HorFim") .HasColumnType("timestamp"); b.Property<DateTime>("HorIni") .HasColumnType("timestamp"); b.Property<int>("Intervalo") .HasColumnType("integer"); b.Property<int>("VeterinarioId") .HasColumnType("integer"); b.HasKey("Id"); b.ToTable("VeterinarioGrade"); }); modelBuilder.Entity("Equinox.Domain.Models.ClienteAnimal", b => { b.HasOne("Equinox.Domain.Models.Cliente", "Cliente") .WithMany("ClienteAnimal") .HasForeignKey("ClienteId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Equinox.Domain.Models.ClienteContato", b => { b.HasOne("Equinox.Domain.Models.Cliente", "Cliente") .WithMany("ClienteContato") .HasForeignKey("ClienteId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.957364
128
0.425461
[ "MIT" ]
sergfarias/BackendGranado
src/Equinox.Infra.Data/Migrations/20201205064342_ajusteVeterinario2.Designer.cs
9,280
C#
namespace SpottedZebra.UnitySizeExplorer.WPF.Views.Pages { using System; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.Win32; using ViewModels.Pages; public partial class StartPageView : UserControl { public static readonly RoutedUICommand OpenAction = new RoutedUICommand( "OpenAction", "OpenAction", typeof(StartPageView)); public StartPageView() { this.InitializeComponent(); this.Loaded += this.OnLoaded; } private static string GetDefaultUnityLogPath() { var appdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var defaultPath = Path.Combine(appdata, "Unity", "Editor"); return defaultPath; } private void OnLoaded(object sender, RoutedEventArgs e) { this.Focus(); } private void OnOpen(object sender, ExecutedRoutedEventArgs e) { var openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = GetDefaultUnityLogPath(); openFileDialog.DefaultExt = ".log"; openFileDialog.Filter = "Unity Editor.log file (*.log)|*.log"; var result = openFileDialog.ShowDialog(); if (result.HasValue && result.Value) { var fileName = openFileDialog.FileName; ((StartPageViewModel)this.DataContext).OpenFile(fileName); } } private void OnFileDropped(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); var fileName = files[0]; ((StartPageViewModel)this.DataContext).OpenFile(fileName); } } private void OnClose(object sender, ExecutedRoutedEventArgs e) { Application.Current.Shutdown(); } } }
30.314286
100
0.592366
[ "MIT" ]
U3DC/unitysizeexplorer
Source/UnitySizeExplorer.WPF/Views/Pages/StartPageView.xaml.cs
2,124
C#
/* * LambdaSharp (λ#) * Copyright (C) 2018-2019 * lambdasharp.net * * 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; using System.Text; using Amazon.CloudFormation.Model; namespace LambdaSharp.Tool.Cli.Tier { internal class TierModuleDetails { //--- Properties --- public string StackName { get; set; } public string ModuleDeploymentName { get; set; } public string StackStatus { get; set; } public DateTime DeploymentDate { get; set; } public Stack Stack { get; set; } public string ModuleReference { get; set; } public string CoreServices { get; set; } public bool IsRoot { get; set; } public bool HasDefaultSecretKeyParameter { get; set; } } }
32.487179
75
0.683504
[ "Apache-2.0" ]
spencerkittleson/LambdaSharpTool
src/LambdaSharp.Tool/Cli/Tier/TierModuleDetails.cs
1,268
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("01. Convert from base-10 to base-N")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Convert from base-10 to base-N")] [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("a4cf1a68-7361-442b-8498-63f866866175")] // 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.945946
84
0.741846
[ "MIT" ]
IvelinMarinov/SoftUni
02. Programming Fundamentals - Jan2017/09. Strings - Exercises/01. Convert from base-10 to base-N/Properties/AssemblyInfo.cs
1,444
C#
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. namespace UnrealBuildTool.Rules { public class WmfMedia : ModuleRules { public WmfMedia(ReadOnlyTargetRules Target) : base(Target) { DynamicallyLoadedModuleNames.AddRange( new string[] { "Media", }); PrivateDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "MediaUtils", "RenderCore", "WmfMediaFactory", }); PrivateIncludePathModuleNames.AddRange( new string[] { "Media", }); PrivateIncludePaths.AddRange( new string[] { "WmfMedia/Private", "WmfMedia/Private/Player", "WmfMedia/Private/Wmf", }); if (Target.bCompileAgainstEngine) { PrivateDependencyModuleNames.Add("Engine"); PrivateDependencyModuleNames.Add("HeadMountedDisplay"); } if (Target.Type != TargetType.Server) { if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32)) { PublicDelayLoadDLLs.Add("mf.dll"); PublicDelayLoadDLLs.Add("mfplat.dll"); PublicDelayLoadDLLs.Add("mfplay.dll"); PublicDelayLoadDLLs.Add("mfuuid.dll"); PublicDelayLoadDLLs.Add("shlwapi.dll"); } } } } }
22.142857
60
0.657258
[ "MIT" ]
CaptainUnknown/UnrealEngine_NVIDIAGameWorks
Engine/Plugins/Media/WmfMedia/Source/WmfMedia/WmfMedia.Build.cs
1,240
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Elight.Utility.ResponseModels { /// <summary> /// Laytpl + Laypage 分页模型。 /// </summary> /// <typeparam name="TEntity"></typeparam> public class LayPadding<TEntity> where TEntity : class { public int code { get; set; } /// <summary> /// 获取结果。 /// </summary> public bool result { get; set; } /// <summary> /// 备注信息。 /// </summary> public string msg { get; set; } /// <summary> /// 数据列表。 /// </summary> public List<TEntity> list { get; set; } public string backgroundImage { get; set; } /// <summary> /// 记录条数。 /// </summary> public long count { get; set; } } }
22.459459
58
0.511432
[ "MIT" ]
luhongguo/AdminAgentAnchor
Elight.Utility/ResponseModels/LayPadding.cs
883
C#
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Mvc.Rendering; using System; using FactoryManager.Models; namespace FactoryManager.Controllers { public class EngineersController : Controller { private readonly FactoryManagerContext _db; public EngineersController(FactoryManagerContext db) { _db = db; } List<Engineer> AllEngineers() => _db.Engineers.ToList(); public void AddNewEngineerMachine(int machineId, int EngineerId) => _db.EngineerMachines.Add(new EngineerMachine() { EngineerId = EngineerId, MachineId = machineId }); public ActionResult Index() => View(AllEngineers()); public ActionResult Create() { ViewBag.MachineId = new SelectList(_db.Machines, "MachineId", "ModelName"); return View(); } [HttpPost] public ActionResult Create(Engineer engineer) { _db.Engineers.Add(engineer); _db.SaveChanges(); return RedirectToAction("Edit", new {id = engineer.EngineerId}); } public ActionResult Details(int id) { var engineer = _db.Engineers .Include(engineer => engineer.EngineerMachines) .ThenInclude(em => em.Machine) .FirstOrDefault(e => e.EngineerId == id); return View(engineer); } public ActionResult Delete(int id) { Engineer e = _db.Engineers.FirstOrDefault(engineer => engineer.EngineerId == id); return View(e); } [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { var e = _db.Engineers.FirstOrDefault(engineer => engineer.EngineerId == id); _db.Engineers.Remove(e); _db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Edit(int id) { var e = _db.Engineers.FirstOrDefault(e => e.EngineerId == id); ViewBag.MachineId = new SelectList(_db.Machines, "MachineId", "ModelName"); return View(e); } [HttpPost] public ActionResult Edit(Engineer engineer, int MachineId) { if (MachineId != 0) { AddNewEngineerMachine(MachineId, engineer.EngineerId); } _db.Entry(engineer).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } [HttpPost] public ActionResult DeleteMachine(int machineId, int id) { Console.WriteLine(machineId); var em = _db.EngineerMachines.FirstOrDefault(em => em.EngineerMachineId == machineId); _db.EngineerMachines.Remove(em); _db.SaveChanges(); return RedirectToAction("Edit", new {id = id}); } } }
30.597701
172
0.671675
[ "MIT" ]
reeder32/Factory.Solution
Factory/Controllers/EngineersController.cs
2,662
C#
 using System; namespace VeiligStallen.ApiClient.DataModel { /// <summary> /// Transactions data holder for chart display /// </summary> public class TransactionsChartData { /// <summary> /// Date range start /// </summary> public DateTime? DateFrom { get; set; } /// <summary> /// Date range end /// </summary> public DateTime? DateTo { get; set; } /// <summary> /// Sampling interval /// </summary> public TimeSpan SamplingInterval { get; set; } /// <summary> /// Sampling interval friendly name if any /// </summary> public string SamplingIntervalName { get; set; } /// <summary> /// Time slots the data have been aggregated to /// </summary> public AggregationTimeSlot[] DataAggregationTimeSlots { get; set; } /// <summary> /// The actual aggregated data /// </summary> public TransactionsChartDataRecord[] Data { get; set; } } /// <summary> /// Transactions data single rec for the chart /// </summary> public class TransactionsChartDataRecord { /// <summary> /// sortable time stamp (ticks) /// </summary> public long TimeStampSort { get; set; } /// <summary> /// Time stamp /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// data aggregated for declared AggregationTimeSlots /// </summary> public int[] Data { get; set; } } }
25.03125
75
0.537453
[ "MIT" ]
cartomatic/Veiligstallen.ApiClient
Veiligstallen.ApiClient/DataModel/TransactionChartData.cs
1,604
C#
using Terraria; using Terraria.ID; using Terrexpansion.Common.Systems.Players; namespace Terrexpansion.Content.Items.Accessories.Summoner { public class VileVial : BaseItem { public override void SetStaticDefaults() => Tooltip.SetDefault("+3 summon damage" + "\nSummon weapons become corrosive"); public override void SafeSetDefaults() { item.rare = ItemRarityID.Blue; item.value = Item.sellPrice(gold: 1); item.accessory = true; } public override void UpdateAccessory(Player player, bool hideVisual) => player.GetModPlayer<TerrePlayer>().vileVial = true; } }
31.571429
131
0.665158
[ "MIT" ]
Steviegt6/Terrexpansion
Content/Items/Accessories/Summoner/VileVial.cs
665
C#
using System.Collections.Generic; namespace Nest { public class RangeBucket : BucketBase, IBucket { public RangeBucket(IReadOnlyDictionary<string, IAggregate> dict) : base(dict) { } public long DocCount { get; set; } public double? From { get; set; } public string FromAsString { get; set; } public string Key { get; set; } public double? To { get; set; } public string ToAsString { get; set; } } }
23.333333
83
0.690476
[ "Apache-2.0" ]
Henr1k80/elasticsearch-net
src/Nest/Aggregations/Bucket/Range/RangeBucket.cs
422
C#
using System; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Web.DynamicData; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebFormsApp { public partial class Children_InsertField : System.Web.DynamicData.FieldTemplateUserControl { } }
23.928571
97
0.8
[ "MIT" ]
jarman75/NetWeb
WebFormsApp/DynamicData/FieldTemplates/Children_Insert.ascx.cs
335
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.UserModel.Helpers { using NPOI.SS.Formula; using NPOI.SS.UserModel; using NPOI.SS.Util; using System.Collections.Generic; using System.Linq; /** * Helper for Shifting rows up or down * * This abstract class exists to consolidate duplicated code between XSSFRowShifter and HSSFRowShifter (currently methods sprinkled throughout HSSFSheet) */ public abstract class RowShifter { protected ISheet sheet; public RowShifter(ISheet sh) { sheet = sh; } /** * Shifts, grows, or shrinks the merged regions due to a row Shift. * Merged regions that are completely overlaid by Shifting will be deleted. * * @param startRow the row to start Shifting * @param endRow the row to end Shifting * @param n the number of rows to shift * @return an array of affected merged regions, doesn't contain deleted ones */ public List<CellRangeAddress> ShiftMergedRegions(int startRow, int endRow, int n) { List<CellRangeAddress> ShiftedRegions = new List<CellRangeAddress>(); ISet<int> removedIndices = new HashSet<int>(); //move merged regions completely if they fall within the new region boundaries when they are Shifted int size = sheet.NumMergedRegions; for (int i = 0; i < size; i++) { CellRangeAddress merged = sheet.GetMergedRegion(i); // remove merged region that overlaps Shifting if (startRow + n <= merged.FirstRow && endRow + n >= merged.LastRow) { removedIndices.Add(i); continue; } bool inStart = (merged.FirstRow >= startRow || merged.LastRow >= startRow); bool inEnd = (merged.FirstRow <= endRow || merged.LastRow <= endRow); //don't check if it's not within the Shifted area if (!inStart || !inEnd) { continue; } //only shift if the region outside the Shifted rows is not merged too if (!merged.ContainsRow(startRow - 1) && !merged.ContainsRow(endRow + 1)) { merged.FirstRow = (/*setter*/merged.FirstRow + n); merged.LastRow = (/*setter*/merged.LastRow + n); //have to Remove/add it back ShiftedRegions.Add(merged); removedIndices.Add(i); } } if (!(removedIndices.Count==0)/*.IsEmpty()*/) { sheet.RemoveMergedRegions(removedIndices.ToList()); } //read so it doesn't Get Shifted again foreach (CellRangeAddress region in ShiftedRegions) { sheet.AddMergedRegion(region); } return ShiftedRegions; } /** * Updated named ranges */ public abstract void UpdateNamedRanges(FormulaShifter Shifter); /** * Update formulas. */ public abstract void UpdateFormulas(FormulaShifter Shifter); /** * Update the formulas in specified row using the formula Shifting policy specified by Shifter * * @param row the row to update the formulas on * @param Shifter the formula Shifting policy */ public abstract void UpdateRowFormulas(IRow row, FormulaShifter Shifter); public abstract void UpdateConditionalFormatting(FormulaShifter Shifter); /** * Shift the Hyperlink anchors (not the hyperlink text, even if the hyperlink * is of type LINK_DOCUMENT and refers to a cell that was Shifted). Hyperlinks * do not track the content they point to. * * @param Shifter the formula Shifting policy */ public abstract void UpdateHyperlinks(FormulaShifter Shifter); } }
38.412214
157
0.582075
[ "Apache-2.0" ]
68681395/npoi
main/SS/UserModel/Helpers/RowShifter.cs
5,032
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.ActiveRecord.Tests { using System; using System.Data.SqlClient; using Castle.ActiveRecord.Framework; using Castle.ActiveRecord.Framework.Scopes; using Castle.ActiveRecord.Tests.Model; using Castle.Core.Configuration; using NHibernate; using NUnit.Framework; [TestFixture] public class DifferentDatabaseScopeTestCase : AbstractActiveRecordTest { [SetUp] public void Setup() { base.Init(); ActiveRecordStarter.Initialize( GetConfigSource(), typeof(Blog), typeof(Post), typeof(OtherDbBlog), typeof(OtherDbPost), typeof(Test2ARBase) ); Recreate(); } [Test, Category("mssql")] public void SimpleCase() { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); SqlConnection conn = CreateSqlConnection(); using(conn) { conn.Open(); using(new DifferentDatabaseScope(conn)) { blog.Create(); } } Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 1, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 1, blogs2.Length ); } [Test, Category("mssql")] public void UsingSessionScope() { ISession session1, session2; using(new SessionScope()) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session1 = blog.CurrentSession; Assert.IsNotNull(session1); SqlConnection conn = CreateSqlConnection(); using(conn) { conn.Open(); using(new DifferentDatabaseScope(conn)) { blog.Create(); session2 = blog.CurrentSession; Assert.IsNotNull(session2); Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); } } } Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 1, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 1, blogs2.Length ); } [Test, Category("mssql")] public void UsingTransactionScope() { SqlConnection conn = CreateSqlConnection(); ISession session1, session2; ITransaction trans1, trans2; using(new TransactionScope()) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session1 = blog.CurrentSession; trans1 = blog.CurrentSession.Transaction; Assert.IsNotNull(session1); Assert.IsNotNull(session1.Transaction); Assert.IsFalse(session1.Transaction.WasCommitted); Assert.IsFalse(session1.Transaction.WasRolledBack); conn.Open(); using(new DifferentDatabaseScope(conn)) { blog.Create(); session2 = blog.CurrentSession; trans2 = blog.CurrentSession.Transaction; Assert.IsNotNull(session2); Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(session2.Transaction); Assert.IsFalse(session2.Transaction.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); } } Assert.IsFalse(session1.IsOpen); Assert.IsFalse(session2.IsOpen); Assert.IsTrue(trans1.WasCommitted); Assert.IsFalse(trans1.WasRolledBack); Assert.IsTrue(trans2.WasCommitted); Assert.IsFalse(trans2.WasRolledBack); Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 1, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 1, blogs2.Length ); } [Test, Category("mssql")] public void UsingTransactionScopeWithRollback() { SqlConnection conn = CreateSqlConnection(); ISession session1, session2; ITransaction trans1, trans2; using(TransactionScope scope = new TransactionScope()) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session1 = blog.CurrentSession; trans1 = blog.CurrentSession.Transaction; Assert.IsNotNull(session1); Assert.IsNotNull(session1.Transaction); Assert.IsFalse(session1.Transaction.WasCommitted); Assert.IsFalse(session1.Transaction.WasRolledBack); conn.Open(); using(new DifferentDatabaseScope(conn)) { blog.Create(); session2 = blog.CurrentSession; trans2 = blog.CurrentSession.Transaction; Assert.IsNotNull(session2); Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(session2.Transaction); Assert.IsFalse(session2.Transaction.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); scope.VoteRollBack(); } } Assert.IsFalse(session1.IsOpen); Assert.IsFalse(session2.IsOpen); Assert.IsFalse(trans1.WasCommitted); Assert.IsTrue(trans1.WasRolledBack); Assert.IsFalse(trans2.WasCommitted); Assert.IsTrue(trans2.WasRolledBack); Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 0, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 0, blogs2.Length ); } [Test, Category("mssql")] public void MoreThanOneConnectionWithinTheSessionScope() { SqlConnection conn = CreateSqlConnection(); SqlConnection conn2 = CreateSqlConnection2(); using(new SessionScope()) { foreach(SqlConnection connection in new SqlConnection[] { conn, conn2 }) { connection.Open(); using(new DifferentDatabaseScope(connection)) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Create(); } } } OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 1, blogs2.Length ); Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 1, blogs.Length ); } [Test, Category("mssql")] public void UsingSessionAndTransactionScope() { SqlConnection conn = CreateSqlConnection(); ISession session1, session2; ITransaction trans1, trans2; using(new SessionScope()) { using(TransactionScope scope = new TransactionScope()) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session1 = blog.CurrentSession; Assert.IsNotNull(session1); trans1 = session1.Transaction; Assert.IsNotNull(trans1); Assert.IsFalse(trans1.WasCommitted); Assert.IsFalse(trans1.WasRolledBack); conn.Open(); using(new DifferentDatabaseScope(conn)) { blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session2 = blog.CurrentSession; Assert.IsNotNull(session2); trans2 = session2.Transaction; Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(session2.Transaction); Assert.IsFalse(session2.Transaction.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); } using(new DifferentDatabaseScope(conn)) { blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session2 = blog.CurrentSession; Assert.IsNotNull(session2); Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(session2.Transaction); Assert.IsFalse(session2.Transaction.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); } } } Assert.IsFalse(session1.IsOpen); Assert.IsFalse(session2.IsOpen); Assert.IsTrue(trans1.WasCommitted); Assert.IsFalse(trans1.WasRolledBack); Assert.IsTrue(trans2.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 1, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 2, blogs2.Length ); } [Test, Category("mssql")] public void SequenceOfTransactions() { SqlConnection conn = CreateSqlConnection(); ISession session1, session2; ITransaction trans1, trans2; using(new SessionScope()) { using(TransactionScope scope = new TransactionScope()) { Blog blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session1 = blog.CurrentSession; Assert.IsNotNull(session1); trans1 = session1.Transaction; Assert.IsNotNull(trans1); Assert.IsFalse(trans1.WasCommitted); Assert.IsFalse(trans1.WasRolledBack); conn.Open(); using(new DifferentDatabaseScope(conn)) { blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session2 = blog.CurrentSession; Assert.IsNotNull(session2); trans2 = session2.Transaction; Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(session2.Transaction); Assert.IsFalse(session2.Transaction.WasCommitted); Assert.IsFalse(session2.Transaction.WasRolledBack); } using(new DifferentDatabaseScope(conn)) { blog = new Blog(); blog.Name = "hammett's blog"; blog.Author = "hamilton verissimo"; blog.Save(); session2 = blog.CurrentSession; Assert.IsNotNull(session2); Assert.IsFalse( Object.ReferenceEquals(session1, session2) ); Assert.IsNotNull(trans2); Assert.IsFalse(trans2.WasCommitted); Assert.IsFalse(trans2.WasRolledBack); } } conn.Close(); using(TransactionScope scope = new TransactionScope()) { Blog blog = new Blog(); blog.Name = "another blog"; blog.Author = "erico verissimo"; blog.Save(); } } Assert.IsFalse(session1.IsOpen); Assert.IsFalse(session2.IsOpen); Assert.IsTrue(trans1.WasCommitted); Assert.IsFalse(trans1.WasRolledBack); Assert.IsTrue(trans2.WasCommitted); Assert.IsFalse(trans2.WasRolledBack); Blog[] blogs = Blog.FindAll(); Assert.IsNotNull( blogs ); Assert.AreEqual( 2, blogs.Length ); OtherDbBlog[] blogs2 = OtherDbBlog.FindAll(); Assert.IsNotNull( blogs2 ); Assert.AreEqual( 2, blogs2.Length ); } private SqlConnection CreateSqlConnection() { IConfigurationSource config = GetConfigSource(); IConfiguration db2 = config.GetConfiguration( typeof(Test2ARBase) ); SqlConnection conn = null; foreach(IConfiguration child in db2.Children) { if (child.Name == "connection.connection_string") { conn = new SqlConnection(child.Value); } } return conn; } private SqlConnection CreateSqlConnection2() { IConfigurationSource config = GetConfigSource(); IConfiguration db2 = config.GetConfiguration( typeof(ActiveRecordBase) ); SqlConnection conn = null; foreach(IConfiguration child in db2.Children) { if (child.Name == "connection.connection_string") { conn = new SqlConnection(child.Value); } } return conn; } } }
26.698482
77
0.652665
[ "Apache-2.0" ]
castleproject-deprecated/ActiveRecord
src/Castle.ActiveRecord.Tests/DifferentDatabaseScopeTestCase.cs
12,308
C#
namespace Simplic.DocumentProcessing { /// <summary> /// Barcode recognition result /// </summary> public class BarcodeRecognitionResult { /// <summary> /// Gets or sets the barcode /// </summary> public string Barcode { get; set; } /// <summary> /// Gets or sets the barcode type /// </summary> public string BarcodeType { get; set; } /// <summary> /// Gets or sets the page /// </summary> public int Page { get; set; } } }
23.791667
48
0.495622
[ "MIT" ]
simplic/simplic-document-processing
src/Simplic.DocumentProcessing/Barcode/BarcodeRecognitionResult.cs
573
C#
//this source code was auto-generated by tolua#, do not modify it using System; using LuaInterface; public class GameConstWrap { public static void Register(LuaState L) { L.BeginClass(typeof(GameConst), typeof(System.Object)); L.RegFunction("New", _CreateGameConst); L.RegFunction("__tostring", ToLua.op_ToString); L.RegVar("DebugMode", get_DebugMode, set_DebugMode); L.RegVar("LogMode", get_LogMode, set_LogMode); L.RegVar("UpdateMode", get_UpdateMode, set_UpdateMode); L.RegVar("LuaByteMode", get_LuaByteMode, set_LuaByteMode); L.RegVar("LuaBundleMode", get_LuaBundleMode, set_LuaBundleMode); L.RegConstant("TimerInterval", 1); L.RegConstant("GameFrameRate", 60); L.RegVar("GameName", get_GameName, null); L.RegVar("AssetsDir", get_AssetsDir, null); L.RegVar("BundleSuffix", get_BundleSuffix, null); L.RegVar("WebUrl", get_WebUrl, null); L.RegVar("VersionNumber", get_VersionNumber, null); L.RegVar("VersionBytes", get_VersionBytes, null); L.EndClass(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _CreateGameConst(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 0) { GameConst obj = new GameConst(); ToLua.PushObject(L, obj); return 1; } else { return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: GameConst.New"); } } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_DebugMode(IntPtr L) { try { LuaDLL.lua_pushboolean(L, GameConst.DebugMode); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_LogMode(IntPtr L) { try { LuaDLL.lua_pushboolean(L, GameConst.LogMode); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_UpdateMode(IntPtr L) { try { LuaDLL.lua_pushboolean(L, GameConst.UpdateMode); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_LuaByteMode(IntPtr L) { try { LuaDLL.lua_pushboolean(L, GameConst.LuaByteMode); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_LuaBundleMode(IntPtr L) { try { LuaDLL.lua_pushboolean(L, GameConst.LuaBundleMode); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_GameName(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.GameName); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_AssetsDir(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.AssetsDir); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_BundleSuffix(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.BundleSuffix); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_WebUrl(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.WebUrl); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_VersionNumber(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.VersionNumber); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_VersionBytes(IntPtr L) { try { LuaDLL.lua_pushstring(L, GameConst.VersionBytes); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_DebugMode(IntPtr L) { try { bool arg0 = LuaDLL.luaL_checkboolean(L, 2); GameConst.DebugMode = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_LogMode(IntPtr L) { try { bool arg0 = LuaDLL.luaL_checkboolean(L, 2); GameConst.LogMode = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_UpdateMode(IntPtr L) { try { bool arg0 = LuaDLL.luaL_checkboolean(L, 2); GameConst.UpdateMode = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_LuaByteMode(IntPtr L) { try { bool arg0 = LuaDLL.luaL_checkboolean(L, 2); GameConst.LuaByteMode = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_LuaBundleMode(IntPtr L) { try { bool arg0 = LuaDLL.luaL_checkboolean(L, 2); GameConst.LuaBundleMode = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } }
19.677305
83
0.695441
[ "MIT" ]
getker/Kerven_Client
Assets/ToLua/Source/Generate/GameConstWrap.cs
5,551
C#
using System; using System.Collections.Generic; namespace RDotNet { /// <summary> /// A special function. /// </summary> public class SpecialFunction : Function { /// <summary> /// Creates a special function proxy. /// </summary> /// <param name="engine">The engine.</param> /// <param name="pointer">The pointer.</param> protected internal SpecialFunction(REngine engine, IntPtr pointer) : base(engine, pointer) { } /// <summary> /// Invoke this special function, using an ordered list of unnamed arguments. /// </summary> /// <param name="args">The arguments of the function</param> /// <returns>The result of the evaluation</returns> public override SymbolicExpression Invoke(params SymbolicExpression[] args) { return InvokeOrderedArguments(args); } // Invoke this special function, using a list of named arguments in the form of a dictionary /// <summary> /// NotSupportedException /// </summary> /// <param name="args">key-value pairs</param> /// <returns>Always throws an exception</returns> public override SymbolicExpression Invoke(IDictionary<string, SymbolicExpression> args) { throw new NotSupportedException(); } } }
34.756098
101
0.584561
[ "MIT" ]
StatTag/rdotnet
R.NET/SpecialFunction.cs
1,427
C#
using Discord; using Discord.Commands; using NadekoBot.Commands; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; /* Voltana's legacy public class AsyncLazy<T> : Lazy<Task<T>> { public AsyncLazy(Func<T> valueFactory) : base(() => Task.Factory.StartNew(valueFactory)) { } public AsyncLazy(Func<Task<T>> taskFactory) : base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap()) { } public TaskAwaiter<T> GetAwaiter() { return Value.GetAwaiter(); } } */ namespace NadekoBot.Modules.Administration.Commands { internal class ServerGreetCommand : DiscordCommand { public static ConcurrentDictionary<ulong, AnnounceControls> AnnouncementsDictionary; public static long Greeted = 0; public ServerGreetCommand(DiscordModule module) : base(module) { AnnouncementsDictionary = new ConcurrentDictionary<ulong, AnnounceControls>(); NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserLeft += UserLeft; var data = Classes.DbHandler.Instance.GetAllRows<Classes._DataModels.Announcement>(); if (!data.Any()) return; foreach (var obj in data) AnnouncementsDictionary.TryAdd((ulong)obj.ServerId, new AnnounceControls(obj)); } private async void UserLeft(object sender, UserEventArgs e) { try { if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) || !AnnouncementsDictionary[e.Server.Id].Bye) return; var controls = AnnouncementsDictionary[e.Server.Id]; var channel = NadekoBot.Client.GetChannel(controls.ByeChannel); var msg = controls.ByeText.Replace("%user%", "**" + e.User.Name + "**").Trim(); if (string.IsNullOrEmpty(msg)) return; if (controls.ByePM) { Greeted++; try { await e.User.SendMessage($"`Farewell Message From {e.Server?.Name}`\n" + msg); } catch { } } else { if (channel == null) return; Greeted++; var toDelete = await channel.SendMessage(msg); if (e.Server.CurrentUser.GetPermissions(channel).ManageMessages) { await Task.Delay(300000); // 5 minutes await toDelete.Delete(); } } } catch { } } private async void UserJoined(object sender, Discord.UserEventArgs e) { try { if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) || !AnnouncementsDictionary[e.Server.Id].Greet) return; var controls = AnnouncementsDictionary[e.Server.Id]; var channel = NadekoBot.Client.GetChannel(controls.GreetChannel); var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim(); if (string.IsNullOrEmpty(msg)) return; if (controls.GreetPM) { Greeted++; await e.User.SendMessage($"`Welcome Message From {e.Server.Name}`\n" + msg); } else { if (channel == null) return; Greeted++; var toDelete = await channel.SendMessage(msg); if (e.Server.CurrentUser.GetPermissions(channel).ManageMessages) { await Task.Delay(300000); // 5 minutes await toDelete.Delete(); } } } catch { } } public class AnnounceControls { private Classes._DataModels.Announcement _model { get; } public bool Greet { get { return _model.Greet; } set { _model.Greet = value; Save(); } } public ulong GreetChannel { get { return (ulong)_model.GreetChannelId; } set { _model.GreetChannelId = (long)value; Save(); } } public bool GreetPM { get { return _model.GreetPM; } set { _model.GreetPM = value; Save(); } } public bool ByePM { get { return _model.ByePM; } set { _model.ByePM = value; Save(); } } public string GreetText { get { return _model.GreetText; } set { _model.GreetText = value; Save(); } } public bool Bye { get { return _model.Bye; } set { _model.Bye = value; Save(); } } public ulong ByeChannel { get { return (ulong)_model.ByeChannelId; } set { _model.ByeChannelId = (long)value; Save(); } } public string ByeText { get { return _model.ByeText; } set { _model.ByeText = value; Save(); } } public ulong ServerId { get { return (ulong)_model.ServerId; } set { _model.ServerId = (long)value; } } public AnnounceControls(Classes._DataModels.Announcement model) { this._model = model; } public AnnounceControls(ulong serverId) { this._model = new Classes._DataModels.Announcement(); ServerId = serverId; } internal bool ToggleBye(ulong id) { if (Bye) { return Bye = false; } else { ByeChannel = id; return Bye = true; } } internal bool ToggleGreet(ulong id) { if (Greet) { return Greet = false; } else { GreetChannel = id; return Greet = true; } } internal bool ToggleGreetPM() => GreetPM = !GreetPM; internal bool ToggleByePM() => ByePM = !ByePM; private void Save() { Classes.DbHandler.Instance.Save(_model); } } internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "greet") .Description("Enables or Disables anouncements on the current channel when someone joins the server.") .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var controls = AnnouncementsDictionary[e.Server.Id]; if (controls.ToggleGreet(e.Channel.Id)) await e.Channel.SendMessage("Greet announcements enabled on this channel."); else await e.Channel.SendMessage("Greet announcements disabled."); }); cgb.CreateCommand(Module.Prefix + "greetmsg") .Description("Sets a new announce message. Type %user% if you want to mention the new member.\n**Usage**: .greetmsg Welcome to the server, %user%.") .Parameter("msg", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (e.GetArg("msg") == null) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); AnnouncementsDictionary[e.Server.Id].GreetText = e.GetArg("msg"); await e.Channel.SendMessage("New greet message set."); if (!AnnouncementsDictionary[e.Server.Id].Greet) await e.Channel.SendMessage("Enable greet messsages by typing `.greet`"); }); cgb.CreateCommand(Module.Prefix + "bye") .Description("Enables or Disables anouncements on the current channel when someone leaves the server.") .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); var controls = AnnouncementsDictionary[e.Server.Id]; if (controls.ToggleBye(e.Channel.Id)) await e.Channel.SendMessage("Bye announcements enabled on this channel."); else await e.Channel.SendMessage("Bye announcements disabled."); }); cgb.CreateCommand(Module.Prefix + "byemsg") .Description("Sets a new announce leave message. Type %user% if you want to mention the new member.\n**Usage**: .byemsg %user% has left the server.") .Parameter("msg", ParameterType.Unparsed) .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (e.GetArg("msg") == null) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); AnnouncementsDictionary[e.Server.Id].ByeText = e.GetArg("msg"); await e.Channel.SendMessage("New bye message set."); if (!AnnouncementsDictionary[e.Server.Id].Bye) await e.Channel.SendMessage("Enable bye messsages by typing `.bye`."); }); cgb.CreateCommand(Module.Prefix + "byepm") .Description("Toggles whether the good bye messages will be sent in a PM or in the text channel.") .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); AnnouncementsDictionary[e.Server.Id].ToggleByePM(); if (AnnouncementsDictionary[e.Server.Id].ByePM) await e.Channel.SendMessage("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves."); else await e.Channel.SendMessage("Bye messages will be sent in a bound channel from now on."); if (!AnnouncementsDictionary[e.Server.Id].Bye) await e.Channel.SendMessage("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`"); }); cgb.CreateCommand(Module.Prefix + "greetpm") .Description("Toggles whether the greet messages will be sent in a PM or in the text channel.") .Do(async e => { if (!e.User.ServerPermissions.ManageServer) return; if (!AnnouncementsDictionary.ContainsKey(e.Server.Id)) AnnouncementsDictionary.TryAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); AnnouncementsDictionary[e.Server.Id].ToggleGreetPM(); if (AnnouncementsDictionary[e.Server.Id].GreetPM) await e.Channel.SendMessage("Greet messages will be sent in a PM from now on."); else await e.Channel.SendMessage("Greet messages will be sent in a bound channel from now on."); if (!AnnouncementsDictionary[e.Server.Id].Greet) await e.Channel.SendMessage("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`"); }); } } }
40.971061
205
0.515775
[ "MIT" ]
jjp47/nadeko02
NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs
12,746
C#
using UnityEngine; using System.Collections; public class Projectile : MonoBehaviour { public LayerMask collisionMask; public Color trailColour; float speed = 10; float damage = 1; float lifetime = 3; float skinWidth = .1f; void Start() { Destroy (gameObject, lifetime); Collider[] initialCollisions = Physics.OverlapSphere (transform.position, .1f, collisionMask); if (initialCollisions.Length > 0) { OnHitObject(initialCollisions[0], transform.position); } GetComponent<TrailRenderer> ().material.SetColor ("_TintColor", trailColour); } public void SetSpeed(float newSpeed) { speed = newSpeed; } void Update () { float moveDistance = speed * Time.deltaTime; CheckCollisions (moveDistance); transform.Translate (Vector3.forward * moveDistance); } void CheckCollisions(float moveDistance) { Ray ray = new Ray (transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, moveDistance + skinWidth, collisionMask, QueryTriggerInteraction.Collide)) { OnHitObject(hit.collider, hit.point); } } void OnHitObject(Collider c, Vector3 hitPoint) { IDamageable damageableObject = c.GetComponent<IDamageable> (); if (damageableObject != null) { damageableObject.TakeHit(damage, hitPoint, transform.forward); } GameObject.Destroy (gameObject); } }
25.692308
112
0.738024
[ "MIT" ]
kumakier/funzshooter
Assets/Script/Projectile.cs
1,338
C#
using System; namespace QIQO.Business.Client.Entities { public class Comment { public int CommentKey { get; set; } public int EntityKey { get; set; } public int EntityTypeKey { get; set; } public QIQOCommentType CommentType { get; set; } = QIQOCommentType.Public; public string CommentValue { get; set; } public string AddedUserID { get; set; } public DateTime AddedDateTime { get; set; } public string UpdateUserID { get; set; } public DateTime UpdateDateTime { get; set; } } }
33.117647
82
0.632327
[ "MIT" ]
rdrrichards/QIQO.Business.Client.Solution
QIQO.Business.Client.Entities/Classes/Comment.cs
563
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Horse.Messaging.Client; using Horse.Messaging.Protocol; using Horse.Messaging.Protocol.Models; using Horse.Messaging.Server.Clients; using Horse.Messaging.Server.Cluster; using Horse.Messaging.Server.Helpers; using Horse.Messaging.Server.Queues; using Horse.Messaging.Server.Routing; using Horse.Messaging.Server.Security; namespace Horse.Messaging.Server.Network { internal class ServerMessageHandler : INetworkMessageHandler { #region Fields /// <summary> /// Messaging Queue Server /// </summary> private readonly HorseRider _rider; public ServerMessageHandler(HorseRider rider) { _rider = rider; } #endregion #region Handle public async Task Handle(MessagingClient client, HorseMessage message, bool fromNode) { try { await HandleUnsafe(client, message); } catch (OperationCanceledException) { await client.SendAsync(message.CreateResponse(HorseResultCode.LimitExceeded)); } catch (DuplicateNameException) { await client.SendAsync(message.CreateResponse(HorseResultCode.Duplicate)); } } private Task HandleUnsafe(MessagingClient client, HorseMessage message) { switch (message.ContentType) { //subscribe to a queue case KnownContentTypes.QueueSubscribe: return Subscribe(client, message); //unsubscribe from a queue case KnownContentTypes.QueueUnsubscribe: return Unsubscribe(client, message); //get queue consumers case KnownContentTypes.QueueConsumers: return GetQueueConsumers(client, message); //creates new queue case KnownContentTypes.CreateQueue: return CreateQueue(client, message); //remove only queue case KnownContentTypes.RemoveQueue: return RemoveQueue(client, message); //update queue case KnownContentTypes.UpdateQueue: return UpdateQueue(client, message); //clear messages in queue case KnownContentTypes.ClearMessages: return ClearMessages(client, message); //get queue information list case KnownContentTypes.QueueList: return GetQueueList(client, message); //get queue information case KnownContentTypes.NodeList: return GetNodeList(client, message); //get client information list case KnownContentTypes.ClientList: return GetClients(client, message); //lists all routers case KnownContentTypes.ListRouters: return ListRouters(client, message); //creates new router case KnownContentTypes.CreateRouter: return CreateRouter(client, message); //removes a router case KnownContentTypes.RemoveRouter: return RemoveRouter(client, message); //lists all bindings of a router case KnownContentTypes.ListBindings: return ListRouterBindings(client, message); //adds new binding to a router case KnownContentTypes.AddBinding: return CreateRouterBinding(client, message); //removes a binding from a router case KnownContentTypes.RemoveBinding: return RemoveRouterBinding(client, message); //for not-defines content types, use user-defined message handler default: foreach (IServerMessageHandler handler in _rider.ServerMessageHandlers.All()) return handler.Received(client, message); return Task.CompletedTask; } } #endregion #region Queue /// <summary> /// Finds and subscribes to the queue and sends response /// </summary> private async Task Subscribe(MessagingClient client, HorseMessage message) { HorseQueue queue = _rider.Queue.Find(message.Target); //if auto creation active, try to create queue if (queue == null && _rider.Queue.Options.AutoQueueCreation) { QueueOptions options = QueueOptions.CloneFrom(_rider.Queue.Options); queue = await _rider.Queue.Create(message.Target, options, message, true, true, client); } if (queue == null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } QueueClient found = queue.FindClient(client.UniqueId); if (found != null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); return; } SubscriptionResult result = await queue.AddClient(client); if (message.WaitResponse) { switch (result) { case SubscriptionResult.Success: await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); break; case SubscriptionResult.Unauthorized: await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); break; case SubscriptionResult.Full: await client.SendAsync(message.CreateResponse(HorseResultCode.LimitExceeded)); break; } } } /// <summary> /// Unsubscribes from the queue and sends response /// </summary> private async Task Unsubscribe(MessagingClient client, HorseMessage message) { HorseQueue queue = _rider.Queue.Find(message.Target); if (queue == null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } bool success = queue.RemoveClient(client); if (message.WaitResponse) await client.SendAsync(message.CreateResponse(success ? HorseResultCode.Ok : HorseResultCode.NotFound)); } /// <summary> /// Gets active consumers of the queue /// </summary> public async Task GetQueueConsumers(MessagingClient client, HorseMessage message) { HorseQueue queue = _rider.Queue.Find(message.Target); if (queue == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanReceiveQueueConsumers(client, queue); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } List<ClientInformation> list = new List<ClientInformation>(); foreach (QueueClient cc in queue.ClientsClone) list.Add(new ClientInformation { Id = cc.Client.UniqueId, Name = cc.Client.Name, Type = cc.Client.Type, IsAuthenticated = cc.Client.IsAuthenticated, Online = cc.JoinDate.LifetimeMilliseconds(), }); HorseMessage response = message.CreateResponse(HorseResultCode.Ok); message.ContentType = KnownContentTypes.QueueConsumers; response.Serialize(list, _rider.MessageContentSerializer); await client.SendAsync(response); } /// <summary> /// Creates new queue and sends response /// </summary> private async Task CreateQueue(MessagingClient client, HorseMessage message) { NetworkOptionsBuilder builder = null; if (message.Length > 0) builder = await System.Text.Json.JsonSerializer.DeserializeAsync<NetworkOptionsBuilder>(message.Content); HorseQueue queue = _rider.Queue.Find(message.Target); //if queue exists, we can't create. return duplicate response. if (queue != null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Duplicate)); return; } //check authority if client can create queue foreach (IClientAuthorization authorization in _rider.Client.Authorizations.All()) { bool grant = await authorization.CanCreateQueue(client, message.Target, builder); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } //creates new queue QueueOptions options = QueueOptions.CloneFrom(_rider.Queue.Options); if (builder != null) builder.ApplyToQueue(options); queue = await _rider.Queue.Create(message.Target, options, message, true, false, client); //if creation successful, sends response if (message.WaitResponse) { if (queue != null) await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); else await client.SendAsync(message.CreateResponse(HorseResultCode.Failed)); } } /// <summary> /// Removes a queue from a server /// </summary> private async Task RemoveQueue(MessagingClient client, HorseMessage message) { HorseQueue queue = _rider.Queue.Find(message.Target); if (queue == null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanRemoveQueue(client, queue); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } await _rider.Queue.Remove(queue); if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Creates new queue and sends response /// </summary> private async Task UpdateQueue(MessagingClient client, HorseMessage message) { NetworkOptionsBuilder builder = await System.Text.Json.JsonSerializer.DeserializeAsync<NetworkOptionsBuilder>(message.Content); HorseQueue queue = _rider.Queue.Find(message.Target); if (queue == null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanUpdateQueueOptions(client, queue, builder); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } builder.Type = null; builder.ApplyToQueue(queue.Options); //if creation successful, sends response if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); _rider.Cluster.SendQueueUpdated(queue); } /// <summary> /// Clears messages in a queue /// </summary> private async Task ClearMessages(MessagingClient client, HorseMessage message) { HorseQueue queue = _rider.Queue.Find(message.Target); if (queue == null) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } string prio = message.FindHeader(HorseHeaders.PRIORITY_MESSAGES); string msgs = message.FindHeader(HorseHeaders.MESSAGES); bool clearPrio = !string.IsNullOrEmpty(prio) && prio.Equals("yes", StringComparison.InvariantCultureIgnoreCase); bool clearMsgs = !string.IsNullOrEmpty(msgs) && msgs.Equals("yes", StringComparison.InvariantCultureIgnoreCase); foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanClearQueueMessages(client, queue, clearPrio, clearMsgs); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } if (clearPrio && clearMsgs) { await queue.Manager.PriorityMessageStore.Clear(); await queue.Manager.MessageStore.Clear(); } else if (clearPrio) await queue.Manager.PriorityMessageStore.Clear(); else if (clearMsgs) await queue.Manager.MessageStore.Clear(); //if creation successful, sends response if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Finds all queues in the server /// </summary> private async Task GetQueueList(MessagingClient client, HorseMessage message) { foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanReceiveQueues(client); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } List<QueueInformation> list = new List<QueueInformation>(); foreach (HorseQueue queue in _rider.Queue.Queues) { if (queue == null) continue; string ack = "none"; if (queue.Options.Acknowledge == QueueAckDecision.JustRequest) ack = "just"; else if (queue.Options.Acknowledge == QueueAckDecision.WaitForAcknowledge) ack = "wait"; list.Add(new QueueInformation { Name = queue.Name, Topic = queue.Topic, Status = queue.Status.ToString().Trim().ToLower(), PriorityMessages = queue.Manager.PriorityMessageStore.Count(), Messages = queue.Manager.MessageStore.Count(), ProcessingMessages = queue.ClientsClone.Count(x => x.CurrentlyProcessing != null), DeliveryTrackingMessags = queue.Manager.DeliveryHandler.Tracker.GetDeliveryCount(), Acknowledge = ack, AcknowledgeTimeout = Convert.ToInt32(queue.Options.AcknowledgeTimeout.TotalMilliseconds), MessageTimeout = Convert.ToInt32(queue.Options.MessageTimeout.TotalMilliseconds), ReceivedMessages = queue.Info.ReceivedMessages, SentMessages = queue.Info.SentMessages, Deliveries = queue.Info.Deliveries, NegativeAcks = queue.Info.NegativeAcknowledge, Acks = queue.Info.Acknowledges, TimeoutMessages = queue.Info.TimedOutMessages, SavedMessages = queue.Info.MessageSaved, RemovedMessages = queue.Info.MessageRemoved, Errors = queue.Info.ErrorCount, LastMessageReceived = queue.Info.GetLastMessageReceiveUnix(), LastMessageSent = queue.Info.GetLastMessageSendUnix(), MessageLimit = queue.Options.MessageLimit, MessageSizeLimit = queue.Options.MessageSizeLimit, DelayBetweenMessages = queue.Options.DelayBetweenMessages }); } HorseMessage response = message.CreateResponse(HorseResultCode.Ok); message.ContentType = KnownContentTypes.QueueList; response.Serialize(list, _rider.MessageContentSerializer); await client.SendAsync(response); } #endregion #region Instance /// <summary> /// Gets connected instance list /// </summary> private async Task GetNodeList(MessagingClient client, HorseMessage message) { foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanManageInstances(client, message); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } List<NodeInformation> list = new List<NodeInformation>(); //outgoing nodes foreach (NodeClient node in _rider.Cluster.Clients) { string state = NodeState.Replica.ToString(); if (node.Info.Id == _rider.Cluster.MainNode?.Id) state = NodeState.Main.ToString(); else if (node.Info.Id == _rider.Cluster.SuccessorNode?.Id) state = NodeState.Successor.ToString(); list.Add(new NodeInformation { Id = node.Info.Id, Name = node.Info.Name, Host = node.Info.Host, PublicHost = node.Info.PublicHost, State = state, IsConnected = node.IsConnected, Lifetime = Convert.ToInt64((DateTime.UtcNow - node.ConnectedDate).TotalMilliseconds) }); } HorseMessage response = message.CreateResponse(HorseResultCode.Ok); message.ContentType = KnownContentTypes.NodeList; response.Serialize(list, _rider.MessageContentSerializer); await client.SendAsync(response); } #endregion #region Client /// <summary> /// Gets all connected clients /// </summary> public async Task GetClients(MessagingClient client, HorseMessage message) { foreach (IAdminAuthorization authorization in _rider.Client.AdminAuthorizations.All()) { bool grant = await authorization.CanReceiveClients(client); if (!grant) { if (message.WaitResponse) await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } List<ClientInformation> list = new List<ClientInformation>(); string filter = null; if (!string.IsNullOrEmpty(message.Target)) filter = message.Target; foreach (MessagingClient mc in _rider.Client.Clients) { if (!string.IsNullOrEmpty(filter)) { if (string.IsNullOrEmpty(mc.Type) || !Filter.CheckMatch(mc.Type, filter)) continue; } list.Add(new ClientInformation { Id = mc.UniqueId, Name = mc.Name, Type = mc.Type, IsAuthenticated = mc.IsAuthenticated, Online = mc.ConnectedDate.LifetimeMilliseconds(), }); } HorseMessage response = message.CreateResponse(HorseResultCode.Ok); response.ContentType = KnownContentTypes.ClientList; response.Serialize(list, _rider.MessageContentSerializer); await client.SendAsync(response); } #endregion #region Router /// <summary> /// Creates new router /// </summary> private async Task CreateRouter(MessagingClient client, HorseMessage message) { IRouter found = _rider.Router.Find(message.Target); if (found != null) { await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); return; } string methodHeader = message.FindHeader(HorseHeaders.ROUTE_METHOD); RouteMethod method = RouteMethod.Distribute; if (!string.IsNullOrEmpty(methodHeader)) method = (RouteMethod) Convert.ToInt32(methodHeader); //check create queue access foreach (IClientAuthorization authorization in _rider.Client.Authorizations.All()) { bool grant = await authorization.CanCreateRouter(client, message.Target, method); if (!grant) { await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } _rider.Router.Add(message.Target, method); await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Removes a router with it's bindings /// </summary> private async Task RemoveRouter(MessagingClient client, HorseMessage message) { IRouter found = _rider.Router.Find(message.Target); if (found == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); return; } //check create queue access foreach (IClientAuthorization authorization in _rider.Client.Authorizations.All()) { bool grant = await authorization.CanRemoveRouter(client, found); if (!grant) { await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } _rider.Router.Remove(found); await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Sends all routers /// </summary> private async Task ListRouters(MessagingClient client, HorseMessage message) { List<RouterInformation> items = new List<RouterInformation>(); foreach (IRouter router in _rider.Router.Routers) { RouterInformation info = new RouterInformation { Name = router.Name, IsEnabled = router.IsEnabled }; if (router is Router r) info.Method = r.Method; items.Add(info); } HorseMessage response = message.CreateResponse(HorseResultCode.Ok); response.Serialize(items, new NewtonsoftContentSerializer()); await client.SendAsync(response); } /// <summary> /// Creates new binding for a router /// </summary> private async Task CreateRouterBinding(MessagingClient client, HorseMessage message) { IRouter router = _rider.Router.Find(message.Target); if (router == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } BindingInformation info = message.Deserialize<BindingInformation>(new NewtonsoftContentSerializer()); //check create queue access foreach (IClientAuthorization authorization in _rider.Client.Authorizations.All()) { bool grant = await authorization.CanCreateBinding(client, router, info); if (!grant) { await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } switch (info.BindingType) { case BindingType.Direct: router.AddBinding(new DirectBinding(info.Name, info.Target, info.ContentType, info.Priority, info.Interaction, info.Method)); break; case BindingType.Queue: router.AddBinding(new QueueBinding(info.Name, info.Target, info.Priority, info.Interaction)); break; case BindingType.Http: router.AddBinding(new HttpBinding(info.Name, info.Target, (HttpBindingMethod) (info.ContentType ?? 0), info.Priority, info.Interaction)); break; case BindingType.Topic: router.AddBinding(new TopicBinding(info.Name, info.Target, info.ContentType ?? 0, info.Priority, info.Interaction, info.Method)); break; } await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Removes a router with it's bindings /// </summary> private async Task RemoveRouterBinding(MessagingClient client, HorseMessage message) { IRouter router = _rider.Router.Find(message.Target); if (router == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } string name = message.FindHeader(HorseHeaders.BINDING_NAME); if (string.IsNullOrEmpty(name)) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } Binding[] bindings = router.GetBindings(); Binding binding = bindings.FirstOrDefault(x => x.Name == name); if (binding == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } //check create queue access foreach (IClientAuthorization authorization in _rider.Client.Authorizations.All()) { bool grant = await authorization.CanRemoveBinding(client, binding); if (!grant) { await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } router.RemoveBinding(binding); await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); } /// <summary> /// Sends all bindings of a router /// </summary> private async Task ListRouterBindings(MessagingClient client, HorseMessage message) { IRouter router = _rider.Router.Find(message.Target); if (router == null) { await client.SendAsync(message.CreateResponse(HorseResultCode.NotFound)); return; } List<BindingInformation> items = new List<BindingInformation>(); foreach (Binding binding in router.GetBindings()) { BindingInformation info = new BindingInformation { Name = binding.Name, Target = binding.Target, Priority = binding.Priority, ContentType = binding.ContentType, Interaction = binding.Interaction }; if (binding is QueueBinding) info.BindingType = BindingType.Queue; else if (binding is DirectBinding directBinding) { info.Method = directBinding.RouteMethod; info.BindingType = BindingType.Direct; } else if (binding is TopicBinding topicBinding) { info.Method = topicBinding.RouteMethod; info.BindingType = BindingType.Topic; } else if (binding is HttpBinding) info.BindingType = BindingType.Http; items.Add(info); } HorseMessage response = message.CreateResponse(HorseResultCode.Ok); response.Serialize(items, new NewtonsoftContentSerializer()); await client.SendAsync(response); } #endregion } }
37.899128
157
0.553051
[ "Apache-2.0" ]
horse-framework/horse-mq
src/Horse.Messaging.Server/Network/ServerMessageHandler.cs
30,433
C#
using System.Buffers.Binary; namespace CSPDC { public partial class ByteManager { public int ReadBytesvarint() { int result = 0; int numRead = 0; byte read; do { Enforce(1); read = ReadByte(); int value = ((byte)read & 0b01111111); result |= (value << (7 * numRead)); numRead++; if (numRead > 5) throw new FieldOverflowException("varint too long"); } while ((read & 0b10000000) != 0); return result; } public void WriteBytesvarint(int Value) { byte[] data = new byte[5]; byte length = 0; uint workingValue = (uint)Value; do { byte temp = (byte)(workingValue & 0b01111111); workingValue >>= 7; if (workingValue != 0) { temp |= 0b10000000; } data[length] = temp; length++; } while (workingValue != 0); byte[] return_data = new byte[length]; for (byte i = 0; i < length; i++) { return_data[i] = data[i]; } WriteBytes(data); } } }
26.384615
72
0.405977
[ "MIT" ]
alice-cash/CSPDC
CSPDC/varint.cs
1,374
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using VRTK; public class VR_ControllerMovementForce : MonoBehaviour { private Vector3 lastPos; private Vector3 velocity; private HashSet<Rigidbody> hits = new HashSet<Rigidbody>(); private void Update() { var pos = transform.position; velocity = (pos - lastPos) / Time.deltaTime; lastPos = pos; foreach (var rb in hits) { //Debug.Log(rb + " added force " + velocity + " : frame " + Time.frameCount, rb); if (rb == null) continue; rb.AddForce(Vector3.ClampMagnitude(velocity * 0.1f, 20), ForceMode.Impulse); } hits.Clear(); } private void OnTriggerEnter(Collider other) { if (other.GetComponentInParent<VRTK_PlayerObject>() != null) return; var rb = other.GetComponentInParent<Rigidbody>(); if (rb != null) { //rb.AddForce(Vector3.ClampMagnitude(velocity * 0.1f, 20)); hits.Add(rb); } } }
26.047619
93
0.585009
[ "CC0-1.0", "MIT" ]
Soludus/Soludus2Enercity
Assets/Soludus/VR Game/Common/VRTK Extensions/VR_ControllerMovementForce.cs
1,096
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Collections; using System.Runtime.InteropServices; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Teste { public class StateMenu : ClientState { public Texture2D capaTexture; public Texture2D titleTexture; public StateMenu(Game1 game1) : base(game1) { capaTexture = game.Content.Load<Texture2D>("bg1"); titleTexture = game.Content.Load<Texture2D>("logo1ok"); } public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(capaTexture, new Rectangle(0, 0, game.GraphicsDevice.PresentationParameters.BackBufferWidth / 2, game.GraphicsDevice.PresentationParameters.BackBufferHeight / 2), Color.White); } public override void AfterDraw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw(titleTexture, new Vector2(game.GraphicsDevice.PresentationParameters.BackBufferWidth - 300, 10), Color.White); } public override void Update(GameTime gameTime) { } } }
33.543478
141
0.659754
[ "Apache-2.0" ]
juniortarcisio/Failed-MMO-Server-Client-XNA
MMO_XNA/GameStates/StateMenu.cs
1,545
C#
 using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace Framework.Shared.UI.Windows.Dialogs { public class DialogWindowEvents : MonoBehaviour { [SerializeField] private Button ok; [SerializeField] private Button cancel; public event UnityAction OkSelected { add => ok.onClick.AddListener(value); remove => ok.onClick.RemoveListener(value); } public event UnityAction CancelSelected { add => cancel.onClick.AddListener(value); remove => cancel.onClick.RemoveListener(value); } } }
26.166667
59
0.636943
[ "MIT" ]
sipasi/DurakCardsGame
Assets/Code/Shared/UI/Windows/Dialogs/DialogWindowEvents.cs
630
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DanpheEMR.ServerModel.InventoryModels.InventoryReportModel { public class ReturnToVendorItems { public DateTime ReturnDate { get; set; } public string VendorName { get; set; } public string ItemName { get; set; } public string BatchNo { get; set; } public int GoodsReceiptNo { get; set; } public Nullable<double> Quantity { get; set; } public Nullable<decimal> ItemRate { get; set; } public Nullable<int> CreditNoteNo { get; set; } public Nullable<decimal> DiscountAmount { get; set; } public Nullable<decimal> VAT { get; set; } public Nullable<decimal> TotalAmount { get; set; } public string Remark { get; set; } } }
34.24
68
0.658879
[ "MIT" ]
MenkaChaugule/hospital-management-emr
Code/Components/DanpheEMR.ServerModel/InventoryModels/InventoryReportModel/ReturnToVendorItemsModel.cs
858
C#
using System.Threading.Tasks; using RedPipes.Configuration.Visualization; namespace RedPipes.Configuration { /// <summary> provides the execute func extensions </summary> public static class Execute { /// <summary> /// Adds the <paramref name="execute"/> delegate in the pipeline /// and unconditionally executes the next pipe /// </summary> public static IBuilder<TIn, TOut> Use<TIn, TOut>(this IBuilder<TIn, TOut> builder, Pipe.Execute<TOut> execute, string? name = null) { return builder.Use(next => new Pipe<TOut>((ctx, value) => { execute(ctx, value); return Task.CompletedTask; }, next, name), name); } /// <summary> /// Adds the <paramref name="executeAsyncAsync"/> delegate in the pipeline /// and unconditionally executes the next pipe /// </summary> public static IBuilder<TIn, TOut> UseAsync<TIn, TOut>(this IBuilder<TIn, TOut> builder, Pipe.ExecuteAsync<TOut> executeAsyncAsync, string? name = null) { return builder.Use(next => new Pipe<TOut>(executeAsyncAsync, next, name), name); } internal class Pipe<T> : IPipe<T> { private readonly Pipe.ExecuteAsync<T> _executeAsync; private readonly IPipe<T> _next; private readonly string _name; public Pipe(Pipe.ExecuteAsync<T> executeAsync, IPipe<T> next, string? name) { _executeAsync = executeAsync; _next = next; _name = name?? GenerateName(); } public async Task Execute(IContext ctx, T value) { await _executeAsync(ctx, value).ConfigureAwait(false); await _next.Execute(ctx, value).ConfigureAwait(false); } public void Accept(IGraphBuilder<IPipe> visitor) { visitor.GetOrAddNode(this, (Keys.Name, _name)); if (visitor.AddEdge(this, _next, (Keys.Name, "Next"))) _next.Accept(visitor); } private static string GenerateName() { return $"Execute ({nameof(IContext)} ctx, {typeof(T).GetCSharpName()} value) => {{ ... }}"; } } } }
36.230769
159
0.55966
[ "MIT" ]
resc/redpipes
src/RedPipes/Configuration/Execute.cs
2,357
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 devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DeviceFarm.Model { /// <summary> /// Container for the parameters to the ListOfferingPromotions operation. /// Returns a list of offering promotions. Each offering promotion record contains the /// ID and description of the promotion. The API returns a <code>NotEligible</code> error /// if the caller is not permitted to invoke the operation. Contact <a href="mailto:aws-devicefarm-support@amazon.com">aws-devicefarm-support@amazon.com</a> /// if you believe that you should be able to invoke this operation. /// </summary> public partial class ListOfferingPromotionsRequest : AmazonDeviceFarmRequest { private string _nextToken; /// <summary> /// Gets and sets the property NextToken. /// <para> /// An identifier that was returned from the previous call to this operation, which can /// be used to return the next set of items in the list. /// </para> /// </summary> [AWSProperty(Min=4, Max=1024)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
35.645161
160
0.677376
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/ListOfferingPromotionsRequest.cs
2,210
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BugTracker_API.Models { interface IUser { public int Id { get; set; } public string Username { get; set; } } }
17.714286
44
0.669355
[ "Unlicense" ]
VygandasEidukis/Bug_Tracker_API
BugTracker_API/Models/IUser.cs
250
C#
 using Core.Features.Playlists.Commands; using Core.Features.Playlists.Queries; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Api.Controllers; public class PlaylistsController : BaseController { /*[HttpGet("Global")] public async Task<IActionResult> GetGlobalPlaylists() { }}*/ [HttpGet("GetByGuildId")] public async Task<IActionResult> GetGuildPlaylists(Guid guildId, bool ignoreGlobal = false) { return Ok(await Mediator.Send(new GetPlaylistsQuery(guildId, ignoreGlobal))); } [HttpGet("GetByName")] public async Task<IActionResult> GetByName(string name, Guid guildId) { return Ok(await Mediator.Send(new GetPlaylistByNameQuery(name, guildId))); } [HttpPost("Add")] public async Task<IActionResult> Add(AddPlaylistCommand command) { return Ok(await Mediator.Send(command)); } [HttpPost("AddSubreddit")] public async Task<IActionResult> AddSubreddit(AddSubredditToPlaylistCommand command) { return Ok(await Mediator.Send(command)); } [HttpDelete("Remove")] public async Task<IActionResult> Remove(RemovePlaylistCommand command) { return Ok(await Mediator.Send(command)); } [HttpDelete("RemoveSubreddit")] public async Task<IActionResult> RemoveSubreddit(RemovePlaylistSubredditCommand command) { return Ok(await Mediator.Send(command)); } }
26.796296
95
0.70076
[ "MIT" ]
bartblokhuis/UltimateRedditBot
api/src/Api/Controllers/PlaylistsController.cs
1,449
C#
using RPG.Data.Context; using RPG.Domain.Dto.Character; using RPG.Domain.DTO.Weapon; using RPG.Domain.Response; using System; using System.Threading.Tasks; namespace RPG.Data.Repository.WeaponRepository { public class WeaponRepository : IWeaponRepository { private readonly DataContext _dataContext; public WeaponRepository(DataContext dataContext) { _dataContext = dataContext; } public Task<ServiceResponse<GetCharacterDto>> AddWeapon(AddWeaponDto newWeapon) { throw new NotImplementedException(); } } }
24.08
87
0.694352
[ "MIT" ]
HusseinShukri/DotNET-RPG
RPG/RPG.DB/Repository/WeaponRepository/.vshistory/WeaponRepository.cs/2021-08-20_21_56_40_760.cs
604
C#
/// <summary> /// Copyright 2010 Neuroph Project http://neuroph.sourceforge.net /// /// 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. /// </summary> namespace org.neuroph.nnet { using Layer = org.neuroph.core.Layer; using org.neuroph.core; using InstarLearning = org.neuroph.nnet.learning.InstarLearning; using ConnectionFactory = org.neuroph.util.ConnectionFactory; using LayerFactory = org.neuroph.util.LayerFactory; using NeuralNetworkFactory = org.neuroph.util.NeuralNetworkFactory; using NeuralNetworkType = org.neuroph.util.NeuralNetworkType; using NeuronProperties = org.neuroph.util.NeuronProperties; using TransferFunctionType = org.neuroph.util.TransferFunctionType; /// <summary> /// Instar neural network with Instar learning rule. /// @author Zoran Sevarac <sevarac@gmail.com> /// </summary> public class Instar : NeuralNetwork { /// <summary> /// The class fingerprint that is set to indicate serialization /// compatibility with a previous version of the class. /// </summary> private const long serialVersionUID = 1L; /// <summary> /// Creates new Instar with specified number of input neurons. /// </summary> /// <param name="inputNeuronsCount"> /// number of neurons in input layer </param> public Instar(int inputNeuronsCount) { this.createNetwork(inputNeuronsCount); } /// <summary> /// Creates Instar architecture with specified number of input neurons /// </summary> /// <param name="inputNeuronsCount"> /// number of neurons in input layer </param> private void createNetwork(int inputNeuronsCount) { // set network type this.NetworkType = NeuralNetworkType.INSTAR; // init neuron settings for this type of network NeuronProperties neuronProperties = new NeuronProperties(); neuronProperties.setProperty("transferFunction", TransferFunctionType.Step.ToString()); // create input layer Layer inputLayer = LayerFactory.createLayer(inputNeuronsCount, neuronProperties); this.addLayer(inputLayer); // createLayer output layer neuronProperties.setProperty("transferFunction", TransferFunctionType.Step.ToString()); Layer outputLayer = LayerFactory.createLayer(1, neuronProperties); this.addLayer(outputLayer); // create full conectivity between input and output layer ConnectionFactory.fullConnect(inputLayer, outputLayer); // set input and output cells for this network NeuralNetworkFactory.DefaultIO = this; // set appropriate learning rule for this network this.LearningRule = new InstarLearning(); } } }
34.786517
90
0.738372
[ "Apache-2.0" ]
starhash/Neuroph.NET
Neuroph/nnet/Instar.cs
3,098
C#
using AccountingNote.ORM.DBModels; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AccountingNote.DBSource { public class UserInfoManger { //public static DataRow GetUserInfoByAccount(string account) //{ // string connectionString = DBHelper.GetConnectionString(); // string dbCommandString = // @"SELECT [ID], [Account],[PWD],[Name],[Email] // FROM UserInfo // WHERE [Account] = @account // "; // List<SqlParameter> list = new List<SqlParameter>(); // list.Add(new SqlParameter("@account", account)); // try // { // return DBHelper.ReadDataRow(connectionString, dbCommandString, list); // } // catch (Exception ex) // { // Logger.WriteLog(ex); // return null; // } //} public static UserInfo GetUserInfoByAccount(string account) { try { using (ContextModel context = new ContextModel()) { var query = (from item in context.UserInfoes where item.Account == account select item); var obj = query.FirstOrDefault(); return obj; } } catch (Exception ex) { Logger.WriteLog(ex); return null; } } } }
26.692308
87
0.485879
[ "MIT" ]
who000238/WebformMiniSample
WebformMiniSample/AccountingNote.DBSource/UserInfoManger.cs
1,737
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("AgarServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AgarServer")] [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("fd025558-5c2e-444c-8761-b42cbb4c5a2a")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.583333
84
0.747967
[ "MIT" ]
wIksS/AgarOnline
AgarServer/AgarServer/Properties/AssemblyInfo.cs
1,356
C#
using EasyLOB.Identity; using EasyLOB.Identity.Application; using EasyLOB.Identity.Persistence; using EasyLOB.Security; using System.Security.Principal; using System.Threading; using Unity; using Unity.Injection; namespace EasyLOB { public static partial class AppDIUnityHelper { public static void SetupIdentity() { Container.RegisterType(typeof(IAuthenticationManager), typeof(AuthenticationManagerMock), AppLifetimeManager); //Container.RegisterType(typeof(IAuthenticationManager), typeof(AuthenticationManager), AppLifetimeManager); Container.RegisterType(typeof(IIdentityGenericApplication<>), typeof(IdentityGenericApplication<>), AppLifetimeManager); Container.RegisterType(typeof(IIdentityGenericApplicationDTO<,>), typeof(IdentityGenericApplicationDTO<,>), AppLifetimeManager); // Entity Framework Container.RegisterType(typeof(IIdentityUnitOfWork), typeof(IdentityUnitOfWorkEF), AppLifetimeManager); Container.RegisterType(typeof(IIdentityGenericRepository<>), typeof(IdentityGenericRepositoryEF<>), AppLifetimeManager); // NHibernate //Container.RegisterType(typeof(IIdentityUnitOfWork), typeof(IdentityUnitOfWorkNH), AppLifetimeManager); //Container.RegisterType(typeof(IIdentityGenericRepository<>), typeof(IdentityGenericRepositoryNH<>), AppLifetimeManager); } } }
47.387097
141
0.737236
[ "MIT" ]
EasyLOB/EasyLOB-Chinook-2
Chinook.Shell/EasyLOB/DIUnity/AppDIUnityHelperIdentity.cs
1,471
C#
using System; namespace FuelSDK { /// <summary> /// ETTriggeredSendDefinition - Defines a triggered send in the account. /// </summary> public class ETTriggeredSendDefinition : TriggeredSendDefinition { /// <summary> /// Gets or sets the folder identifier. /// </summary> /// <value>The folder identifier.</value> public int? FolderID { get; set; } internal string FolderMediaType = "triggered_send"; /// <summary> /// Gets or sets the subscribers. /// </summary> /// <value>The subscribers.</value> public ETSubscriber[] Subscribers { get; set; } /// <summary> /// Send this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.SendReturn"/></returns> public SendReturn Send() { var ts = new ETTriggerSend { CustomerKey = CustomerKey, TriggeredSendDefinition = this, Subscribers = Subscribers, AuthStub = AuthStub, }; ((ETTriggeredSendDefinition)ts.TriggeredSendDefinition).Subscribers = null; return new SendReturn(ts); } /// <summary> /// Post this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.PostReturn"/> object.</returns> public PostReturn Post() { return new PostReturn(this); } /// <summary> /// Patch this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.PatchReturn"/> object..</returns> public PatchReturn Patch() { return new PatchReturn(this); } /// <summary> /// Delete this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.DeleteReturn"/> object..</returns> public DeleteReturn Delete() { return new DeleteReturn(this); } /// <summary> /// Get this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.GetReturn"/> object..</returns> public GetReturn Get() { var r = new GetReturn(this); LastRequestID = r.RequestID; return r; } /// <summary> /// Gets the more results. /// </summary> /// <returns>The <see cref="T:FuelSDK.GetReturn"/> object..</returns> public GetReturn GetMoreResults() { var r = new GetReturn(this, true, null); LastRequestID = r.RequestID; return r; } /// <summary> /// Info of this instance. /// </summary> /// <returns>The <see cref="T:FuelSDK.InfoReturn"/> object..</returns> public InfoReturn Info() { return new InfoReturn(this); } } [Obsolete("ET_TriggeredSend will be removed in future release. Please use ETTriggeredSendDefinition instead.")] public class ET_TriggeredSend : ETTriggeredSendDefinition { } }
34.378378
119
0.642689
[ "MIT" ]
DM-Francis/FuelSDK-CSharp
FuelSDK-CSharp/ETTriggeredSendDefinition.cs
2,546
C#
namespace TcpServerTestEcho { partial class FormServer { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.btnClear = new System.Windows.Forms.Button(); this.txtLog = new System.Windows.Forms.TextBox(); this.btnSwitchService = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.btnClear); this.panel1.Controls.Add(this.txtLog); this.panel1.Controls.Add(this.btnSwitchService); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1214, 789); this.panel1.TabIndex = 0; // // btnClear // this.btnClear.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClear.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnClear.Location = new System.Drawing.Point(1012, 94); this.btnClear.Margin = new System.Windows.Forms.Padding(4); this.btnClear.Name = "btnClear"; this.btnClear.Size = new System.Drawing.Size(162, 54); this.btnClear.TabIndex = 4; this.btnClear.Text = "清空"; this.btnClear.UseVisualStyleBackColor = true; this.btnClear.Click += new System.EventHandler(this.BtnClear_Click); // // txtLog // this.txtLog.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.txtLog.BackColor = System.Drawing.SystemColors.Window; this.txtLog.Location = new System.Drawing.Point(34, 155); this.txtLog.Multiline = true; this.txtLog.Name = "txtLog"; this.txtLog.ReadOnly = true; this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtLog.Size = new System.Drawing.Size(1140, 600); this.txtLog.TabIndex = 3; // // btnSwitchService // this.btnSwitchService.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnSwitchService.Location = new System.Drawing.Point(497, 40); this.btnSwitchService.Margin = new System.Windows.Forms.Padding(4); this.btnSwitchService.Name = "btnSwitchService"; this.btnSwitchService.Size = new System.Drawing.Size(220, 70); this.btnSwitchService.TabIndex = 2; this.btnSwitchService.Text = "启动"; this.btnSwitchService.UseVisualStyleBackColor = true; this.btnSwitchService.Click += new System.EventHandler(this.BtnSwitchService_Click); // // FormServer // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 24F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(1214, 789); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.Name = "FormServer"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "TcpServerTestEcho - 与外面妖艳的贱货不一样的EchoServer"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.TextBox txtLog; private System.Windows.Forms.Button btnSwitchService; } }
43.711864
156
0.598488
[ "Apache-2.0" ]
Gao996/HPSocket.Net
demo/TcpServer-TestEcho/FormServer.Designer.cs
5,346
C#
#if __IOS__ || __MACCATALYST__ using Foundation; using Yang.Maui.Helper.CustomControls.Platform; using Microsoft.Maui.Graphics.Platform; using Microsoft.Maui.Handlers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UIKit; using Microsoft.Maui.Graphics; namespace Yang.Maui.Helper.CustomControls.DrawableView { public class TouchEventArgs : EventArgs { public TouchEventArgs(Point point) { Point = point; } public Point Point { get; set; } } public class TouchNativeDrawableView : PlatformDrawableView { public event EventHandler<TouchEventArgs>? TouchDown; public event EventHandler<TouchEventArgs>? TouchMove; public event EventHandler<TouchEventArgs>? TouchUp; public override void TouchesBegan(NSSet touches, UIEvent? evt) { base.TouchesBegan(touches, evt); var viewPoints = this.GetPointsInView(evt); PointF viewPoint = viewPoints.Length > 0 ? viewPoints[0] : PointF.Zero; var point = new Point(viewPoint.X, viewPoint.Y); TouchDown?.Invoke(this, new TouchEventArgs(point)); } public override void TouchesMoved(NSSet touches, UIEvent? evt) { base.TouchesMoved(touches, evt); var viewPoints = this.GetPointsInView(evt); PointF viewPoint = viewPoints.Length > 0 ? viewPoints[0] : PointF.Zero; var point = new Point(viewPoint.X, viewPoint.Y); TouchMove?.Invoke(this, new TouchEventArgs(point)); } public override void TouchesEnded(NSSet touches, UIEvent? evt) { base.TouchesEnded(touches, evt); var viewPoints = this.GetPointsInView(evt); PointF viewPoint = viewPoints.Length > 0 ? viewPoints[0] : PointF.Zero; var point = new Point(viewPoint.X, viewPoint.Y); TouchUp?.Invoke(this, new TouchEventArgs(point)); } public override void TouchesCancelled(NSSet touches, UIEvent? evt) { base.TouchesCancelled(touches, evt); var viewPoints = this.GetPointsInView(evt); PointF viewPoint = viewPoints.Length > 0 ? viewPoints[0] : PointF.Zero; var point = new Point(viewPoint.X, viewPoint.Y); TouchUp?.Invoke(this, new TouchEventArgs(point)); } } public partial class DrawableViewHandler : ViewHandler<IDrawableView, TouchNativeDrawableView> { const NSKeyValueObservingOptions observingOptions = NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.OldNew | NSKeyValueObservingOptions.Prior; IDisposable? _isLoadedObserverDisposable; protected override TouchNativeDrawableView CreatePlatformView() { var nativeDrawableView = new TouchNativeDrawableView { UserInteractionEnabled = true, BackgroundColor = UIColor.Clear, }; return nativeDrawableView; } protected override void ConnectHandler(TouchNativeDrawableView nativeView) { base.ConnectHandler(nativeView); var key = nativeView.Superview == null ? "subviews" : "superview"; _isLoadedObserverDisposable = nativeView.AddObserver(key, observingOptions, OnViewLoadedObserver); nativeView.TouchDown += OnTouchDown; nativeView.TouchMove += OnTouchMove; nativeView.TouchUp += OnTouchUp; nativeView.PlatformDraw += OnDraw; } protected override void DisconnectHandler(TouchNativeDrawableView nativeView) { base.DisconnectHandler(nativeView); _isLoadedObserverDisposable?.Dispose(); _isLoadedObserverDisposable = null; nativeView.TouchDown -= OnTouchDown; nativeView.TouchMove -= OnTouchMove; nativeView.TouchUp -= OnTouchUp; nativeView.PlatformDraw -= OnDraw; } public static void MapInvalidate(DrawableViewHandler handler, IDrawableView drawableView, object? arg) { handler.PlatformView?.SetNeedsDisplay(); } void OnViewLoadedObserver(NSObservedChange nSObservedChange) { if (!nSObservedChange?.NewValue?.Equals(NSNull.Null) ?? false) { VirtualView?.Load(); } else if (!nSObservedChange?.OldValue?.Equals(NSNull.Null) ?? false) { VirtualView?.Unload(); _isLoadedObserverDisposable?.Dispose(); _isLoadedObserverDisposable = null; } } void OnTouchDown(object? sender, TouchEventArgs e) { VirtualView?.OnTouchDown(e.Point); } void OnTouchMove(object? sender, TouchEventArgs e) { VirtualView?.OnTouchMove(e.Point); } void OnTouchUp(object? sender, TouchEventArgs e) { VirtualView?.OnTouchUp(e.Point); } private void OnDraw(object sender, PlatformDrawEventArgs e) { VirtualView?.OnDraw(sender, e); } } } #endif
32.574074
166
0.627819
[ "MIT" ]
xtuzy/Xamarin.Native.Helper
Yang.Maui.Helper/CustomControls/DrawableView/DrawableViewHandler.iOS.cs
5,279
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.marketing.campaign.self.activity.batchquery /// </summary> public class AlipayMarketingCampaignSelfActivityBatchqueryRequest : IAlipayRequest<AlipayMarketingCampaignSelfActivityBatchqueryResponse> { /// <summary> /// 支付宝商户活动批量信息查询 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.marketing.campaign.self.activity.batchquery"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
24.014493
141
0.547978
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayMarketingCampaignSelfActivityBatchqueryRequest.cs
3,342
C#
using System; using pdxpartyparrot.Core; using pdxpartyparrot.Core.Effects; using pdxpartyparrot.Core.Util; using pdxpartyparrot.Game.Interactables; using Spine.Unity; using UnityEngine; namespace pdxpartyparrot.ggj2020.Actors { [RequireComponent(typeof(AudioSource))] [RequireComponent(typeof(BoneFollower))] public sealed class RepairPoint : MonoBehaviour, IInteractable { #region Events public event EventHandler<EventArgs> RepairedEvent; #endregion public enum DamageType { Fire, Damaged, Loose, Random, //Stacked, } private const int DamageTypeCount = 3; public enum RepairState { Repaired, UnRepaired, } public Type InteractableType => GetType(); #region Effects [Header("Effects")] [SerializeField] private EffectTrigger _fireDamageEffectTrigger; [SerializeField] private EffectTrigger _damagedEffectTrigger; [SerializeField] private EffectTrigger _looseEffectTrigger; [SerializeField] private EffectTrigger _repairEffectTrigger; #endregion [Space(10)] [SerializeField] private DamageType _damageType = DamageType.Random; [SerializeField] [ReadOnly] private DamageType _currentDamageType = DamageType.Fire; public DamageType CurrentDamageType => _currentDamageType; [Space(10)] [SerializeField] [ReadOnly] private RepairState _repairState = RepairState.Repaired; public RepairState CurrentRepairState => _repairState; public bool IsRepaired => RepairState.Repaired == CurrentRepairState; public bool CanInteract => !IsRepaired; #region Unity Lifecycle private void Awake() { GetComponent<AudioSource>().spatialBlend = 0.0f; } #endregion public void Initialize() { ResetDamage(); } public void ResetDamage() { _repairState = RepairState.Repaired; StopDamageEffects(); _repairEffectTrigger.StopTrigger(); } public void Damage() { _repairState = RepairState.UnRepaired; gameObject.SetActive(true); switch(_damageType) { case DamageType.Fire: case DamageType.Damaged: case DamageType.Loose: _currentDamageType = _damageType; break; case DamageType.Random: _currentDamageType = (DamageType)PartyParrotManager.Instance.Random.Next(DamageTypeCount); break; /*case DamageType.Stacked: break;*/ } // TODO: make overrides something we can do from the debug menu //_currentDamageType = DamageType.Damaged; InitDamage(); } private void InitDamage() { switch(_currentDamageType) { case DamageType.Fire: _fireDamageEffectTrigger.Trigger(); break; case DamageType.Damaged: _damagedEffectTrigger.Trigger(); break; case DamageType.Loose: _looseEffectTrigger.Trigger(); break; default: Debug.LogError($"Invalid damage type {_currentDamageType}"); break; } } public void Repair() { Debug.Log("Point repair successful!"); _repairState = RepairState.Repaired; StopDamageEffects(); //_repairEffectTrigger.Trigger(); RepairedEvent?.Invoke(this, EventArgs.Empty); gameObject.SetActive(false); } private void StopDamageEffects() { _fireDamageEffectTrigger.StopTrigger(); _damagedEffectTrigger.StopTrigger(); _looseEffectTrigger.StopTrigger(); } } }
25.488095
107
0.554881
[ "Apache-2.0" ]
pdxparrot/ggj2020
Assets/Scripts/ggj2020/Actors/RepairPoint.cs
4,284
C#
namespace oadr2b_ven.UserControls.OptSchedule { partial class oadrucOptScheduleView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pnlOptSchedule = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lvAvailability = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.txtResource = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.btnDeleteSchedule = new System.Windows.Forms.Button(); this.btnAddSchedule = new System.Windows.Forms.Button(); this.txtMarketContext = new System.Windows.Forms.TextBox(); this.txtOptID = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.numericUpDownDuration = new System.Windows.Forms.NumericUpDown(); this.label4 = new System.Windows.Forms.Label(); this.dtStart = new System.Windows.Forms.DateTimePicker(); this.label3 = new System.Windows.Forms.Label(); this.cmbOptReason = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.cmbOptType = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.pnlOptSchedule.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownDuration)).BeginInit(); this.SuspendLayout(); // // pnlOptSchedule // this.pnlOptSchedule.Controls.Add(this.groupBox1); this.pnlOptSchedule.Controls.Add(this.txtResource); this.pnlOptSchedule.Controls.Add(this.label5); this.pnlOptSchedule.Controls.Add(this.btnDeleteSchedule); this.pnlOptSchedule.Controls.Add(this.btnAddSchedule); this.pnlOptSchedule.Controls.Add(this.txtMarketContext); this.pnlOptSchedule.Controls.Add(this.txtOptID); this.pnlOptSchedule.Controls.Add(this.label7); this.pnlOptSchedule.Controls.Add(this.label6); this.pnlOptSchedule.Controls.Add(this.numericUpDownDuration); this.pnlOptSchedule.Controls.Add(this.label4); this.pnlOptSchedule.Controls.Add(this.dtStart); this.pnlOptSchedule.Controls.Add(this.label3); this.pnlOptSchedule.Controls.Add(this.cmbOptReason); this.pnlOptSchedule.Controls.Add(this.label2); this.pnlOptSchedule.Controls.Add(this.cmbOptType); this.pnlOptSchedule.Controls.Add(this.label1); this.pnlOptSchedule.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlOptSchedule.Location = new System.Drawing.Point(0, 0); this.pnlOptSchedule.Name = "pnlOptSchedule"; this.pnlOptSchedule.Size = new System.Drawing.Size(425, 415); this.pnlOptSchedule.TabIndex = 0; // // groupBox1 // this.groupBox1.Controls.Add(this.lvAvailability); this.groupBox1.Location = new System.Drawing.Point(19, 163); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(383, 200); this.groupBox1.TabIndex = 19; this.groupBox1.TabStop = false; this.groupBox1.Text = "Availability"; // // lvAvailability // this.lvAvailability.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.lvAvailability.Dock = System.Windows.Forms.DockStyle.Fill; this.lvAvailability.FullRowSelect = true; this.lvAvailability.GridLines = true; this.lvAvailability.Location = new System.Drawing.Point(3, 16); this.lvAvailability.Name = "lvAvailability"; this.lvAvailability.Size = new System.Drawing.Size(377, 181); this.lvAvailability.TabIndex = 16; this.lvAvailability.UseCompatibleStateImageBehavior = false; this.lvAvailability.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Start Date/Time"; this.columnHeader1.Width = 131; // // columnHeader2 // this.columnHeader2.Text = "Duration"; this.columnHeader2.Width = 86; // // txtResource // this.txtResource.Location = new System.Drawing.Point(228, 81); this.txtResource.Name = "txtResource"; this.txtResource.Size = new System.Drawing.Size(171, 20); this.txtResource.TabIndex = 5; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(225, 65); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 18; this.label5.Text = "Resource"; // // btnDeleteSchedule // this.btnDeleteSchedule.Location = new System.Drawing.Point(249, 369); this.btnDeleteSchedule.Name = "btnDeleteSchedule"; this.btnDeleteSchedule.Size = new System.Drawing.Size(150, 23); this.btnDeleteSchedule.TabIndex = 15; this.btnDeleteSchedule.TabStop = false; this.btnDeleteSchedule.Text = "Remove Selected Rows"; this.btnDeleteSchedule.UseVisualStyleBackColor = true; this.btnDeleteSchedule.Click += new System.EventHandler(this.btnDeleteSchedule_Click); // // btnAddSchedule // this.btnAddSchedule.Location = new System.Drawing.Point(300, 134); this.btnAddSchedule.Name = "btnAddSchedule"; this.btnAddSchedule.Size = new System.Drawing.Size(99, 23); this.btnAddSchedule.TabIndex = 8; this.btnAddSchedule.Text = "Add Availability"; this.btnAddSchedule.UseVisualStyleBackColor = true; this.btnAddSchedule.Click += new System.EventHandler(this.btnAddSchedule_Click); // // txtMarketContext // this.txtMarketContext.Location = new System.Drawing.Point(18, 81); this.txtMarketContext.Name = "txtMarketContext"; this.txtMarketContext.Size = new System.Drawing.Size(171, 20); this.txtMarketContext.TabIndex = 4; // // txtOptID // this.txtOptID.Enabled = false; this.txtOptID.Location = new System.Drawing.Point(18, 29); this.txtOptID.Name = "txtOptID"; this.txtOptID.Size = new System.Drawing.Size(121, 20); this.txtOptID.TabIndex = 1; this.txtOptID.TabStop = false; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(15, 65); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(79, 13); this.label7.TabIndex = 1; this.label7.Text = "Market Context"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(15, 13); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(38, 13); this.label6.TabIndex = 1; this.label6.Text = "Opt ID"; // // numericUpDownDuration // this.numericUpDownDuration.Location = new System.Drawing.Point(221, 137); this.numericUpDownDuration.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.numericUpDownDuration.Name = "numericUpDownDuration"; this.numericUpDownDuration.Size = new System.Drawing.Size(56, 20); this.numericUpDownDuration.TabIndex = 7; this.numericUpDownDuration.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(218, 121); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(79, 13); this.label4.TabIndex = 6; this.label4.Text = "Duration (Hour)"; // // dtStart // this.dtStart.CustomFormat = "ddd MMM dd yyyy hh:mm tt"; this.dtStart.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dtStart.Location = new System.Drawing.Point(22, 137); this.dtStart.MaxDate = new System.DateTime(3000, 12, 31, 0, 0, 0, 0); this.dtStart.MinDate = new System.DateTime(2000, 1, 1, 0, 0, 0, 0); this.dtStart.Name = "dtStart"; this.dtStart.Size = new System.Drawing.Size(180, 20); this.dtStart.TabIndex = 6; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(19, 121); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(55, 13); this.label3.TabIndex = 4; this.label3.Text = "Start Date"; // // cmbOptReason // this.cmbOptReason.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbOptReason.FormattingEnabled = true; this.cmbOptReason.Items.AddRange(new object[] { "economic", "emergency", "mustRun", "notParticipating", "outageRunStatus", "overrideStatus", "participating", "x-schedule"}); this.cmbOptReason.Location = new System.Drawing.Point(278, 28); this.cmbOptReason.Name = "cmbOptReason"; this.cmbOptReason.Size = new System.Drawing.Size(121, 21); this.cmbOptReason.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(278, 13); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 13); this.label2.TabIndex = 2; this.label2.Text = "Opt Reason"; // // cmbOptType // this.cmbOptType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbOptType.FormattingEnabled = true; this.cmbOptType.Items.AddRange(new object[] { "optIn", "optOut"}); this.cmbOptType.Location = new System.Drawing.Point(145, 28); this.cmbOptType.Name = "cmbOptType"; this.cmbOptType.Size = new System.Drawing.Size(121, 21); this.cmbOptType.TabIndex = 2; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(142, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(51, 13); this.label1.TabIndex = 0; this.label1.Text = "Opt Type"; // // oadrucOptScheduleView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.pnlOptSchedule); this.Name = "oadrucOptScheduleView"; this.Size = new System.Drawing.Size(425, 415); this.pnlOptSchedule.ResumeLayout(false); this.pnlOptSchedule.PerformLayout(); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownDuration)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pnlOptSchedule; private System.Windows.Forms.NumericUpDown numericUpDownDuration; private System.Windows.Forms.Label label4; private System.Windows.Forms.DateTimePicker dtStart; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cmbOptReason; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cmbOptType; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtMarketContext; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtOptID; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button btnAddSchedule; private System.Windows.Forms.Button btnDeleteSchedule; private System.Windows.Forms.ListView lvAvailability; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.TextBox txtResource; private System.Windows.Forms.Label label5; private System.Windows.Forms.GroupBox groupBox1; } }
45.42284
112
0.585785
[ "BSD-3-Clause" ]
epri-dev/OpenADR-Virtual-End-Node
oadr2b-ven/UserControls/OptSchedule/oadrucOptScheduleView.Designer.cs
14,719
C#
// Copyright 2016-2018 Confluent Inc., 2015-2016 Andreas Heider // // 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. // // Derived from: rdkafka-dotnet, licensed under the 2-clause BSD License. // // Refer to LICENSE for more information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Confluent.Kafka.Impl; using Confluent.Kafka.Internal; namespace Confluent.Kafka { /// <summary> /// Implements a high-level Apache Kafka consumer with /// deserialization capability. /// </summary> internal class Consumer<TKey, TValue> : IConsumer<TKey, TValue>, IClient { internal class Config { internal IEnumerable<KeyValuePair<string, string>> config; internal Action<Error> errorHandler; internal Action<LogMessage> logHandler; internal Action<string> statisticsHandler; internal Action<CommittedOffsets> offsetsCommittedHandler; internal Func<List<TopicPartition>, IEnumerable<TopicPartitionOffset>> partitionsAssignedHandler; internal Func<List<TopicPartitionOffset>, IEnumerable<TopicPartitionOffset>> partitionsRevokedHandler; } private IDeserializer<TKey> keyDeserializer; private IDeserializer<TValue> valueDeserializer; private Dictionary<Type, object> defaultDeserializers = new Dictionary<Type, object> { { typeof(Null), Deserializers.Null }, { typeof(Ignore), Deserializers.Ignore }, { typeof(int), Deserializers.Int32 }, { typeof(long), Deserializers.Int64 }, { typeof(string), Deserializers.Utf8 }, { typeof(float), Deserializers.Single }, { typeof(double), Deserializers.Double }, { typeof(byte[]), Deserializers.ByteArray } }; private int cancellationDelayMaxMs; private bool disposeHasBeenCalled = false; private object disposeHasBeenCalledLockObj = new object(); /// <summary> /// keeps track of whether or not assign has been called during /// invocation of a rebalance callback event. /// </summary> private int assignCallCount = 0; private object assignCallCountLockObj = new object(); private bool enableHeaderMarshaling = true; private bool enableTimestampMarshaling = true; private bool enableTopicNameMarshaling = true; private SafeKafkaHandle kafkaHandle; private Action<Error> errorHandler; private Librdkafka.ErrorDelegate errorCallbackDelegate; private void ErrorCallback(IntPtr rk, ErrorCode err, string reason, IntPtr opaque) { // Ensure registered handlers are never called as a side-effect of Dispose/Finalize (prevents deadlocks in common scenarios). if (kafkaHandle.IsClosed) { return; } errorHandler?.Invoke(kafkaHandle.CreatePossiblyFatalError(err, reason)); } private Action<string> statisticsHandler; private Librdkafka.StatsDelegate statisticsCallbackDelegate; private int StatisticsCallback(IntPtr rk, IntPtr json, UIntPtr json_len, IntPtr opaque) { // Ensure registered handlers are never called as a side-effect of Dispose/Finalize (prevents deadlocks in common scenarios). if (kafkaHandle.IsClosed) { return 0; } statisticsHandler?.Invoke(Util.Marshal.PtrToStringUTF8(json)); return 0; // instruct librdkafka to immediately free the json ptr. } private Action<LogMessage> logHandler; private object loggerLockObj = new object(); private Librdkafka.LogDelegate logCallbackDelegate; private void LogCallback(IntPtr rk, SyslogLevel level, string fac, string buf) { // Ensure registered handlers are never called as a side-effect of Dispose/Finalize (prevents deadlocks in common scenarios). // Note: kafkaHandle can be null if the callback is during construction (in that case the delegate should be called). if (kafkaHandle != null && kafkaHandle.IsClosed) { return; } logHandler?.Invoke(new LogMessage(Util.Marshal.PtrToStringUTF8(Librdkafka.name(rk)), level, fac, buf)); } private Func<List<TopicPartition>, IEnumerable<TopicPartitionOffset>> partitionsAssignedHandler; private Func<List<TopicPartitionOffset>, IEnumerable<TopicPartitionOffset>> partitionsRevokedHandler; private Librdkafka.RebalanceDelegate rebalanceDelegate; private void RebalanceCallback( IntPtr rk, ErrorCode err, IntPtr partitions, IntPtr opaque) { var partitionAssignment = SafeKafkaHandle.GetTopicPartitionOffsetErrorList(partitions).Select(p => p.TopicPartition).ToList(); // Ensure registered handlers are never called as a side-effect of Dispose/Finalize (prevents deadlocks in common scenarios). if (kafkaHandle.IsClosed) { // The RebalanceCallback should never be invoked as a side effect of Dispose. // If for some reason flow of execution gets here, something is badly wrong. // (and we have a closed librdkafka handle that is expecting an assign call...) throw new Exception("Unexpected rebalance callback on disposed kafkaHandle"); } if (err == ErrorCode.Local_AssignPartitions) { if (partitionsAssignedHandler == null) { Assign(partitionAssignment.Select(p => new TopicPartitionOffset(p, Offset.Unset))); return; } lock (assignCallCountLockObj) { assignCallCount = 0; } var assignTo = partitionsAssignedHandler(partitionAssignment); lock (assignCallCountLockObj) { if (assignCallCount > 0) { throw new InvalidOperationException("Assign/Unassign must not be called in the partitions assigned handler."); } } Assign(assignTo); return; } if (err == ErrorCode.Local_RevokePartitions) { if (partitionsRevokedHandler == null) { Unassign(); return; } var assignmentWithPositions = new List<TopicPartitionOffset>(); foreach (var tp in partitionAssignment) { try { assignmentWithPositions.Add(new TopicPartitionOffset(tp, Position(tp))); } catch { assignmentWithPositions.Add(new TopicPartitionOffset(tp, Offset.Unset)); } } lock (assignCallCountLockObj) { assignCallCount = 0; } var assignTo = partitionsRevokedHandler(assignmentWithPositions); lock (assignCallCountLockObj) { if (assignCallCount > 0) { throw new InvalidOperationException("Assign/Unassign must not be called in the partitions revoked handler."); } } // This distinction is important because calling Assign whilst the consumer is being // closed (which will generally trigger this callback) is disallowed. if (assignTo.Count() > 0) { Assign(assignTo); } else { Unassign(); } return; } throw new KafkaException(kafkaHandle.CreatePossiblyFatalError(err, null)); } private Action<CommittedOffsets> offsetsCommittedHandler; private Librdkafka.CommitDelegate commitDelegate; private void CommitCallback( IntPtr rk, ErrorCode err, IntPtr offsets, IntPtr opaque) { // Ensure registered handlers are never called as a side-effect of Dispose/Finalize (prevents deadlocks in common scenarios). if (kafkaHandle.IsClosed) { return; } offsetsCommittedHandler?.Invoke(new CommittedOffsets( SafeKafkaHandle.GetTopicPartitionOffsetErrorList(offsets), kafkaHandle.CreatePossiblyFatalError(err, null) )); } private static byte[] KeyAsByteArray(rd_kafka_message msg) { byte[] keyAsByteArray = null; if (msg.key != IntPtr.Zero) { keyAsByteArray = new byte[(int) msg.key_len]; Marshal.Copy(msg.key, keyAsByteArray, 0, (int) msg.key_len); } return keyAsByteArray; } private static byte[] ValueAsByteArray(rd_kafka_message msg) { byte[] valAsByteArray = null; if (msg.val != IntPtr.Zero) { valAsByteArray = new byte[(int) msg.len]; Marshal.Copy(msg.val, valAsByteArray, 0, (int) msg.len); } return valAsByteArray; } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Assignment" /> /// </summary> public List<TopicPartition> Assignment => kafkaHandle.GetAssignment(); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Subscription" /> /// </summary> public List<string> Subscription => kafkaHandle.GetSubscription(); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Subscribe(IEnumerable{string})" /> /// </summary> public void Subscribe(IEnumerable<string> topics) { kafkaHandle.Subscribe(topics); } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Subscribe(string)" /> /// </summary> public void Subscribe(string topic) => Subscribe(new[] { topic }); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Unsubscribe" /> /// </summary> public void Unsubscribe() => kafkaHandle.Unsubscribe(); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Assign(TopicPartition)" /> /// </summary> public void Assign(TopicPartition partition) => Assign(new List<TopicPartition> { partition }); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Assign(TopicPartitionOffset)" /> /// </summary> public void Assign(TopicPartitionOffset partition) => Assign(new List<TopicPartitionOffset> { partition }); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Assign(IEnumerable{TopicPartitionOffset})" /> /// </summary> public void Assign(IEnumerable<TopicPartitionOffset> partitions) { lock (assignCallCountLockObj) { assignCallCount += 1; } kafkaHandle.Assign(partitions.ToList()); } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Assign(TopicPartition)" /> /// </summary> public void Assign(IEnumerable<TopicPartition> partitions) { lock (assignCallCountLockObj) { assignCallCount += 1; } kafkaHandle.Assign(partitions.Select(p => new TopicPartitionOffset(p, Offset.Unset)).ToList()); } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Unassign" /> /// </summary> public void Unassign() { lock (assignCallCountLockObj) { assignCallCount += 1; } kafkaHandle.Assign(null); } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.StoreOffset(ConsumeResult{TKey, TValue})" /> /// </summary> public void StoreOffset(ConsumeResult<TKey, TValue> result) => StoreOffset(new TopicPartitionOffset(result.TopicPartition, result.Offset + 1)); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.StoreOffset(TopicPartitionOffset)" /> /// </summary> public void StoreOffset(TopicPartitionOffset offset) { try { kafkaHandle.StoreOffsets(new [] { offset }); } catch (TopicPartitionOffsetException e) { throw new KafkaException(e.Results[0].Error); } } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Commit()" /> /// </summary> public List<TopicPartitionOffset> Commit() // TODO: use a librdkafka queue for this. => kafkaHandle.Commit(null); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Commit(IEnumerable{TopicPartitionOffset})" /> /// </summary> public void Commit(IEnumerable<TopicPartitionOffset> offsets) // TODO: use a librdkafka queue for this. => kafkaHandle.Commit(offsets); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Commit(ConsumeResult{TKey, TValue})" /> /// </summary> public void Commit(ConsumeResult<TKey, TValue> result) { if (result.Message == null) { throw new InvalidOperationException("Attempt was made to commit offset corresponding to an empty consume result"); } Commit(new [] { new TopicPartitionOffset(result.TopicPartition, result.Offset + 1) }); } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Seek(TopicPartitionOffset)" /> /// </summary> public void Seek(TopicPartitionOffset tpo) => kafkaHandle.Seek(tpo.Topic, tpo.Partition, tpo.Offset, -1); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Pause(IEnumerable{TopicPartition})" /> /// </summary> public void Pause(IEnumerable<TopicPartition> partitions) => kafkaHandle.Pause(partitions); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Resume(IEnumerable{TopicPartition})" /> /// </summary> public void Resume(IEnumerable<TopicPartition> partitions) => kafkaHandle.Resume(partitions); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Committed(IEnumerable{TopicPartition}, TimeSpan)" /> /// </summary> public List<TopicPartitionOffset> Committed(IEnumerable<TopicPartition> partitions, TimeSpan timeout) // TODO: use a librdkafka queue for this. => kafkaHandle.Committed(partitions, (IntPtr)timeout.TotalMillisecondsAsInt()); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Position(TopicPartition)" /> /// </summary> public Offset Position(TopicPartition partition) { try { return kafkaHandle.Position(new List<TopicPartition> { partition }).First().Offset; } catch (TopicPartitionOffsetException e) { throw new KafkaException(e.Results[0].Error); } } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.OffsetsForTimes(IEnumerable{TopicPartitionTimestamp}, TimeSpan)" /> /// </summary> public List<TopicPartitionOffset> OffsetsForTimes(IEnumerable<TopicPartitionTimestamp> timestampsToSearch, TimeSpan timeout) // TODO: use a librdkafka queue for this. => kafkaHandle.OffsetsForTimes(timestampsToSearch, timeout.TotalMillisecondsAsInt()); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.GetWatermarkOffsets(TopicPartition)" /> /// </summary> public WatermarkOffsets GetWatermarkOffsets(TopicPartition topicPartition) => kafkaHandle.GetWatermarkOffsets(topicPartition.Topic, topicPartition.Partition); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.QueryWatermarkOffsets(TopicPartition, TimeSpan)" /> /// </summary> public WatermarkOffsets QueryWatermarkOffsets(TopicPartition topicPartition, TimeSpan timeout) => kafkaHandle.QueryWatermarkOffsets(topicPartition.Topic, topicPartition.Partition, timeout.TotalMillisecondsAsInt()); /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.MemberId" /> /// </summary> public string MemberId => kafkaHandle.MemberId; /// <summary> /// Refer to <see cref="Confluent.Kafka.IClient.AddBrokers(string)" /> /// </summary> public int AddBrokers(string brokers) => kafkaHandle.AddBrokers(brokers); /// <summary> /// Refer to <see cref="Confluent.Kafka.IClient.Name" /> /// </summary> public string Name => kafkaHandle.Name; /// <summary> /// An opaque reference to the underlying librdkafka client instance. /// This can be used to construct an AdminClient that utilizes the same /// underlying librdkafka client as this Consumer instance. /// </summary> public Handle Handle => new Handle { Owner = this, LibrdkafkaHandle = kafkaHandle }; /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey,TValue}.Close" />. /// </summary> public void Close() { // commits offsets and unsubscribes. kafkaHandle.ConsumerClose(); Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases all resources used by this Consumer without /// committing offsets and without alerting the group coordinator /// that the consumer is exiting the group. If you do not call /// <see cref="Confluent.Kafka.Consumer{TKey,TValue}.Close" /> or /// <see cref="Confluent.Kafka.Consumer{TKey,TValue}.Unsubscribe" /> /// prior to Dispose, the group will rebalance after a timeout /// specified by group's `session.timeout.ms`. /// You should commit offsets / unsubscribe from the group before /// calling this method (typically by calling /// <see cref="Confluent.Kafka.Consumer{TKey,TValue}.Close()" />). /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the /// <see cref="Confluent.Kafka.Consumer{TKey,TValue}" /> /// and optionally disposes the managed resources. /// </summary> /// <param name="disposing"> /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { // Calling Dispose a second or subsequent time should be a no-op. lock (disposeHasBeenCalledLockObj) { if (disposeHasBeenCalled) { return; } disposeHasBeenCalled = true; } if (disposing) { // calls to rd_kafka_destroy may result in callbacks // as a side-effect. however the callbacks this class // registers with librdkafka ensure that any registered // events are not called if the kafkaHandle is closed. // this avoids deadlocks in common scenarios. kafkaHandle.Dispose(); } } internal Consumer(ConsumerBuilder<TKey, TValue> builder) { var baseConfig = builder.ConstructBaseConfig(this); this.statisticsHandler = baseConfig.statisticsHandler; this.logHandler = baseConfig.logHandler; this.errorHandler = baseConfig.errorHandler; this.partitionsAssignedHandler = baseConfig.partitionsAssignedHandler; this.partitionsRevokedHandler = baseConfig.partitionsRevokedHandler; this.offsetsCommittedHandler = baseConfig.offsetsCommittedHandler; Librdkafka.Initialize(null); var config = Confluent.Kafka.Config.ExtractCancellationDelayMaxMs(baseConfig.config, out this.cancellationDelayMaxMs); if (config.FirstOrDefault(prop => string.Equals(prop.Key, "group.id", StringComparison.Ordinal)).Value == null) { throw new ArgumentException("'group.id' configuration parameter is required and was not specified."); } var modifiedConfig = config .Where(prop => prop.Key != ConfigPropertyNames.Consumer.ConsumeResultFields); var enabledFieldsObj = config.FirstOrDefault(prop => prop.Key == ConfigPropertyNames.Consumer.ConsumeResultFields).Value; if (enabledFieldsObj != null) { var fields = enabledFieldsObj.Replace(" ", ""); if (fields != "all") { this.enableHeaderMarshaling = false; this.enableTimestampMarshaling = false; this.enableTopicNameMarshaling = false; if (fields != "none") { var parts = fields.Split(','); foreach (var part in parts) { switch (part) { case "headers": this.enableHeaderMarshaling = true; break; case "timestamp": this.enableTimestampMarshaling = true; break; case "topic": this.enableTopicNameMarshaling = true; break; default: throw new ArgumentException( $"Unexpected consume result field name '{part}' in config value '{ConfigPropertyNames.Consumer.ConsumeResultFields}'."); } } } } } var configHandle = SafeConfigHandle.Create(); modifiedConfig .ToList() .ForEach((kvp) => { if (kvp.Value == null) throw new ArgumentNullException($"'{kvp.Key}' configuration parameter must not be null."); configHandle.Set(kvp.Key, kvp.Value); }); // Explicitly keep references to delegates so they are not reclaimed by the GC. rebalanceDelegate = RebalanceCallback; commitDelegate = CommitCallback; errorCallbackDelegate = ErrorCallback; logCallbackDelegate = LogCallback; statisticsCallbackDelegate = StatisticsCallback; IntPtr configPtr = configHandle.DangerousGetHandle(); if (partitionsAssignedHandler != null || partitionsRevokedHandler != null) { Librdkafka.conf_set_rebalance_cb(configPtr, rebalanceDelegate); } if (offsetsCommittedHandler != null) { Librdkafka.conf_set_offset_commit_cb(configPtr, commitDelegate); } if (errorHandler != null) { Librdkafka.conf_set_error_cb(configPtr, errorCallbackDelegate); } if (logHandler != null) { Librdkafka.conf_set_log_cb(configPtr, logCallbackDelegate); } if (statisticsHandler != null) { Librdkafka.conf_set_stats_cb(configPtr, statisticsCallbackDelegate); } this.kafkaHandle = SafeKafkaHandle.Create(RdKafkaType.Consumer, configPtr, this); configHandle.SetHandleAsInvalid(); // config object is no longer useable. var pollSetConsumerError = kafkaHandle.PollSetConsumer(); if (pollSetConsumerError != ErrorCode.NoError) { throw new KafkaException(new Error(pollSetConsumerError, $"Failed to redirect the poll queue to consumer_poll queue: {ErrorCodeExtensions.GetReason(pollSetConsumerError)}")); } // setup key deserializer. if (builder.KeyDeserializer == null) { if (!defaultDeserializers.TryGetValue(typeof(TKey), out object deserializer)) { throw new InvalidOperationException( $"Key deserializer was not specified and there is no default deserializer defined for type {typeof(TKey).Name}."); } this.keyDeserializer = (IDeserializer<TKey>)deserializer; } else { this.keyDeserializer = builder.KeyDeserializer; } // setup value deserializer. if (builder.ValueDeserializer == null) { if (!defaultDeserializers.TryGetValue(typeof(TValue), out object deserializer)) { throw new InvalidOperationException( $"Value deserializer was not specified and there is no default deserializer defined for type {typeof(TValue).Name}."); } this.valueDeserializer = (IDeserializer<TValue>)deserializer; } else { this.valueDeserializer = builder.ValueDeserializer; } } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey, TValue}.Consume(int)" /> /// </summary> public ConsumeResult<TKey, TValue> Consume(int millisecondsTimeout) { var msgPtr = kafkaHandle.ConsumerPoll((IntPtr)millisecondsTimeout); if (msgPtr == IntPtr.Zero) { return null; } try { var msg = Util.Marshal.PtrToStructure<rd_kafka_message>(msgPtr); string topic = null; if (this.enableTopicNameMarshaling) { if (msg.rkt != IntPtr.Zero) { topic = Util.Marshal.PtrToStringUTF8(Librdkafka.topic_name(msg.rkt)); } } if (msg.err == ErrorCode.Local_PartitionEOF) { return new ConsumeResult<TKey, TValue> { TopicPartitionOffset = new TopicPartitionOffset(topic, msg.partition, msg.offset), Message = null, IsPartitionEOF = true }; } long timestampUnix = 0; IntPtr timestampType = (IntPtr)TimestampType.NotAvailable; if (enableTimestampMarshaling) { timestampUnix = Librdkafka.message_timestamp(msgPtr, out timestampType); } var timestamp = new Timestamp(timestampUnix, (TimestampType)timestampType); Headers headers = null; if (enableHeaderMarshaling) { headers = new Headers(); Librdkafka.message_headers(msgPtr, out IntPtr hdrsPtr); if (hdrsPtr != IntPtr.Zero) { for (var i=0; ; ++i) { var err = Librdkafka.header_get_all(hdrsPtr, (IntPtr)i, out IntPtr namep, out IntPtr valuep, out IntPtr sizep); if (err != ErrorCode.NoError) { break; } var headerName = Util.Marshal.PtrToStringUTF8(namep); byte[] headerValue = null; if (valuep != IntPtr.Zero) { headerValue = new byte[(int)sizep]; Marshal.Copy(valuep, headerValue, 0, (int)sizep); } headers.Add(headerName, headerValue); } } } if (msg.err != ErrorCode.NoError) { throw new ConsumeException( new ConsumeResult<byte[], byte[]> { TopicPartitionOffset = new TopicPartitionOffset(topic, msg.partition, msg.offset), Message = new Message<byte[], byte[]> { Timestamp = timestamp, Headers = headers, Key = KeyAsByteArray(msg), Value = ValueAsByteArray(msg) }, IsPartitionEOF = false }, kafkaHandle.CreatePossiblyFatalError(msg.err, null)); } TKey key; try { unsafe { key = keyDeserializer.Deserialize( msg.key == IntPtr.Zero ? ReadOnlySpan<byte>.Empty : new ReadOnlySpan<byte>(msg.key.ToPointer(), (int)msg.key_len), msg.key == IntPtr.Zero, new SerializationContext(MessageComponentType.Key, topic)); } } catch (Exception ex) { throw new ConsumeException( new ConsumeResult<byte[], byte[]> { TopicPartitionOffset = new TopicPartitionOffset(topic, msg.partition, msg.offset), Message = new Message<byte[], byte[]> { Timestamp = timestamp, Headers = headers, Key = KeyAsByteArray(msg), Value = ValueAsByteArray(msg) }, IsPartitionEOF = false }, new Error(ErrorCode.Local_KeyDeserialization), ex); } TValue val; try { unsafe { val = valueDeserializer.Deserialize( msg.val == IntPtr.Zero ? ReadOnlySpan<byte>.Empty : new ReadOnlySpan<byte>(msg.val.ToPointer(), (int)msg.len), msg.val == IntPtr.Zero, new SerializationContext(MessageComponentType.Value, topic)); } } catch (Exception ex) { throw new ConsumeException( new ConsumeResult<byte[], byte[]> { TopicPartitionOffset = new TopicPartitionOffset(topic, msg.partition, msg.offset), Message = new Message<byte[], byte[]> { Timestamp = timestamp, Headers = headers, Key = KeyAsByteArray(msg), Value = ValueAsByteArray(msg) }, IsPartitionEOF = false }, new Error(ErrorCode.Local_ValueDeserialization), ex); } return new ConsumeResult<TKey, TValue> { TopicPartitionOffset = new TopicPartitionOffset(topic, msg.partition, msg.offset), Message = new Message<TKey, TValue> { Timestamp = timestamp, Headers = headers, Key = key, Value = val }, IsPartitionEOF = false }; } finally { Librdkafka.message_destroy(msgPtr); } } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey, TValue}.Consume(CancellationToken)" /> /// </summary> public ConsumeResult<TKey, TValue> Consume(CancellationToken cancellationToken = default(CancellationToken)) { while (true) { // Note: An alternative to throwing on cancellation is to return null, // but that would be problematic downstream (require null checks). cancellationToken.ThrowIfCancellationRequested(); ConsumeResult<TKey, TValue> result = Consume(cancellationDelayMaxMs); if (result == null) { continue; } return result; } } /// <summary> /// Refer to <see cref="Confluent.Kafka.IConsumer{TKey, TValue}.Consume(TimeSpan)" /> /// </summary> public ConsumeResult<TKey, TValue> Consume(TimeSpan timeout) => Consume(timeout.TotalMillisecondsAsInt()); } }
41.257611
156
0.546659
[ "Apache-2.0" ]
AdaskoTheBeAsT/confluent-kafka-dotnet
src/Confluent.Kafka/Consumer.cs
35,234
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.462/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using Persistence.Interfaces.Theming; using System; using System.Collections; using System.Windows.Forms; using ToolkitSettings.Classes.PaletteExplorer; namespace Persistence.Classes.Options.Theming { public class ThemingLogic { #region Variables private IThemeOptions _themeOptions; private PaletteThemeSettingsManager _paletteThemeSettingsManager = new PaletteThemeSettingsManager(); #endregion #region Constructors public ThemingLogic() { } #endregion #region Events public void PaletteMode_Click(object sender, EventArgs e) { } #endregion #region Methods public void InitialisePaletteCollection(ArrayList paletteCollection) { paletteCollection = new ArrayList(); paletteCollection.Add("Global"); paletteCollection.Add("Professional System"); paletteCollection.Add("Professional Office 2003"); paletteCollection.Add("Office 2007 Blue"); paletteCollection.Add("Office 2007 Silver"); paletteCollection.Add("Office 2007 Black"); paletteCollection.Add("Office 2010 Blue"); paletteCollection.Add("Office 2010 Silver"); paletteCollection.Add("Office 2010 Black"); paletteCollection.Add("Office 2013"); paletteCollection.Add("Office 2013 White"); paletteCollection.Add("Sparkle Blue"); paletteCollection.Add("Sparkle Orange"); paletteCollection.Add("Sparkle Purple"); paletteCollection.Add("Custom"); } public void InitialisePaletteCollection(AutoCompleteStringCollection paletteCollection) { paletteCollection = new AutoCompleteStringCollection(); paletteCollection.Add("Global"); paletteCollection.Add("Professional System"); paletteCollection.Add("Professional Office 2003"); paletteCollection.Add("Office 2007 Blue"); paletteCollection.Add("Office 2007 Silver"); paletteCollection.Add("Office 2007 Black"); paletteCollection.Add("Office 2010 Blue"); paletteCollection.Add("Office 2010 Silver"); paletteCollection.Add("Office 2010 Black"); paletteCollection.Add("Office 2013"); paletteCollection.Add("Office 2013 White"); paletteCollection.Add("Sparkle Blue"); paletteCollection.Add("Sparkle Orange"); paletteCollection.Add("Sparkle Purple"); paletteCollection.Add("Custom"); } public void InitialisePaletteCollectionControl(ComboBox paletteCollectionControl, ArrayList paletteCollection, AutoCompleteStringCollection paletteStringCollection) { InitialisePaletteCollection(paletteCollection); InitialisePaletteCollection(paletteStringCollection); foreach (string item in paletteCollection) { paletteCollectionControl.Items.Add(item); } foreach (string item in paletteStringCollection) { paletteCollectionControl.AutoCompleteCustomSource.Add(item); } } public void InitialisePaletteCollectionControl(KryptonComboBox paletteCollectionControl, ArrayList paletteCollection, AutoCompleteStringCollection paletteStringCollection) { InitialisePaletteCollection(paletteCollection); InitialisePaletteCollection(paletteStringCollection); foreach (string item in paletteCollection) { paletteCollectionControl.Items.Add(item); } foreach (string item in paletteStringCollection) { paletteCollectionControl.AutoCompleteCustomSource.Add(item); } } public void ChangeTheme(PaletteMode paletteMode) { SetPaletteMode(paletteMode); switch (paletteMode) { case PaletteMode.Global: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Custom; break; case PaletteMode.ProfessionalSystem: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem; break; case PaletteMode.ProfessionalOffice2003: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalOffice2003; break; case PaletteMode.Office2007Blue: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Blue; break; case PaletteMode.Office2007Silver: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Silver; break; case PaletteMode.Office2007Black: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Black; break; case PaletteMode.Office2010Blue: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Blue; break; case PaletteMode.Office2010Silver: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Silver; break; case PaletteMode.Office2010Black: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Black; break; case PaletteMode.Office2013: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2013; break; case PaletteMode.Office2013White: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Office2013White; break; case PaletteMode.SparkleBlue: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleBlue; break; case PaletteMode.SparkleOrange: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleOrange; break; case PaletteMode.SparklePurple: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.SparklePurple; break; case PaletteMode.Custom: _themeOptions.KryptonManager.GlobalPaletteMode = PaletteModeManager.Custom; _paletteThemeSettingsManager.SetCustomThemeFilePath(_themeOptions.PaletteFilePathControl.Text); break; default: break; } EnableApplyButton(true); EnableRestoreToDefaultsButton(true); } private void EnableRestoreToDefaultsButton(bool enabled) { _themeOptions.ResetToDefaultsControl.Enabled = enabled; } private void EnableApplyButton(bool enabled) { _themeOptions.ApplyControl.Enabled = enabled; } private void EnableCustomThemeControls(bool enabled) { _themeOptions.CustomPaletteLabel.Enabled = enabled; _themeOptions.PaletteFilePathControl.Enabled = enabled; _themeOptions.LoadPaletteFilePathControl.Enabled = enabled; } private string GetPaletteModeAsString(PaletteMode paletteMode) { string mode = ""; switch (paletteMode) { case PaletteMode.Global: mode = "Global"; break; case PaletteMode.ProfessionalSystem: mode = "Professional System"; break; case PaletteMode.ProfessionalOffice2003: mode = "Professional Office 2003"; break; case PaletteMode.Office2007Blue: mode = "Office 2007 Blue"; break; case PaletteMode.Office2007Silver: mode = "Office 2007 Silver"; break; case PaletteMode.Office2007Black: mode = "Office 2007 Black"; break; case PaletteMode.Office2010Blue: mode = "Office 2010 Blue"; break; case PaletteMode.Office2010Silver: mode = "Office 2010 Silver"; break; case PaletteMode.Office2010Black: mode = "Office 2010 Black"; break; case PaletteMode.Office2013: mode = "Office 2013"; break; case PaletteMode.Office2013White: mode = "Office 2013 White"; break; case PaletteMode.SparkleBlue: mode = "Sparkle Blue"; break; case PaletteMode.SparkleOrange: mode = "Sparkle Orange"; break; case PaletteMode.SparklePurple: mode = "Sparkle Purple"; break; case PaletteMode.Custom: mode = "Custom"; break; } return mode; } #endregion #region Setters/Getters /// <summary> /// Sets the PaletteMode to the value of paletteMode. /// </summary> /// <param name="paletteMode">The value of paletteMode.</param> public void SetPaletteMode(PaletteMode paletteMode) { _themeOptions.PaletteMode = paletteMode; } /// <summary> /// Gets the PaletteMode value. /// </summary> /// <returns>The value of paletteMode.</returns> public PaletteMode GetPaletteMode() { return _themeOptions.PaletteMode; } #endregion } }
34.9967
179
0.586665
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.462
Source/Krypton Toolkit Suite Extended/Shared/Persistence/Classes/Options/Theming/ThemingLogic.cs
10,606
C#
using Sirenix.OdinInspector; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace com.tinylabproductions.TLPLib.Components.aspect_ratio { [ExecuteAlways] public class CanvasAspectRatioExpander : UIBehaviour, ILayoutSelfController { #region Unity Serialized Fields #pragma warning disable 649 // ReSharper disable NotNullMemberIsNotInitialized, FieldCanBeMadeReadOnly.Local [SerializeField] float aspectRatio = (float) 16 / 9; // ReSharper restore NotNullMemberIsNotInitialized, FieldCanBeMadeReadOnly.Local #pragma warning restore 649 #endregion [ShowInInspector] string humanReadable => $"{aspectRatio * 9}:9"; RectTransform rt, parent; DrivenRectTransformTracker rtTracker = new DrivenRectTransformTracker(); protected override void Awake() => init(); void init() { if (rt) return; rt = GetComponent<RectTransform>(); parent = (RectTransform) rt.parent; rtTracker.Clear(); rtTracker.Add( this, rt, DrivenTransformProperties.Anchors | DrivenTransformProperties.AnchoredPosition | DrivenTransformProperties.SizeDelta | DrivenTransformProperties.Scale ); rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.anchoredPosition = Vector2.zero; } protected override void Start() { base.Start(); selfLayout(); } protected override void OnRectTransformDimensionsChange() => selfLayout(); protected override void OnEnable() => selfLayout(); protected override void OnDisable() { rtTracker.Clear(); rt = parent = null; } void selfLayout() { if (!IsActive()) return; init(); var parentRect = parent.rect; var parentAspect = parentRect.width / parentRect.height; if (parentAspect > aspectRatio) { rt.sizeDelta = Vector2.zero; rt.localScale = Vector3.one; } else { var scale = aspectRatio / parentAspect; var targetSize = parentRect.size * scale; rt.sizeDelta = targetSize - parentRect.size; rt.localScale = new Vector3(1 / scale, 1 / scale, 1); } } public void SetLayoutHorizontal() => selfLayout(); public void SetLayoutVertical() => selfLayout(); } }
28.182927
84
0.671571
[ "MIT" ]
tinylabproductions/tlplib
parts/0000-TLPLib/Assets/Vendor/TLPLib/core/Components/aspect_ratio/CanvasAspectRatioExpander.cs
2,313
C#
using System; using System.Collections.Generic; using System.Linq; namespace Medenka { class Program { private static string[] combination; private static string[] set; private static HashSet<string> result = new HashSet<string>(); static void Main(string[] args) { set = Console.ReadLine().Split(); int parts = set.Count(x => x == "1"); combination = new string[parts - 1 + set.Length]; int combinationIndex = 0; for (int i = 0; i < set.Length; i++) { combination[combinationIndex++] = set[i]; if (set[i] == "1" && combinationIndex < combination.Length) { combination[combinationIndex++] = "|"; } } Generate(0); } private static void Generate(int index) { if (index == combination.Length) { Console.WriteLine(string.Join(string.Empty, combination)); return; } Generate(index + 1); if (combination[index] == "|" && combination[index + 1] == "0") { Swap(index, index + 1); Generate(index + 1); Swap(index + 1, index); } } private static void Swap(int firstIndex, int secondIndex) { string temp = combination[firstIndex]; combination[firstIndex] = combination[secondIndex]; combination[secondIndex] = temp; } } }
27.271186
75
0.486638
[ "MIT" ]
NaskoVasilev/Algorithms
Exam - 15 May 2016/Exam15May2016/Medenka/Program.cs
1,611
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("ObjectBase.API")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("ObjectBase.API")] [assembly: System.Reflection.AssemblyTitleAttribute("ObjectBase.API")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
42.291667
81
0.633498
[ "MIT" ]
alphamax/ObjectBase
ObjectBase/ObjectBase.API/obj/Debug/net5.0/ObjectBase.API.AssemblyInfo.cs
1,015
C#
namespace Day12; public class Node { public string Name { get; set; } = string.Empty; public List<Node> Connections { get; } = new(); public bool IsLarge => char.IsUpper(Name.First()); } public static class Program { private static readonly Dictionary<string, Node> Nodes = new(); private static readonly List<string> Solutions = new(); public static void Main() { var input = File.ReadAllLines("input.txt") .Where(l => l.Length > 0) .Select(l => l.Split('-')); foreach (var edge in input) { if (!Nodes.ContainsKey(edge[0])) { Nodes.Add(edge[0], new Node { Name = edge[0] }); } if (!Nodes.ContainsKey(edge[1])) { Nodes.Add(edge[1], new Node { Name = edge[1] }); } Nodes[edge[0]].Connections.Add(Nodes[edge[1]]); Nodes[edge[1]].Connections.Add(Nodes[edge[0]]); } foreach (var node in Nodes) { Console.WriteLine(node.Key); } PrintAllPaths(true); var partOne = Solutions.Count; Console.WriteLine($"PartOne: {partOne}"); Solutions.Clear(); PrintAllPaths(false); var partTwo = Solutions.Count; Console.WriteLine($"PartOne: {partTwo}"); } private static void PrintAllPaths(bool visitedSmallCave) { var isVisited = Nodes.Select(kvp => kvp.Key) .ToDictionary(n => n, _ => 0); var path = new Stack<string>(); path.Push("start"); PrintAllPathsUtil("start", isVisited, visitedSmallCave, path); } private static void PrintAllPathsUtil(string current, Dictionary<string, int> isVisited, bool visitedSmallCave, Stack<string> localPath) { if (current == "end") { Solutions.Add(string.Join(',', localPath)); return; } if (!Nodes[current].IsLarge) { if (current is "start" or "end") { isVisited[current] = 1; } else if (!visitedSmallCave && isVisited[current] == 1) { visitedSmallCave = true; isVisited[current] = 2; } else { isVisited[current] = 1; } } foreach (var connection in Nodes[current].Connections .Where(connection => isVisited[connection.Name] == 0 || isVisited[connection.Name] == 1 && connection.Name is not "start" and not "end" && !visitedSmallCave)) { localPath.Push(connection.Name); PrintAllPathsUtil(connection.Name, isVisited, visitedSmallCave, localPath); localPath.Pop(); } if (visitedSmallCave && !Nodes[current].IsLarge && isVisited[current] == 2) { isVisited[current] = 1; } else { isVisited[current] = 0; } } }
30.690909
187
0.466528
[ "Unlicense" ]
eXpl0it3r/Advent-of-Code
2021/Day12/Program.cs
3,376
C#
using System.Web; using System.Web.Mvc; namespace WebApplicationForTestingRequests { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
20.357143
80
0.680702
[ "MIT" ]
Dimitvp/TestingAppForRequsets
WebApplicationForTestingRequests/WebApplicationForTestingRequests/App_Start/FilterConfig.cs
287
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; #nullable enable namespace TSKT { public class SoundPlayer : MonoBehaviour { public readonly struct Task { readonly SoundObject soundObject; public Task(SoundObject obj) { soundObject = obj; } public Task SetPriority(int priority) { if (soundObject) { soundObject.Priority = priority; } return this; } } [SerializeField] GameObject? soundObjectPrefab = default; [SerializeField] float interval = 0.1f; readonly List<SoundObject> soundObjects = new List<SoundObject>(); public Task Play(AudioClip audio, bool loop = false, string? channel = null, float volume = 1f) { if (!audio) { return default; } if (channel != null) { // 同じチャンネルの音を止める Stop(channel); } // 同じ音を同時に再生しない foreach (var it in soundObjects) { if (it.Clip == audio && it.ElapsedTime < interval && it.IsPlaying) { return default; } } var soundObject = soundObjects.FirstOrDefault(_ => !_.Clip); if (soundObject == null) { var obj = Instantiate(soundObjectPrefab, transform, false)!; soundObject = obj.GetComponent<SoundObject>(); soundObjects.Add(soundObject); } soundObject.Play(audio, loop: loop, volume: volume); soundObject.Channel = channel; return new Task(soundObject); } public void Stop(string channel) { foreach (var it in soundObjects) { if (it.Channel == channel) { it.Stop(); } } } public void StopAll() { foreach (var it in soundObjects) { it.Stop(); } } public bool IsPlaying() { foreach (var it in soundObjects) { if (it.IsPlaying) { return true; } } return false; } public bool IsPlaying(AudioClip clip) { foreach (var it in soundObjects) { if (it.Clip == clip && it.IsPlaying) { return true; } } return false; } public bool TryGetPlayingChannel(string channel, out SoundObject? soundObject) { foreach (var it in soundObjects) { if (it.Channel == channel && it.IsPlaying) { soundObject = it; return true; } } soundObject = null; return false; } public bool TryGetPriority(string channel, out int priority) { if (TryGetPlayingChannel(channel, out var current)) { priority = current!.Priority; return true; } priority = 0; return false; } public int GetPriority(string channel, int defaultValue = int.MinValue) { if (TryGetPlayingChannel(channel, out var current)) { return current!.Priority; } return defaultValue; } public float GetPlayingSoundDuration(bool includeLoop = true) { var result = 0f; foreach (var it in soundObjects) { if (it.IsPlaying) { if (includeLoop || !it.Loop) { result = Mathf.Max(result, it.Clip.length); } } } return result; } } }
25.553571
103
0.429769
[ "MIT" ]
enue/Unity_TSKT_Sound
Assets/Package/Runtime/SoundPlayer.cs
4,345
C#
using System; namespace Steamworks { public struct AccountID_t : global::System.IEquatable<global::Steamworks.AccountID_t>, global::System.IComparable<global::Steamworks.AccountID_t> { public AccountID_t(uint value) { this.m_AccountID = value; } public override string ToString() { return this.m_AccountID.ToString(); } public override bool Equals(object other) { return other is global::Steamworks.AccountID_t && this == (global::Steamworks.AccountID_t)other; } public override int GetHashCode() { return this.m_AccountID.GetHashCode(); } public bool Equals(global::Steamworks.AccountID_t other) { return this.m_AccountID == other.m_AccountID; } public int CompareTo(global::Steamworks.AccountID_t other) { return this.m_AccountID.CompareTo(other.m_AccountID); } public static bool operator ==(global::Steamworks.AccountID_t x, global::Steamworks.AccountID_t y) { return x.m_AccountID == y.m_AccountID; } public static bool operator !=(global::Steamworks.AccountID_t x, global::Steamworks.AccountID_t y) { return !(x == y); } public static explicit operator global::Steamworks.AccountID_t(uint value) { return new global::Steamworks.AccountID_t(value); } public static explicit operator uint(global::Steamworks.AccountID_t that) { return that.m_AccountID; } public uint m_AccountID; } }
23.25
146
0.727599
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/Steamworks/AccountID_t.cs
1,397
C#
<<<<<<< HEAD <<<<<<< HEAD // // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // ======= ======= >>>>>>> update form orginal repo #region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo using System; using System.Data; using DotNetNuke.Entities.Modules; namespace DotNetNuke.Tests.Integration.Executers.Dto { public class CopyModuleItem : IHydratable { public int Id { get; set; } public string Title { get; set; } public int KeyID { get { return Id; } set { Id = value; } } public void Fill(IDataReader dr) { Id = Convert.ToInt32(dr["ModuleId"]); Title = Convert.ToString(dr["ModuleTitle"]); } } }
35.711864
115
0.688182
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/CopyModuleItem.cs
2,112
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; namespace NetOffice.VisioApi { /// <summary> /// DispatchInterface IVPaths /// SupportByVersion Visio, 11,12,14,15,16 /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface), BaseType, Enumerator(Enumerator.Reference, EnumeratorInvoke.Property, "Visio", 11, 12, 14, 15, 16), HasIndexProperty(IndexInvoke.Property, "Item")] [TypeId("000D0720-0000-0000-C000-000000000046")] [CoClassSource(typeof(NetOffice.VisioApi.Paths))] public interface IVPaths : ICOMObject, IEnumerableProvider<NetOffice.VisioApi.IVPath> { #region Properties /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] [BaseResult] NetOffice.VisioApi.IVApplication Application { get; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] Int16 ObjectType { get; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="index">Int16 index</param> [SupportByVersion("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] NetOffice.VisioApi.IVPath get_Item16(Int16 index); /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Alias for get_Item16 /// </summary> /// <param name="index">Int16 index</param> [SupportByVersion("Visio", 11,12,14,15,16), Redirect("get_Item16")] NetOffice.VisioApi.IVPath Item16(Int16 index); /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] Int16 Count16 { get; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="index">Int32 index</param> [SupportByVersion("Visio", 11,12,14,15,16)] [BaseResult] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] NetOffice.VisioApi.IVPath this[Int32 index] { get; } /// <summary> /// SupportByVersion Visio 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Visio", 11,12,14,15,16)] Int32 Count { get; } #endregion #region IEnumerable<NetOffice.VisioApi.IVPath> /// <summary> /// SupportByVersion Visio, 11,12,14,15,16 /// </summary> [SupportByVersion("Visio", 11, 12, 14, 15, 16)] new IEnumerator<NetOffice.VisioApi.IVPath> GetEnumerator(); #endregion } }
30.096774
193
0.67274
[ "MIT" ]
igoreksiz/NetOffice
Source/Visio/DispatchInterfaces/IVPaths.cs
2,801
C#
using System; using Connect.Razor.Blade.HtmlTags; // **** // **** // This is auto-generated code - don't modify // Re-run the generation program to recreate // Created 15.10.2019 10:17 // // Each tag and attributes of it prepare code, and they return an object of the same type again // to allow fluid chaining of the commands // **** // **** // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantArgumentDefaultValue // ReSharper disable InconsistentNaming // ReSharper disable IdentifierTypo // ReSharper disable UnusedMember.Global namespace Connect.Razor.Blade.Html5 { /// <summary> /// Generate a standard abbr tag /// </summary> public partial class Abbr : Tag { public Abbr(object content = null) : base("abbr", content) { } public Abbr(params object[] content) : base("abbr", null, content) { } } /// <summary> /// Generate a standard address tag /// </summary> public partial class Address : Tag { public Address(object content = null) : base("address", content) { } public Address(params object[] content) : base("address", null, content) { } } /// <summary> /// Generate a standard b tag /// </summary> public partial class B : Tag { public B(object content = null) : base("b", content) { } public B(params object[] content) : base("b", null, content) { } } /// <summary> /// Generate a standard bdi tag /// </summary> public partial class Bdi : Tag { public Bdi(object content = null) : base("bdi", content) { } public Bdi(params object[] content) : base("bdi", null, content) { } } /// <summary> /// Generate a standard bdo tag /// </summary> public partial class Bdo : Tag { public Bdo(object content = null) : base("bdo", content) { } public Bdo(params object[] content) : base("bdo", null, content) { } public Bdo Dir(string value) => this.Attr("dir", value); } /// <summary> /// Generate a standard blockquote tag /// </summary> public partial class Blockquote : Tag { public Blockquote(object content = null) : base("blockquote", content) { } public Blockquote(params object[] content) : base("blockquote", null, content) { } public Blockquote Cite(string value) => this.Attr("cite", value); } /// <summary> /// Generate a standard cite tag /// </summary> public partial class Cite : Tag { public Cite(object content = null) : base("cite", content) { } public Cite(params object[] content) : base("cite", null, content) { } } /// <summary> /// Generate a standard code tag /// </summary> public partial class Code : Tag { public Code(object content = null) : base("code", content) { } public Code(params object[] content) : base("code", null, content) { } } /// <summary> /// Generate a standard del tag /// </summary> public partial class Del : Tag { public Del(object content = null) : base("del", content) { } public Del(params object[] content) : base("del", null, content) { } public Del Cite(string value) => this.Attr("cite", value); public Del Datetime(string value) => this.Attr("datetime", value); public Del Datetime(DateTime value) => this.Attr("datetime", value); } /// <summary> /// Generate a standard dfn tag /// </summary> public partial class Dfn : Tag { public Dfn(object content = null) : base("dfn", content) { } public Dfn(params object[] content) : base("dfn", null, content) { } } /// <summary> /// Generate a standard em tag /// </summary> public partial class Em : Tag { public Em(object content = null) : base("em", content) { } public Em(params object[] content) : base("em", null, content) { } } /// <summary> /// Generate a standard figcaption tag /// </summary> public partial class Figcaption : Tag { public Figcaption(object content = null) : base("figcaption", content) { } public Figcaption(params object[] content) : base("figcaption", null, content) { } } /// <summary> /// Generate a standard figure tag /// </summary> public partial class Figure : Tag { public Figure(object content = null) : base("figure", content) { } public Figure(params object[] content) : base("figure", null, content) { } } /// <summary> /// Generate a standard i tag /// </summary> public partial class I : Tag { public I(object content = null) : base("i", content) { } public I(params object[] content) : base("i", null, content) { } } /// <summary> /// Generate a standard ins tag /// </summary> public partial class Ins : Tag { public Ins(object content = null) : base("ins", content) { } public Ins(params object[] content) : base("ins", null, content) { } public Ins Cite(string value) => this.Attr("cite", value); public Ins Datetime(string value) => this.Attr("datetime", value); public Ins Datetime(DateTime value) => this.Attr("datetime", value); } /// <summary> /// Generate a standard kbd tag /// </summary> public partial class Kbd : Tag { public Kbd(object content = null) : base("kbd", content) { } public Kbd(params object[] content) : base("kbd", null, content) { } } /// <summary> /// Generate a standard mark tag /// </summary> public partial class Mark : Tag { public Mark(object content = null) : base("mark", content) { } public Mark(params object[] content) : base("mark", null, content) { } } /// <summary> /// Generate a standard meter tag /// </summary> public partial class Meter : Tag { public Meter(object content = null) : base("meter", content) { } public Meter(params object[] content) : base("meter", null, content) { } public Meter Form(string value) => this.Attr("form", value); public Meter High(string value) => this.Attr("high", value); public Meter Low(string value) => this.Attr("low", value); public Meter Max(string value) => this.Attr("max", value); public Meter Min(string value) => this.Attr("min", value); public Meter Optimum(string value) => this.Attr("optimum", value); public Meter Value(string value) => this.Attr("value", value); } /// <summary> /// Generate a standard pre tag /// </summary> public partial class Pre : Tag { public Pre(object content = null) : base("pre", content) { } public Pre(params object[] content) : base("pre", null, content) { } } /// <summary> /// Generate a standard progress tag /// </summary> public partial class Progress : Tag { public Progress(object content = null) : base("progress", content) { } public Progress(params object[] content) : base("progress", null, content) { } public Progress Max(string value) => this.Attr("max", value); public Progress Value(string value) => this.Attr("value", value); } /// <summary> /// Generate a standard q tag /// </summary> public partial class Q : Tag { public Q(object content = null) : base("q", content) { } public Q(params object[] content) : base("q", null, content) { } public Q Cite(string value) => this.Attr("cite", value); } /// <summary> /// Generate a standard rp tag /// </summary> public partial class Rp : Tag { public Rp(object content = null) : base("rp", content) { } public Rp(params object[] content) : base("rp", null, content) { } } /// <summary> /// Generate a standard rt tag /// </summary> public partial class Rt : Tag { public Rt(object content = null) : base("rt", content) { } public Rt(params object[] content) : base("rt", null, content) { } } /// <summary> /// Generate a standard ruby tag /// </summary> public partial class Ruby : Tag { public Ruby(object content = null) : base("ruby", content) { } public Ruby(params object[] content) : base("ruby", null, content) { } } /// <summary> /// Generate a standard s tag /// </summary> public partial class S : Tag { public S(object content = null) : base("s", content) { } public S(params object[] content) : base("s", null, content) { } } /// <summary> /// Generate a standard samp tag /// </summary> public partial class Samp : Tag { public Samp(object content = null) : base("samp", content) { } public Samp(params object[] content) : base("samp", null, content) { } } /// <summary> /// Generate a standard small tag /// </summary> public partial class Small : Tag { public Small(object content = null) : base("small", content) { } public Small(params object[] content) : base("small", null, content) { } } /// <summary> /// Generate a standard strong tag /// </summary> public partial class Strong : Tag { public Strong(object content = null) : base("strong", content) { } public Strong(params object[] content) : base("strong", null, content) { } } /// <summary> /// Generate a standard sub tag /// </summary> public partial class Sub : Tag { public Sub(object content = null) : base("sub", content) { } public Sub(params object[] content) : base("sub", null, content) { } } /// <summary> /// Generate a standard sup tag /// </summary> public partial class Sup : Tag { public Sup(object content = null) : base("sup", content) { } public Sup(params object[] content) : base("sup", null, content) { } } /// <summary> /// Generate a standard template tag /// </summary> public partial class Template : Tag { public Template(object content = null) : base("template", content) { } public Template(params object[] content) : base("template", null, content) { } } /// <summary> /// Generate a standard time tag /// </summary> public partial class Time : Tag { public Time(object content = null) : base("time", content) { } public Time(params object[] content) : base("time", null, content) { } public Time Datetime(string value) => this.Attr("datetime", value); public Time Datetime(DateTime value) => this.Attr("datetime", value); } /// <summary> /// Generate a standard u tag /// </summary> public partial class U : Tag { public U(object content = null) : base("u", content) { } public U(params object[] content) : base("u", null, content) { } } /// <summary> /// Generate a standard var tag /// </summary> public partial class Var : Tag { public Var(object content = null) : base("var", content) { } public Var(params object[] content) : base("var", null, content) { } } }
16.769352
95
0.61658
[ "MIT" ]
DNN-Connect/razor-blade
Razor.Blade/Blade/Html5/GeneratedFormatting.cs
10,615
C#
// This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using System; using System.Windows; using System.Windows.Media; using WPFUI.Extensions; namespace WPFUI.Appearance; /// <summary> /// Lets you update the color accents of the application. /// </summary> public static class Accent { /// <summary> /// SystemAccentColor. /// </summary> public static Color SystemAccent { get { var resource = Application.Current.Resources["SystemAccentColor"]; if (resource is Color color) return color; return Colors.Transparent; } } /// <summary> /// Brush of the SystemAccentColor. /// </summary> public static Brush SystemAccentBrush => new SolidColorBrush(SystemAccent); /// <summary> /// SystemAccentColorLight1. /// </summary> public static Color PrimaryAccent { get { var resource = Application.Current.Resources["SystemAccentColorLight1"]; if (resource is Color color) return color; return Colors.Transparent; } } /// <summary> /// Brush of the SystemAccentColorLight1. /// </summary> public static Brush PrimaryAccentBrush => new SolidColorBrush(PrimaryAccent); /// <summary> /// SystemAccentColorLight2. /// </summary> public static Color SecondaryAccent { get { var resource = Application.Current.Resources["SystemAccentColorLight2"]; if (resource is Color color) return color; return Colors.Transparent; } } /// <summary> /// Brush of the SystemAccentColorLight2. /// </summary> public static Brush SecondaryAccentBrush => new SolidColorBrush(SecondaryAccent); /// <summary> /// SystemAccentColorLight3. /// </summary> public static Color TertiaryAccent { get { var resource = Application.Current.Resources["SystemAccentColorLight3"]; if (resource is Color color) return color; return Colors.Transparent; } } /// <summary> /// Brush of the SystemAccentColorLight3. /// </summary> public static Brush TertiaryAccentBrush => new SolidColorBrush(TertiaryAccent); /// <summary> /// Obsolete alternative for <see cref="Apply"/>. Will be removed in the future. /// </summary> [Obsolete] public static void Change(Color systemAccent, ThemeType themeType = ThemeType.Light, bool systemGlassColor = false) => Apply(systemAccent, themeType, systemGlassColor); /// <summary> /// Obsolete alternative for <see cref="Apply"/>. Will be removed in the future. /// </summary> [Obsolete] public static void Change(Color systemAccent, Color primaryAccent, Color secondaryAccent, Color tertiaryAccent) => Apply(systemAccent, primaryAccent, secondaryAccent, tertiaryAccent); /// <summary> /// Changes the color accents of the application based on the color entered. /// </summary> /// <param name="systemAccent">Primary accent color.</param> /// <param name="themeType">If <see cref="ThemeType.Dark"/>, the colors will be different.</param> /// <param name="systemGlassColor">If the color is taken from the Glass Color System, its brightness will be increased with the help of the operations on HSV space.</param> public static void Apply(Color systemAccent, ThemeType themeType = ThemeType.Light, bool systemGlassColor = false) { if (systemGlassColor) { // WindowGlassColor is little darker than accent color systemAccent = systemAccent.UpdateBrightness(6f); } Color primaryAccent, secondaryAccent, tertiaryAccent; if (themeType == ThemeType.Dark) { primaryAccent = systemAccent.Update(15f, -12f); secondaryAccent = systemAccent.Update(30f, -24f); tertiaryAccent = systemAccent.Update(45f, -36f); } else { primaryAccent = systemAccent.UpdateBrightness(-5f); secondaryAccent = systemAccent.UpdateBrightness(-10f); tertiaryAccent = systemAccent.UpdateBrightness(-15f); } UpdateColorResources( systemAccent, primaryAccent, secondaryAccent, tertiaryAccent ); } /// <summary> /// Changes the color accents of the application based on the entered colors. /// </summary> /// <param name="systemAccent">Primary color.</param> /// <param name="primaryAccent">Alternative light or dark color.</param> /// <param name="secondaryAccent">Second alternative light or dark color (most used).</param> /// <param name="tertiaryAccent">Third alternative light or dark color.</param> public static void Apply(Color systemAccent, Color primaryAccent, Color secondaryAccent, Color tertiaryAccent) { UpdateColorResources(systemAccent, primaryAccent, secondaryAccent, tertiaryAccent); } /// <summary> /// Gets current Desktop Window Manager colorization color. /// <para>It should be the color defined in the system Personalization.</para> /// </summary> public static Color GetColorizationColor() { return UnsafeNativeMethods.GetDwmColor(); } /// <summary> /// Updates application resources. /// </summary> private static void UpdateColorResources(Color systemAccent, Color primaryAccent, Color secondaryAccent, Color tertiaryAccent) { #if DEBUG System.Diagnostics.Debug.WriteLine("INFO | SystemAccentColor: " + systemAccent, "WPFUI.Accent"); System.Diagnostics.Debug.WriteLine("INFO | SystemAccentColorLight1: " + primaryAccent, "WPFUI.Accent"); System.Diagnostics.Debug.WriteLine("INFO | SystemAccentColorLight2: " + secondaryAccent, "WPFUI.Accent"); System.Diagnostics.Debug.WriteLine("INFO | SystemAccentColorLight3: " + tertiaryAccent, "WPFUI.Accent"); #endif // TODO: Inverse TextOnAccentFillColorPrimary if background does not match Application.Current.Resources["SystemAccentColor"] = systemAccent; Application.Current.Resources["SystemAccentColorLight1"] = primaryAccent; Application.Current.Resources["SystemAccentColorLight2"] = secondaryAccent; Application.Current.Resources["SystemAccentColorLight3"] = tertiaryAccent; Application.Current.Resources["SystemAccentBrush"] = secondaryAccent.ToBrush(); Application.Current.Resources["SystemFillColorAttentionBrush"] = secondaryAccent.ToBrush(); Application.Current.Resources["AccentTextFillColorPrimaryBrush"] = tertiaryAccent.ToBrush(); Application.Current.Resources["AccentTextFillColorSecondaryBrush"] = tertiaryAccent.ToBrush(); Application.Current.Resources["AccentTextFillColorTertiaryBrush"] = secondaryAccent.ToBrush(); Application.Current.Resources["AccentFillColorSelectedTextBackgroundBrush"] = systemAccent.ToBrush(); Application.Current.Resources["AccentFillColorDefaultBrush"] = secondaryAccent.ToBrush(); Application.Current.Resources["AccentFillColorSecondaryBrush"] = secondaryAccent.ToBrush(0.9); Application.Current.Resources["AccentFillColorTertiaryBrush"] = secondaryAccent.ToBrush(0.8); } }
36.788462
176
0.667669
[ "MIT" ]
wherewhere/wpfui
src/WPFUI/Appearance/Accent.cs
7,654
C#
using Cam.Cryptography.ECC; using Cam.IO; using Cam.Network.P2P.Payloads; using Cam.Persistence; using System; using System.Collections.Generic; namespace Cam.Consensus { public interface IConsensusContext : IDisposable, ISerializable { //public const uint Version = 0; UInt256 PrevHash { get; } uint BlockIndex { get; } byte ViewNumber { get; } ECPoint[] Validators { get; } int MyIndex { get; } uint PrimaryIndex { get; } uint Timestamp { get; set; } ulong Nonce { get; set; } UInt160 NextConsensus { get; set; } UInt256[] TransactionHashes { get; set; } Dictionary<UInt256, Transaction> Transactions { get; set; } ConsensusPayload[] PreparationPayloads { get; set; } ConsensusPayload[] CommitPayloads { get; set; } ConsensusPayload[] ChangeViewPayloads { get; set; } int[] LastSeenMessage { get; set; } Block Block { get; set; } Snapshot Snapshot { get; } Block CreateBlock(); bool Load(); ConsensusPayload MakeChangeView(); ConsensusPayload MakeCommit(); Block MakeHeader(); ConsensusPayload MakePrepareRequest(); ConsensusPayload MakeRecoveryRequest(); ConsensusPayload MakeRecoveryMessage(); ConsensusPayload MakePrepareResponse(); void Reset(byte viewNumber); void Save(); } }
26.666667
67
0.625
[ "MIT" ]
camchain/CAM
cam/Consensus/IConsensusContext.cs
1,440
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.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoT.Model { /// <summary> /// Container for the parameters to the DetachSecurityProfile operation. /// Disassociates a Device Defender security profile from a thing group or from this account. /// </summary> public partial class DetachSecurityProfileRequest : AmazonIoTRequest { private string _securityProfileName; private string _securityProfileTargetArn; /// <summary> /// Gets and sets the property SecurityProfileName. /// <para> /// The security profile that is detached. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string SecurityProfileName { get { return this._securityProfileName; } set { this._securityProfileName = value; } } // Check to see if SecurityProfileName property is set internal bool IsSetSecurityProfileName() { return this._securityProfileName != null; } /// <summary> /// Gets and sets the property SecurityProfileTargetArn. /// <para> /// The ARN of the thing group from which the security profile is detached. /// </para> /// </summary> [AWSProperty(Required=true)] public string SecurityProfileTargetArn { get { return this._securityProfileTargetArn; } set { this._securityProfileTargetArn = value; } } // Check to see if SecurityProfileTargetArn property is set internal bool IsSetSecurityProfileTargetArn() { return this._securityProfileTargetArn != null; } } }
32.506329
101
0.655763
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/DetachSecurityProfileRequest.cs
2,568
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("AutoMapper.Attributes.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AutoMapper.Attributes.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b64d9f5e-798e-40d0-903a-922d0d1d0480")] // 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.567568
84
0.747722
[ "MIT" ]
schneidenbach/AutoMapper.Attributes
AutoMapper.Attributes.V4.Tests/Properties/AssemblyInfo.cs
1,430
C#
using System; namespace Bari.Core.Exceptions { /// <summary> /// Thrown if there is no registered handler for a reference type /// </summary> [Serializable] public class InvalidReferenceTypeException: Exception { private readonly string referenceType; /// <summary> /// Gets the unsupported reference's type /// </summary> public string ReferenceType { get { return referenceType; } } /// <summary> /// Creates the exception object /// </summary> /// <param name="referenceType">Reference type which is not supported</param> public InvalidReferenceTypeException(string referenceType) { this.referenceType = referenceType; } /// <summary> /// Creates and returns a string representation of the current exception. /// </summary> /// <returns> /// A string representation of the current exception. /// </returns> /// <filterpriority>1</filterpriority><PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="*AllFiles*"/></PermissionSet> public override string ToString() { return string.Format("Reference type {0} is not supported", referenceType); } } }
35.357143
264
0.603367
[ "Apache-2.0" ]
Psychobilly87/bari
src/core/Bari.Core/cs/Exceptions/InvalidReferenceTypeException.cs
1,487
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Smartag.Model.V20180313; using System; using System.Collections.Generic; namespace Aliyun.Acs.Smartag.Transform.V20180313 { public class GetCloudConnectNetworkUseLimitResponseUnmarshaller { public static GetCloudConnectNetworkUseLimitResponse Unmarshall(UnmarshallerContext context) { GetCloudConnectNetworkUseLimitResponse getCloudConnectNetworkUseLimitResponse = new GetCloudConnectNetworkUseLimitResponse(); getCloudConnectNetworkUseLimitResponse.HttpResponse = context.HttpResponse; getCloudConnectNetworkUseLimitResponse.RequestId = context.StringValue("GetCloudConnectNetworkUseLimit.RequestId"); getCloudConnectNetworkUseLimitResponse.TotalAmount = context.IntegerValue("GetCloudConnectNetworkUseLimit.TotalAmount"); getCloudConnectNetworkUseLimitResponse.UsedAmount = context.IntegerValue("GetCloudConnectNetworkUseLimit.UsedAmount"); return getCloudConnectNetworkUseLimitResponse; } } }
45.65
129
0.793538
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-smartag/Smartag/Transform/V20180313/GetCloudConnectNetworkUseLimitResponseUnmarshaller.cs
1,826
C#
using Telerik.Core; using Telerik.Data.Core.Layouts; using Telerik.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace Telerik.UI.Xaml.Controls.Grid.View { internal abstract class DecorationLayer : SharedUILayer { /// <summary> /// Initializes a new instance of the <see cref="DecorationLayer" /> class. /// </summary> protected DecorationLayer() { } internal bool IsAlternateRow(ItemInfo info) { if (this.Owner == null) { return false; } if (this.Owner.AlternationStep == 0 || info.IsCollapsible) { return false; } int rowIndex = info.LayoutInfo.ChildLine - this.Owner.AlternationStartIndex; if (rowIndex < 0) { return false; } return rowIndex % this.Owner.AlternationStep == 0; } internal bool HasHorizontalLine(ItemInfo info) { if (this.Owner == null) { return false; } if (info.IsCollapsible) { return false; } if (info.LayoutInfo.ChildLine == 0 && this.Owner.Model.RowPool.Layout.TotalLineCount > 1) { return false; } return this.Owner.HasHorizontalGridLines; } internal bool IsFirstLine(ItemInfo info) { return info.LayoutInfo.ChildLine == 0 && this.Owner.Model.RowPool.Layout.TotalLineCount > 1; } internal bool IsLastLine(ItemInfo info) { return info.LayoutInfo.Line == this.Owner.Model.RowPool.Layout.VisibleLineCount - 1; } internal virtual void MakeVisible(LineDecorationModel element) { // TODO: pass only the UI representation rather than the model UIElement container = element.Container as UIElement; if (container != null) { container.ClearValue(UIElement.VisibilityProperty); } } internal virtual void Collapse(LineDecorationModel element) { // TODO: pass only the UI representation rather than the model UIElement container = element.Container as UIElement; if (container != null) { container.Visibility = Visibility.Collapsed; } } internal virtual bool HasDecorations(DecorationType decoratorElementType, ItemInfo itemInfo) { if (this.Owner == null) { return false; } switch (decoratorElementType) { case DecorationType.Row: if (this.HasRowFill(itemInfo)) { return true; } if (this.HasHorizontalLine(itemInfo)) { return true; } return this.Owner.HasHorizontalGridLines && this.IsLastLine(itemInfo); case DecorationType.Column: // no need of column decoration for the first line as the border is handled by the root Grid's Border if (itemInfo.LayoutInfo.Line == 0) { return false; } return (this.Owner.GridLinesVisibility & GridLinesVisibility.Vertical) == GridLinesVisibility.Vertical; } return false; } internal virtual object GenerateContainerForLineDecorator() { return null; } internal abstract void ApplyLineDecoratorProperties(LineDecorationModel lineDecorator, DecorationType decoratorElementType); internal abstract RadRect ArrangeLineDecorator(LineDecorationModel decorator, RadRect radRect); internal virtual void PrepareCellDecoration(GridCellModel cell) { } internal virtual void ArrangeCellDecoration(GridCellModel cell) { } private bool HasRowFill(ItemInfo info) { if (this.Owner.RowBackground != null) { return true; } if (this.IsAlternateRow(info)) { return true; } if (this.Owner.RowBackgroundSelector != null && !info.IsCollapsible) { return true; } return false; } } }
28.962733
132
0.527772
[ "Apache-2.0" ]
ChristianGutman/UI-For-UWP
Controls/Grid/Grid.UWP/View/Layers/DecorationLayer.cs
4,665
C#
using System; using System.Net; using System.IO; using Newtonsoft.Json; using RazorEngine; using RazorEngine.Templating; namespace JustFakeIt { public class HttpExpectation { public HttpRequestExpectation Request { get; set; } public HttpResponseExpectation Response { get; set; } public Func<HttpResponseExpectation> ResponseExpectationCallback { get; private set; } public HttpExpectation Returns(string expectedResult, WebHeaderCollection expectedHeaders = null) { Returns(HttpStatusCode.OK, expectedResult, expectedHeaders); return this; } public HttpExpectation Returns(object expectedResult, WebHeaderCollection expectedHeaders = null) { Returns(HttpStatusCode.OK, JsonConvert.SerializeObject(expectedResult), expectedHeaders); return this; } private string BuildAbsolutePath(string relativePath) { var absolutePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath); return absolutePath; } public HttpExpectation ReturnsFromFile(string relativePath, WebHeaderCollection expectedHeaders = null) { var response = File.ReadAllText(BuildAbsolutePath(relativePath)); Returns(HttpStatusCode.OK, response, expectedHeaders); return this; } public HttpExpectation ReturnsFromTemplate(string relativePath, object values, WebHeaderCollection expectedHeaders = null) { var absolutePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath); string compiled = Engine.Razor.RunCompile(File.ReadAllText(absolutePath), Guid.NewGuid().ToString(), null, values); Returns(HttpStatusCode.OK, compiled, expectedHeaders); return this; } public HttpExpectation Returns(HttpStatusCode expectedStatusCode, string someStringData, WebHeaderCollection expectedHeaders = null) { Response = new HttpResponseExpectation(expectedStatusCode, someStringData, expectedHeaders); return this; } public HttpExpectation Returns(HttpStatusCode expectedStatusCode, object expectedResult, WebHeaderCollection expectedHeaders = null) { Returns(expectedStatusCode, JsonConvert.SerializeObject(expectedResult), expectedHeaders); return this; } public HttpExpectation Callback(Func<HttpResponseExpectation> responseExpectationFunc) { ResponseExpectationCallback = responseExpectationFunc; return this; } public HttpExpectation WithHttpStatus(HttpStatusCode expectedStatusCode) { Response.StatusCode = expectedStatusCode; return this; } public HttpExpectation WithHeader(string name, string value) { Response.Headers.Add(name, value); return this; } public HttpExpectation RespondsIn(TimeSpan time) { Response.ResponseTime = time; return this; } public HttpExpectation WithPartialJsonMatching() { Request.BodyMatching = new PartialJsonMatching(); return this; } public HttpExpectation UseActualBodyMatching() { Request.BodyMatching = new AbsoluteBodyMatching(); return this; } } }
35.989796
140
0.656932
[ "Apache-2.0" ]
justeat/JustFakeIt
JustFakeIt/HttpExpectation.cs
3,529
C#
using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Storage; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Orleans.Indexing { /// <summary> /// To minimize the number of RPCs, we process index updates for each grain on the silo where the grain is active. To do this processing, each silo /// has one or more <see cref="IndexWorkflowQueueGrainService"/>s for each grain class, up to the number of hardware threads. A GrainService is a grain that /// belongs to a specific silo. /// + Each of these GrainServices has a queue of workflowRecords, which describe updates that must be propagated to indexes. Each workflowRecord contains /// the following information: /// - workflowID: grainID + a sequence number /// - memberUpdates: the updated values of indexed fields /// /// Ordinarily, these workflowRecords are for grains that are active on <see cref="IndexWorkflowQueueGrainService"/>'s silo. (This may not be true for /// short periods when a grain migrates to another silo or after the silo recovers from failure). /// /// + The <see cref="IndexWorkflowQueueGrainService"/> grain Q has a dictionary updatesOnWait is an in-memory dictionary that maps each grain G to the /// workflowRecords for G that are waiting for be updated. /// </summary> internal class IndexWorkflowQueueBase : IIndexWorkflowQueue { //the persistent state of IndexWorkflowQueue, including: // - doubly linked list of workflowRecordds // - the identity of the IndexWorkflowQueue GrainService protected IndexWorkflowQueueState queueState; //the tail of workflowRecords doubly linked list internal IndexWorkflowRecordNode _workflowRecordsTail; //the grain storage for the index workflow queue private volatile IGrainStorage StorageProvider; private int _queueSeqNum; private Type _grainInterfaceType; private string _grainTypeName; private bool HasAnyTotalIndex => GetHasAnyTotalIndex(); private bool? __hasAnyTotalIndex = null; private bool _isDefinedAsFaultTolerantGrain; private bool IsFaultTolerant => _isDefinedAsFaultTolerantGrain && HasAnyTotalIndex; private IIndexWorkflowQueueHandler __handler; private IIndexWorkflowQueueHandler Handler => InitWorkflowQueueHandler(); private int _isHandlerWorkerIdle; /// <summary> /// This lock is used to queue all the writes to the storage and do them in a single batch, i.e., group commit /// /// Works hand-in-hand with pendingWriteRequests and writeRequestIdGen. /// </summary> private AsyncLock _writeLock; /// <summary> /// Creates a unique ID for each write request to the storage. /// /// The values generated by this ID generator are used in pendingWriteRequests /// </summary> private int _writeRequestIdGen; /// <summary> /// All the write requests that are waiting behind write_lock are accumulated /// in this data structure, and all of them will be done at once. /// </summary> private HashSet<int> _pendingWriteRequests; public const int BATCH_SIZE = int.MaxValue; private SiloAddress _silo; private SiloIndexManager SiloIndexManager; private Lazy<GrainReference> _lazyParent; private GrainReference _recoveryGrainReference; internal IndexWorkflowQueueBase(SiloIndexManager siloIndexManager, Type grainInterfaceType, int queueSequenceNumber, SiloAddress silo, bool isDefinedAsFaultTolerantGrain, Func<GrainReference> parentFunc, GrainReference recoveryGrainReference = null) { queueState = new IndexWorkflowQueueState(); _grainInterfaceType = grainInterfaceType; _queueSeqNum = queueSequenceNumber; _grainTypeName = "Orleans.Indexing.IndexWorkflowQueue-" + IndexUtils.GetFullTypeName(_grainInterfaceType); _workflowRecordsTail = null; __handler = null; _isHandlerWorkerIdle = 1; _isDefinedAsFaultTolerantGrain = isDefinedAsFaultTolerantGrain; this._recoveryGrainReference = recoveryGrainReference; _writeLock = new AsyncLock(); _writeRequestIdGen = 0; _pendingWriteRequests = new HashSet<int>(); _silo = silo; SiloIndexManager = siloIndexManager; _lazyParent = new Lazy<GrainReference>(parentFunc, true); } private IIndexWorkflowQueueHandler InitWorkflowQueueHandler() => __handler = _lazyParent.Value.IsGrainService ? SiloIndexManager.GetGrainService<IIndexWorkflowQueueHandler>( IndexWorkflowQueueHandlerBase.CreateIndexWorkflowQueueHandlerGrainReference(SiloIndexManager, _grainInterfaceType, _queueSeqNum, _silo)) : SiloIndexManager.GrainFactory.GetGrain<IIndexWorkflowQueueHandler>(CreateIndexWorkflowQueuePrimaryKey(_grainInterfaceType, _queueSeqNum)); private async Task EnsureStorage() { if (this.StorageProvider == null) { using (await _writeLock.LockAsync()) { if (this.StorageProvider == null) // Make sure another thread didn't get it { var readGrainReference = this._recoveryGrainReference ?? _lazyParent.Value; this.StorageProvider = typeof(IndexWorkflowQueueGrainService).GetGrainStorage(this.SiloIndexManager.ServiceProvider); await this.StorageProvider.ReadStateAsync(_grainTypeName, readGrainReference, this.queueState); } } } } public async Task AddAllToQueue(Immutable<List<IndexWorkflowRecord>> workflowRecords) { await this.EnsureStorage(); // Note: this can be called with an empty enumeration, to just "wake up" the thread in FT recovery. List<IndexWorkflowRecord> newWorkflows = workflowRecords.Value; foreach (IndexWorkflowRecord newWorkflow in newWorkflows) { AddToQueueNonPersistent(newWorkflow); } InitiateWorkerThread(); await (IsFaultTolerant ? PersistState() : Task.CompletedTask); } public async Task AddToQueue(Immutable<IndexWorkflowRecord> workflow) { await this.EnsureStorage(); AddToQueueNonPersistent(workflow.Value); InitiateWorkerThread(); await (IsFaultTolerant ? PersistState() : Task.CompletedTask); } private void AddToQueueNonPersistent(IndexWorkflowRecord newWorkflow) { var newWorkflowNode = new IndexWorkflowRecordNode(newWorkflow); if (_workflowRecordsTail == null) //if the list is empty { _workflowRecordsTail = newWorkflowNode; queueState.State.WorkflowRecordsHead = newWorkflowNode; } else // otherwise append to the end of the list { _workflowRecordsTail.Append(newWorkflowNode, ref _workflowRecordsTail); } } public async Task RemoveAllFromQueue(Immutable<List<IndexWorkflowRecord>> workflowRecords) { await this.EnsureStorage(); List<IndexWorkflowRecord> newWorkflows = workflowRecords.Value; foreach (IndexWorkflowRecord newWorkflow in newWorkflows) { RemoveFromQueueNonPersistent(newWorkflow); } await (IsFaultTolerant ? PersistState() : Task.CompletedTask); } private void RemoveFromQueueNonPersistent(IndexWorkflowRecord newWorkflow) { for (var current = queueState.State.WorkflowRecordsHead; current != null; current = current.Next) { if (newWorkflow.Equals(current.WorkflowRecord)) { current.Remove(ref queueState.State.WorkflowRecordsHead, ref _workflowRecordsTail); return; } } } private void InitiateWorkerThread() { if (this.SiloIndexManager.InjectableCode.ShouldRunQueueThread(() => Interlocked.Exchange(ref _isHandlerWorkerIdle, 0) == 1)) { IndexWorkflowRecordNode punctuatedHead = AddPunctuationAt(BATCH_SIZE); Handler.HandleWorkflowsUntilPunctuation(punctuatedHead.AsImmutable()).Ignore(); } } private IndexWorkflowRecordNode AddPunctuationAt(int batchSize) { if (_workflowRecordsTail == null) throw new WorkflowIndexException("Adding a punctuation to an empty workflow queue is not possible."); var punctuationHead = queueState.State.WorkflowRecordsHead; if (punctuationHead.IsPunctuation) throw new WorkflowIndexException("The element at the head of workflow queue cannot be a punctuation."); if (batchSize == int.MaxValue) { var punctuation = _workflowRecordsTail.AppendPunctuation(ref _workflowRecordsTail); return punctuationHead; } var punctuationLoc = punctuationHead; for (int i = 1; i < batchSize && punctuationLoc.Next != null; ++i) { punctuationLoc = punctuationLoc.Next; } punctuationLoc.AppendPunctuation(ref _workflowRecordsTail); return punctuationHead; } private List<IndexWorkflowRecord> RemoveFromQueueUntilPunctuation(IndexWorkflowRecordNode from) { List<IndexWorkflowRecord> workflowRecords = new List<IndexWorkflowRecord>(); if (from != null && !from.IsPunctuation) { workflowRecords.Add(from.WorkflowRecord); } IndexWorkflowRecordNode tmp = from?.Next; while (tmp != null && !tmp.IsPunctuation) { workflowRecords.Add(tmp.WorkflowRecord); tmp = tmp.Next; tmp.Prev.Clean(); } if (tmp == null) { from.Remove(ref queueState.State.WorkflowRecordsHead, ref _workflowRecordsTail); } else { from.Next = tmp; tmp.Prev = from; from.Remove(ref queueState.State.WorkflowRecordsHead, ref _workflowRecordsTail); tmp.Remove(ref queueState.State.WorkflowRecordsHead, ref _workflowRecordsTail); } return workflowRecords; } private async Task PersistState() { //create a write-request ID, which is used for group commit int writeRequestId = ++_writeRequestIdGen; //add the write-request ID to the pending write requests _pendingWriteRequests.Add(writeRequestId); //wait before any previous write is done using (await _writeLock.LockAsync()) { // If the write request is not there, it was handled by another worker before we obtained the lock. if (_pendingWriteRequests.Contains(writeRequestId)) { //clear all pending write requests, as this attempt will do them all. _pendingWriteRequests.Clear(); //write the state back to the storage unconditionally var saveETag = this.queueState.ETag; try { this.queueState.ETag = StorageProviderUtils.ANY_ETAG; await StorageProvider.WriteStateAsync(_grainTypeName, _lazyParent.Value, this.queueState); } finally { if (this.queueState.ETag == StorageProviderUtils.ANY_ETAG) { this.queueState.ETag = saveETag; } } } } } private static Immutable<IndexWorkflowRecordNode> EmptyIndexWorkflowRecordNode = new Immutable<IndexWorkflowRecordNode>(null); public Task<Immutable<IndexWorkflowRecordNode>> GiveMoreWorkflowsOrSetAsIdle() { List<IndexWorkflowRecord> removedWorkflows = RemoveFromQueueUntilPunctuation(queueState.State.WorkflowRecordsHead); if (IsFaultTolerant) { //The task of removing the workflow record IDs from the grain runs in parallel with persisting the state. At this point, there //is a possibility that some workflow record IDs do not get removed from the indexable grains while the workflow record is removed //from the queue. This is fine, because having some dangling workflow IDs in some indexable grains is harmless. //TODO: add a garbage collector that runs once in a while and removes the dangling workflow IDs (i.e., the workflow IDs that exist in the // indexable grain, but its corresponding workflow record does not exist in the workflow queue. //Task.WhenAll( // RemoveWorkflowRecordsFromIndexableGrains(removedWorkflows), this.PersistState(//) ).Ignore(); } if (_workflowRecordsTail == null) { _isHandlerWorkerIdle = 1; return Task.FromResult(EmptyIndexWorkflowRecordNode); } else { _isHandlerWorkerIdle = 0; return Task.FromResult(AddPunctuationAt(BATCH_SIZE).AsImmutable()); } } private bool GetHasAnyTotalIndex() { if (!__hasAnyTotalIndex.HasValue) { __hasAnyTotalIndex = SiloIndexManager.IndexFactory.GetGrainIndexes(_grainInterfaceType).HasAnyTotalIndex; } return __hasAnyTotalIndex.Value; } public async Task<Immutable<List<IndexWorkflowRecord>>> GetRemainingWorkflowsIn(HashSet<Guid> activeWorkflowsSet) { await this.EnsureStorage(); var result = new List<IndexWorkflowRecord>(); for (var current = queueState.State.WorkflowRecordsHead; current != null && !current.IsPunctuation; current = current.Next) { if (activeWorkflowsSet.Contains(current.WorkflowRecord.WorkflowId)) { result.Add(current.WorkflowRecord); } } return result.AsImmutable(); } public Task Initialize(IIndexWorkflowQueue oldParentGrainService) => throw new NotSupportedException(); #region STATIC HELPER FUNCTIONS public static GrainReference CreateIndexWorkflowQueueGrainReference(SiloIndexManager siloIndexManager, Type grainInterfaceType, int queueSeqNum, SiloAddress siloAddress) => CreateGrainServiceGrainReference(siloIndexManager, grainInterfaceType, queueSeqNum, siloAddress); public static string CreateIndexWorkflowQueuePrimaryKey(Type grainInterfaceType, int queueSeqNum) => $"{IndexUtils.GetFullTypeName(grainInterfaceType)}-{queueSeqNum}"; private static GrainReference CreateGrainServiceGrainReference(SiloIndexManager siloIndexManager, Type grainInterfaceType, int queueSeqNum, SiloAddress siloAddress) => siloIndexManager.MakeGrainServiceGrainReference(IndexingConstants.INDEX_WORKFLOW_QUEUE_GRAIN_SERVICE_TYPE_CODE, CreateIndexWorkflowQueuePrimaryKey(grainInterfaceType, queueSeqNum), siloAddress); public static IIndexWorkflowQueue GetIndexWorkflowQueueFromGrainHashCode(SiloIndexManager siloIndexManager, Type grainInterfaceType, int grainHashCode, SiloAddress siloAddress) { int queueSeqNum = StorageProviderUtils.PositiveHash(grainHashCode, siloIndexManager.NumWorkflowQueuesPerInterface); var grainReference = CreateGrainServiceGrainReference(siloIndexManager, grainInterfaceType, queueSeqNum, siloAddress); return siloIndexManager.GetGrainService<IIndexWorkflowQueue>(grainReference); } #endregion STATIC HELPER FUNCTIONS } }
45.821429
184
0.637868
[ "MIT" ]
KSemenenko/Orleans.Indexing
src/Orleans.Indexing/Core/FaultTolerance/IndexWorkflowQueueBase.cs
16,679
C#
using Newtonsoft.Json; using System.Collections.Generic; using System.ComponentModel; namespace WalletWasabi.JsonConverters.Collections { public class DefaultValueStringSetAttribute : DefaultValueAttribute { public DefaultValueStringSetAttribute(string json) : base(JsonConvert.DeserializeObject<ISet<string>>(json)) { } } }
22.533333
68
0.807692
[ "MIT" ]
BTCparadigm/WalletWasabi
WalletWasabi/JsonConverters/Collections/DefaultValueStringSetAttribute.cs
338
C#
using System.Linq; using System.Net; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using Xunit; namespace UnitTests.Internal { public sealed class ErrorDocumentTests { // @formatter:wrap_array_initializer_style wrap_if_long [Theory] [InlineData(new[] { HttpStatusCode.UnprocessableEntity }, HttpStatusCode.UnprocessableEntity)] [InlineData(new[] { HttpStatusCode.UnprocessableEntity, HttpStatusCode.UnprocessableEntity }, HttpStatusCode.UnprocessableEntity)] [InlineData(new[] { HttpStatusCode.UnprocessableEntity, HttpStatusCode.Unauthorized }, HttpStatusCode.BadRequest)] [InlineData(new[] { HttpStatusCode.UnprocessableEntity, HttpStatusCode.BadGateway }, HttpStatusCode.InternalServerError)] // @formatter:wrap_array_initializer_style restore public void ErrorDocument_GetErrorStatusCode_IsCorrect(HttpStatusCode[] errorCodes, HttpStatusCode expected) { // Arrange var document = new ErrorDocument(errorCodes.Select(code => new Error(code))); // Act HttpStatusCode status = document.GetErrorStatusCode(); // Assert status.Should().Be(expected); } } }
40.225806
138
0.716119
[ "MIT" ]
3volutionsAG/JsonApiDotNetCore
test/UnitTests/Internal/ErrorDocumentTests.cs
1,247
C#
namespace GoodAI.BrainSimulator.Forms { partial class LicensesForm { /// <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(LicensesForm)); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.licenseList = new System.Windows.Forms.ListBox(); this.licenseText = new System.Windows.Forms.RichTextBox(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.licenseList); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.licenseText); this.splitContainer1.Size = new System.Drawing.Size(997, 603); this.splitContainer1.SplitterDistance = 223; this.splitContainer1.TabIndex = 0; // // licenseList // this.licenseList.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.licenseList.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.licenseList.FormattingEnabled = true; this.licenseList.ItemHeight = 16; this.licenseList.Location = new System.Drawing.Point(3, 3); this.licenseList.Name = "licenseList"; this.licenseList.Size = new System.Drawing.Size(217, 580); this.licenseList.TabIndex = 0; this.licenseList.SelectedIndexChanged += new System.EventHandler(this.licenseList_SelectedIndexChanged); // // licenseText // this.licenseText.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.licenseText.BackColor = System.Drawing.SystemColors.ControlLightLight; this.licenseText.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.licenseText.Location = new System.Drawing.Point(3, 3); this.licenseText.Name = "licenseText"; this.licenseText.ReadOnly = true; this.licenseText.Size = new System.Drawing.Size(764, 588); this.licenseText.TabIndex = 0; this.licenseText.Text = ""; this.licenseText.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.licenseText_LinkClicked); // // LicensesForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(997, 603); this.Controls.Add(this.splitContainer1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "LicensesForm"; this.Text = "Licensing Information"; this.Load += new System.EventHandler(this.LicensesForm_Load); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.ListBox licenseList; private System.Windows.Forms.RichTextBox licenseText; } }
48.846847
168
0.62394
[ "Apache-2.0" ]
GoodAI/BrainSimulator
Sources/Platform/BrainSimulator/Forms/LicensesForm.Designer.cs
5,424
C#
// // Transform Rotate // // Author : Alex Tuduran // Copyright : OmniSAR Technologies // // uncomment this to execute rotation while the game is not running //#define ___EXECUTE_IN_EDITOR___ using UnityEngine; namespace OmniSARTechnologies.Helper { #if ___EXECUTE_IN_EDITOR___ [ExecuteInEditMode] #endif // ___EXECUTE_IN_EDITOR___ public class TransformRotate : MonoBehaviour { public Vector3 eulerAnglesSpeed; private void Update() { transform.RotateAround(transform.position, Vector3.right, eulerAnglesSpeed.x * Time.deltaTime); transform.RotateAround(transform.position, Vector3.up, eulerAnglesSpeed.y * Time.deltaTime); transform.RotateAround(transform.position, Vector3.forward, eulerAnglesSpeed.z * Time.deltaTime); } } }
31.423077
109
0.718482
[ "MIT" ]
DeusIntra/Snowball-Fight
Assets/_Other Packages/OmniSARTechnologies/Common/Helper/Transforms/TransformRotate.cs
819
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.MSHTMLApi { ///<summary> /// DispatchInterface IHTMLCommentElement2 /// SupportByVersion MSHTML, 4 ///</summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class IHTMLCommentElement2 : IHTMLCommentElement { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IHTMLCommentElement2); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IHTMLCommentElement2(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IHTMLCommentElement2(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string data { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "data", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "data", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 length { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "length", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="offset">Int32 offset</param> /// <param name="count">Int32 Count</param> [SupportByVersionAttribute("MSHTML", 4)] public string substringData(Int32 offset, Int32 count) { object[] paramsArray = Invoker.ValidateParamsArray(offset, count); object returnItem = Invoker.MethodReturn(this, "substringData", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrstring">string bstrstring</param> [SupportByVersionAttribute("MSHTML", 4)] public void appendData(string bstrstring) { object[] paramsArray = Invoker.ValidateParamsArray(bstrstring); Invoker.Method(this, "appendData", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="offset">Int32 offset</param> /// <param name="bstrstring">string bstrstring</param> [SupportByVersionAttribute("MSHTML", 4)] public void insertData(Int32 offset, string bstrstring) { object[] paramsArray = Invoker.ValidateParamsArray(offset, bstrstring); Invoker.Method(this, "insertData", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="offset">Int32 offset</param> /// <param name="count">Int32 Count</param> [SupportByVersionAttribute("MSHTML", 4)] public void deleteData(Int32 offset, Int32 count) { object[] paramsArray = Invoker.ValidateParamsArray(offset, count); Invoker.Method(this, "deleteData", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="offset">Int32 offset</param> /// <param name="count">Int32 Count</param> /// <param name="bstrstring">string bstrstring</param> [SupportByVersionAttribute("MSHTML", 4)] public void replaceData(Int32 offset, Int32 count, string bstrstring) { object[] paramsArray = Invoker.ValidateParamsArray(offset, count, bstrstring); Invoker.Method(this, "replaceData", paramsArray); } #endregion #pragma warning restore } }
31.975248
175
0.67224
[ "MIT" ]
NetOffice/NetOffice
Source/MSHTML/DispatchInterfaces/IHTMLCommentElement2.cs
6,459
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using WalkingTec.Mvvm.Core.Extensions; namespace WalkingTec.Mvvm.Core { /// <summary> /// 单表增删改查VM的接口 /// </summary> /// <typeparam name="T">继承TopBasePoco的类</typeparam> public interface IBaseCRUDVM<out T> where T : TopBasePoco { T Entity { get; } /// <summary> /// 根据主键Id获取Entity /// </summary> /// <param name="id">主键Id</param> void SetEntityById(Guid id); /// <summary> /// 设置Entity /// </summary> /// <param name="entity">要设定的TopBasePoco</param> void SetEntity(object entity); /// <summary> /// 添加 /// </summary> void DoAdd(); /// <summary> /// 修改 /// </summary> void DoEdit(bool updateAllFields); /// <summary> /// 删除,对于TopBasePoco进行物理删除,对于PersistPoco把IsValid修改为false /// </summary> void DoDelete(); /// <summary> /// 彻底删除,对PersistPoco进行物理删除 /// </summary> void DoRealDelete(); /// <summary> /// 将源VM的上数据库上下文,Session,登录用户信息,模型状态信息,缓存信息等内容复制到本VM中 /// </summary> /// <param name="vm">复制的源</param> void CopyContext(BaseVM vm); /// <summary> /// 是否跳过基类的唯一性验证,批量导入的时候唯一性验证会由存储过程完成,不需要单独调用本类的验证方法 /// </summary> bool ByPassBaseValidation { get; set; } void Validate(); } /// <summary> /// 单表增删改查基类,所有单表操作的VM应该继承这个基类 /// </summary> /// <typeparam name="TModel">继承TopBasePoco的类</typeparam> public class BaseCRUDVM<TModel> : BaseVM, IBaseCRUDVM<TModel> where TModel : TopBasePoco { public TModel Entity { get; set; } public bool ByPassBaseValidation { get; set; } //保存读取时Include的内容 private List<Expression<Func<TModel, object>>> _toInclude { get; set; } /// <summary> /// 构造函数 /// </summary> public BaseCRUDVM() { //初始化Entity var ctor = typeof(TModel).GetConstructor(Type.EmptyTypes); Entity = ctor.Invoke(null) as TModel; //初始化VM中所有List<>的类 var lists = typeof(TModel).GetProperties().Where(x => x.PropertyType.IsGeneric(typeof(List<>))); foreach (var li in lists) { var gs = li.PropertyType.GetGenericArguments(); var newObj = Activator.CreateInstance(typeof(List<>).MakeGenericType(gs[0])); li.SetValue(Entity, newObj, null); } } public IQueryable<TModel> GetBaseQuery() { return DC.Set<TModel>(); } /// <summary> /// 设定添加和修改时对于重复数据的判断,子类进行相关操作时应重载这个函数 /// </summary> /// <returns>唯一性属性</returns> public virtual DuplicatedInfo<TModel> SetDuplicatedCheck() { return null; } /// <summary> /// 设定读取是Include的内容,子类进行相关操作时应重载这个函数 /// </summary> /// <param name="exps">需要关联的类</param> protected void SetInclude(params Expression<Func<TModel, object>>[] exps) { _toInclude = _toInclude ?? new List<Expression<Func<TModel, object>>>(); _toInclude.AddRange(exps); } /// <summary> /// 根据主键Id设定Entity /// </summary> /// <param name="id">主键Id</param> public void SetEntityById(Guid id) { this.Entity = GetById(id); } /// <summary> /// 设置Entity /// </summary> /// <param name="entity">要设定的TopBasePoco</param> public void SetEntity(object entity) { this.Entity = entity as TModel; } /// <summary> /// 根据主键获取Entity /// </summary> /// <param name="Id">主键Id</param> /// <returns>Entity</returns> public virtual TModel GetById(Guid Id) { TModel rv = null; //建立基础查询 var query = DC.Set<TModel>().AsQueryable(); //循环添加其他设定的Include if (_toInclude != null) { foreach (var item in _toInclude) { query = query.Include(item); } } //获取数据 rv = query.Where(x => x.ID == Id).SingleOrDefault(); if (rv == null) { throw new Exception("数据不存在"); } //如果TopBasePoco有关联的附件,则自动Include 附件名称 var fa = typeof(TModel).GetProperties().Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); foreach (var f in fa) { var fname = DC.GetFKName2<TModel>(f.Name); var fid = typeof(TModel).GetProperty(fname).GetValue(rv) as Guid?; var file = DC.Set<FileAttachment>().Where(x => x.ID == fid).Select(x => new FileAttachment { ID = x.ID, CreateBy = x.CreateBy, CreateTime = x.CreateTime, UpdateBy = x.UpdateBy, UpdateTime = x.UpdateTime, UploadTime = x.UploadTime, FileExt = x.FileExt, FileName = x.FileName, Length = x.Length, GroupName = x.GroupName, IsTemprory = x.IsTemprory, Path = x.Path, SaveFileMode = x.SaveFileMode }).FirstOrDefault(); rv.SetPropertyValue(f.Name, file); } return rv; } /// <summary> /// 添加,进行默认的添加操作。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoAdd() { var pros = typeof(TModel).GetProperties(); //将所有TopBasePoco的属性赋空值,防止添加关联的重复内容 if (typeof(TModel) != typeof(FileAttachment)) { foreach (var pro in pros) { if (pro.PropertyType.GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) { pro.SetValue(Entity, null); } } } //自动设定添加日期和添加人 if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = Entity as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(PersistPoco))) { (Entity as PersistPoco).IsValid = true; } #region 更新子表 foreach (var pro in pros) { //找到类型为List<xxx>的字段 if (pro.PropertyType.GenericTypeArguments.Count() > 0) { //获取xxx的类型 var ftype = pro.PropertyType.GenericTypeArguments.First(); //如果xxx继承自TopBasePoco if (ftype.IsSubclassOf(typeof(BasePoco))) { //界面传过来的子表数据 IEnumerable<TopBasePoco> list = pro.GetValue(Entity) as IEnumerable<BasePoco>; if (list != null && list.Count() > 0) { string fkname = DC.GetFKName<TModel>(pro.Name); PropertyInfo[] itemPros = ftype.GetProperties(); bool found = false; foreach (var newitem in list) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(newitem, null); } if (!string.IsNullOrEmpty(fkname)) { if (itempro.Name.ToLower() == fkname.ToLower()) { itempro.SetValue(newitem, Entity.ID); found = true; } } } } //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 if (found == false) { continue; } //循环页面传过来的子表数据,自动设定添加日期和添加人 foreach (var newitem in list) { var subtype = newitem.GetType(); BasePoco ent = newitem as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } } } } } #endregion //添加数据 DC.Set<TModel>().Add(Entity); //删除不需要的附件 if(DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } DC.SaveChanges(); } /// <summary> /// 修改,进行默认的修改操作。子类如有自定义操作应重载本函数 /// </summary> /// <param name="updateAllFields">为true时,框架会更新当前Entity的全部值,为false时,框架会检查Request.Form里的key,只更新表单提交的字段</param> public virtual void DoEdit(bool updateAllFields = false) { //自动设定修改日期和修改人 if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = Entity as BasePoco; if (ent.UpdateTime == null) { ent.UpdateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.UpdateBy)) { ent.UpdateBy = LoginUserInfo?.ITCode; } } var pros = typeof(TModel).GetProperties(); #region 更新子表 foreach (var pro in pros) { //找到类型为List<xxx>的字段 if (pro.PropertyType.GenericTypeArguments.Count() > 0) { //获取xxx的类型 var ftype = pro.PropertyType.GenericTypeArguments.First(); //如果xxx继承自TopBasePoco if (ftype.IsSubclassOf(typeof(TopBasePoco))) { //界面传过来的子表数据 if (pro.GetValue(Entity) is IEnumerable<TopBasePoco> list && list.Count() > 0) { //获取外键字段名称 string fkname = DC.GetFKName<TModel>(pro.Name); PropertyInfo[] itemPros = ftype.GetProperties(); bool found = false; foreach (var newitem in list) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(newitem, null); } if (!string.IsNullOrEmpty(fkname)) { if (itempro.Name.ToLower() == fkname.ToLower()) { itempro.SetValue(newitem, Entity.ID); found = true; } } } } //如果没有找到相应的外建字段,则可能是多对多的关系,或者做了特殊的设定,这种情况框架无法支持,直接退出本次循环 if (found == false) { continue; } //循环页面传过来的子表数据,将关联到TopBasePoco的字段设为null,并且把外键字段的值设定为主表ID foreach (var newitem in list) { var subtype = newitem.GetType(); if (subtype.IsSubclassOf(typeof(BasePoco))) { BasePoco ent = newitem as BasePoco; if (ent.UpdateTime == null) { ent.UpdateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.UpdateBy)) { ent.UpdateBy = LoginUserInfo?.ITCode; } } foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(newitem, null); } if (!string.IsNullOrEmpty(fkname)) { if (itempro.Name.ToLower() == fkname.ToLower()) { itempro.SetValue(newitem, Entity.ID); found = true; } } } } TModel _entity = null; //打开新的数据库联接,获取数据库中的主表和子表数据 using (var ndc = DC.CreateNew()) { _entity = ndc.Set<TModel>().Include(pro.Name).AsNoTracking().Where(x => x.ID == Entity.ID).FirstOrDefault(); } //比较子表原数据和新数据的区别 IEnumerable<TopBasePoco> toadd = null; IEnumerable<TopBasePoco> toremove = null; IEnumerable<TopBasePoco> data = _entity.GetType().GetProperty(pro.Name).GetValue(_entity) as IEnumerable<TopBasePoco>; Utils.CheckDifference(data, list, out toremove, out toadd); //设定子表应该更新的字段 List<string> setnames = new List<string>(); foreach (var field in FC.Keys) { if (field.StartsWith("Entity." + pro.Name + "[0].")) { string name = field.Replace("Entity." + pro.Name + "[0].", ""); if (name != "UpdateTime" && name != "UpdateBy") { setnames.Add(name); } } } //前台传过来的数据 foreach (var newitem in list) { //数据库中的数据 foreach (var item in data) { //需要更新的数据 if (newitem.ID == item.ID) { dynamic i = newitem; var newitemType = item.GetType(); foreach (var itempro in itemPros) { if (!itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco)) && setnames.Contains(itempro.Name)) { if (itempro.Name != "ID") { DC.UpdateProperty(i, itempro.Name); } } } DC.UpdateProperty(i, "UpdateTime"); DC.UpdateProperty(i, "UpdateBy"); } } } //需要删除的数据 foreach (var item in toremove) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(item, null); } } dynamic i = item; DC.DeleteEntity(i); } //需要添加的数据 foreach (var item in toadd) { if (item.GetType().IsSubclassOf(typeof(BasePoco))) { BasePoco ent = item as BasePoco; if (ent.CreateTime == null) { ent.CreateTime = DateTime.Now; } if (string.IsNullOrEmpty(ent.CreateBy)) { ent.CreateBy = LoginUserInfo?.ITCode; } } DC.AddEntity(item); } } else if (FC.Keys.Contains("Entity." + pro.Name + ".DONOTUSECLEAR") || (pro.GetValue(Entity) is IEnumerable<TopBasePoco> list2 && list2?.Count() == 0)) { PropertyInfo[] itemPros = ftype.GetProperties(); var _entity = DC.Set<TModel>().Include(pro.Name).AsNoTracking().Where(x => x.ID == Entity.ID).FirstOrDefault(); if (_entity != null) { IEnumerable<TopBasePoco> removeData = _entity.GetType().GetProperty(pro.Name).GetValue(_entity) as IEnumerable<TopBasePoco>; foreach (var item in removeData) { foreach (var itempro in itemPros) { if (itempro.PropertyType.IsSubclassOf(typeof(TopBasePoco))) { itempro.SetValue(item, null); } } dynamic i = item; DC.DeleteEntity(i); } } } } } } #endregion if (updateAllFields == false) { foreach (var field in FC.Keys) { if (field.StartsWith("Entity.") && !field.Contains("[")) { string name = field.Replace("Entity.", ""); if (name != "UpdateTime" && name != "UpdateBy") { try { DC.UpdateProperty(Entity, name); } catch (Exception) { } } } } } else { DC.UpdateEntity(Entity); } DC.SaveChanges(); //删除不需要的附件 if (DeletedFileIds != null) { foreach (var item in DeletedFileIds) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } } /// <summary> /// 删除,进行默认的删除操作。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoDelete() { //如果是PersistPoco,则把IsValid设为false,并不进行物理删除 if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(PersistPoco))) { (Entity as PersistPoco).IsValid = false; (Entity as PersistPoco).UpdateTime = DateTime.Now; (Entity as PersistPoco).UpdateBy = LoginUserInfo?.ITCode; DC.UpdateEntity(Entity); try { DC.SaveChanges(); } catch (DbUpdateException) { MSD.AddModelError("", "数据使用中,无法删除"); } } //如果是普通的TopBasePoco,则进行物理删除 else if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(TopBasePoco))) { DoRealDelete(); } } /// <summary> /// 物理删除,对于普通的TopBasePoco和Delete操作相同,对于PersistPoco则进行真正的删除。子类如有自定义操作应重载本函数 /// </summary> public virtual void DoRealDelete() { try { List<Guid> fileids = new List<Guid>(); var pros = typeof(TModel).GetProperties(); //如果包含附件,则先删除附件 var fa = pros.Where(x => x.PropertyType == typeof(FileAttachment)).ToList(); foreach (var f in fa) { if (f.GetValue(Entity) is FileAttachment file) { fileids.Add(file.ID); f.SetValue(Entity, null); } } DC.DeleteEntity(Entity); DC.SaveChanges(); foreach (var item in fileids) { FileAttachmentVM ofa = new FileAttachmentVM(); ofa.CopyContext(this); ofa.SetEntityById(item); ofa.DoDelete(); } } catch (Exception) { MSD.AddModelError("", "数据使用中,无法删除"); } } /// <summary> /// 创建重复数据信息 /// </summary> /// <param name="FieldExps">重复数据信息</param> /// <returns>重复数据信息</returns> protected DuplicatedInfo<TModel> CreateFieldsInfo(params DuplicatedField<TModel>[] FieldExps) { DuplicatedInfo<TModel> d = new DuplicatedInfo<TModel>(); d.AddGroup(FieldExps); return d; } /// <summary> /// 创建一个简单重复数据信息 /// </summary> /// <param name="FieldExp">重复数据的字段</param> /// <returns>重复数据信息</returns> public static DuplicatedField<TModel> SimpleField(Expression<Func<TModel, object>> FieldExp) { return new DuplicatedField<TModel>(FieldExp); } /// <summary> /// 创建一个关联到其他表数组中数据的重复信息 /// </summary> /// <typeparam name="V">关联表类</typeparam> /// <param name="MiddleExp">指向关联表类数组的Lambda</param> /// <param name="FieldExps">指向最终字段的Lambda</param> /// <returns>重复数据信息</returns> public static DuplicatedField<TModel> SubField<V>(Expression<Func<TModel, List<V>>> MiddleExp, params Expression<Func<V, object>>[] FieldExps) { return new ComplexDuplicatedField<TModel, V>(MiddleExp, FieldExps); } /// <summary> /// 验证数据,默认验证重复数据。子类如需要其他自定义验证,则重载这个函数 /// </summary> /// <returns>验证结果</returns> public override void Validate() { //验证多语言数据 if (ByPassBaseValidation == false) { //验证重复数据 ValidateDuplicateData(); } } /// <summary> /// 验证重复数据 /// </summary> protected void ValidateDuplicateData() { //获取设定的重复字段信息 var checkCondition = SetDuplicatedCheck(); if (checkCondition != null && checkCondition.Groups.Count > 0) { //生成基础Query var baseExp = DC.Set<TModel>().AsQueryable(); var modelType = typeof(TModel); ParameterExpression para = Expression.Parameter(modelType, "tm"); //循环所有重复字段组 foreach (var group in checkCondition.Groups) { List<Expression> conditions = new List<Expression>(); //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 MemberExpression idLeft = Expression.Property(para, "Id"); ConstantExpression idRight = Expression.Constant(Entity.ID); BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); conditions.Add(idNotEqual); List<PropertyInfo> props = new List<PropertyInfo>(); //在每个组中循环所有字段 foreach (var field in group.Fields) { Expression exp = field.GetExpression(Entity, para); if (exp != null) { conditions.Add(exp); } //将字段名保存,为后面生成错误信息作准备 props.AddRange(field.GetProperties()); } int count = 0; if (conditions.Count > 1) { //循环添加条件并生成Where语句 Expression conExp = conditions[0]; for (int i = 1; i < conditions.Count; i++) { conExp = Expression.And(conExp, conditions[i]); } MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { modelType }, baseExp.Expression, Expression.Lambda<Func<TModel, bool>>(conExp, new ParameterExpression[] { para })); var result = baseExp.Provider.CreateQuery(whereCallExpression); foreach (var res in result) { count++; } } if (count > 0) { //循环拼接所有字段名 string AllName = ""; foreach (var prop in props) { string name = PropertyHelper.GetPropertyDisplayName(prop); AllName += name + ","; } if (AllName.EndsWith(",")) { AllName = AllName.Remove(AllName.Length - 1); } //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 if (props.Count == 1) { MSD.AddModelError(GetValidationFieldName(props[0])[0], AllName + "字段重复"); } //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 else if (props.Count > 1) { MSD.AddModelError(GetValidationFieldName(props.First())[0], AllName + "字段组合重复"); } } } } } /// <summary> /// 根据属性信息获取验证字段名 /// </summary> /// <param name="pi">属性信息</param> /// <returns>验证字段名称数组,用于ValidationResult</returns> private string[] GetValidationFieldName(PropertyInfo pi) { return new[] { "Entity." + pi.Name }; } } }
39.469737
174
0.388139
[ "MIT" ]
ganmkTrue/WalkingTec.Mvvm
src/WalkingTec.Mvvm.Core/BaseCRUDVM.cs
32,599
C#
//********************************************************************* //xCAD //Copyright(C) 2020 Xarial Pty Limited //Product URL: https://www.xcad.net //License: https://xcad.xarial.com/license/ //********************************************************************* using System; namespace Xarial.XCad.UI.PropertyPage.Enums { [Flags] public enum NumberBoxStyle_e { None = 0, ComboEditBox = 1, EditBoxReadOnly = 2, AvoidSelectionText = 4, NoScrollArrows = 8, Slider = 16, Thumbwheel = 32, SuppressNotifyWhileTracking = 64 } }
25.458333
72
0.471358
[ "MIT" ]
jonnypjohnston/Xarial-xcad
src/Base/UI/PropertyPage/Enums/NumberBoxStyle_e.cs
613
C#
// // CS0659ClassOverrideEqualsWithoutGetHashCode.cs // // Author: // Ji Kun <jikun.nus@gmail.com> // // Copyright (c) 2013 Ji Kun <jikun.nus@gmail.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 NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Refactoring; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [IssueDescription("CS0659: Class overrides Object.Equals but not Object.GetHashCode.", Description = "If two objects are equal then they must both have the same hash code", Category = IssueCategories.CompilerWarnings, Severity = Severity.Warning, PragmaWarning = 1717, AnalysisDisableKeyword = "CSharpWarnings::CS0659")] public class CS0659ClassOverrideEqualsWithoutGetHashCode : GatherVisitorCodeIssueProvider { protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context) { return new GatherVisitor(context, this); } class GatherVisitor : GatherVisitorBase<CS0659ClassOverrideEqualsWithoutGetHashCode> { public GatherVisitor(BaseRefactoringContext ctx, CS0659ClassOverrideEqualsWithoutGetHashCode issueProvider) : base (ctx, issueProvider) { } public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration(methodDeclaration); var resolvedResult = ctx.Resolve(methodDeclaration) as MemberResolveResult; if (resolvedResult == null) return; var method = resolvedResult.Member as IMethod; if (method == null || !method.Name.Equals("Equals") || ! method.IsOverride) return; if (methodDeclaration.Parameters.Count != 1) return; if (!method.Parameters.Single().Type.FullName.Equals("System.Object")) return; var classDeclration = method.DeclaringTypeDefinition; if (classDeclration == null) return; List<IMethod> getHashCode = new List<IMethod>(); var methods = classDeclration.GetMethods(); foreach (var m in methods) { if (m.Name.Equals("GetHashCode")) { getHashCode.Add(m); } } if (!getHashCode.Any()) { AddIssue(ctx, methodDeclaration); return; } else if (getHashCode.Any(f => (f.IsOverride && f.ReturnType.IsKnownType(KnownTypeCode.Int32)))) { return; } AddIssue(ctx, methodDeclaration); } private void AddIssue(BaseRefactoringContext ctx, AstNode node) { var getHashCode = new MethodDeclaration(); getHashCode.Name = "GetHashCode"; getHashCode.Modifiers = Modifiers.Public; getHashCode.Modifiers |= Modifiers.Override; getHashCode.ReturnType = new PrimitiveType("int"); var blockStatement = new BlockStatement(); var invocationExpression = new InvocationExpression(new MemberReferenceExpression(new BaseReferenceExpression(),"GetHashCode")); var returnStatement = new ReturnStatement(invocationExpression); blockStatement.Add(returnStatement); getHashCode.Body = blockStatement; AddIssue(new CodeIssue( (node as MethodDeclaration).NameToken, ctx.TranslateString("If two objects are equal then they must both have the same hash code"), new CodeAction( ctx.TranslateString("Override GetHashCode"), script => { script.InsertAfter(node, getHashCode); }, node ))); } } } }
35.664
138
0.739794
[ "MIT" ]
Jenkin0603/myvim
bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Custom/CompilerErrors/CS0659OverrideEqualWithoutGetHashCode.cs
4,458
C#
using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.ShaderGraph.Drawing.Inspector.PropertyDrawers { [SGPropertyDrawer(typeof(Color))] class ColorPropertyDrawer : IPropertyDrawer { internal delegate void ValueChangedCallback(Color newValue); internal VisualElement CreateGUI( ValueChangedCallback valueChangedCallback, Color fieldToDraw, string labelName, out VisualElement propertyColorField, int indentLevel = 0) { var colorField = new ColorField { value = fieldToDraw, showEyeDropper = false, hdr = false }; if (valueChangedCallback != null) { colorField.RegisterValueChangedCallback(evt => { valueChangedCallback((Color)evt.newValue); }); } propertyColorField = colorField; var defaultRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel)); defaultRow.Add(propertyColorField); return defaultRow; } public Action inspectorUpdateDelegate { get; set; } public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute) { return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] { newValue }), (Color)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } } }
35.734694
121
0.65791
[ "MIT" ]
PULSAR2105/Boids-Bug
Library/PackageCache/com.unity.shadergraph@12.1.1/Editor/Drawing/Inspector/PropertyDrawers/ColorPropertyDrawer.cs
1,751
C#
using System; using System.Linq; using Lamar; using LamarCodeGeneration.Util; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Jasper.Http { public static class EndpointBuilderExtensions { // TODO -- do something to let you chain routing configuration // here later // TODO -- might want an option to add IConfiguration or Hosting options too /// <summary> /// Add Jasper HTTP endpoint routes /// </summary> /// <param name="builder"></param> public static void MapJasperEndpoints(this IEndpointRouteBuilder builder, Action<JasperHttpOptions> configure = null) { builder.DataSources.Add(new JasperRouteEndpointSource((IContainer) builder.ServiceProvider, configure)); } /// <summary> /// Configure the Jasper HTTP routing /// </summary> /// <param name="extensions"></param> /// <param name="configure"></param> /// <returns></returns> public static void ConfigureHttp(this IExtensions extensions, Action<JasperHttpOptions> configure) { var extension = extensions.GetRegisteredExtension<JasperHttpExtension>(); if (extension == null) { extensions.Include<JasperHttpExtension>(); extension = extensions.GetRegisteredExtension<JasperHttpExtension>(); } configure(extension.Options); } internal class JasperHttpStartup : IStartup { public Action<JasperHttpOptions> Customization { get; set; } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(x => x.MapJasperEndpoints(Customization)); } public IServiceProvider ConfigureServices(IServiceCollection services) { return new Container(services); } } } }
32.584615
125
0.627951
[ "MIT" ]
CodingGorilla/jasper
src/Jasper.Http/EndpointBuilderExtensions.cs
2,118
C#
/* Copyright 2017 Coin Foundry (coinfoundry.org) Authors: Oliver Weichhold (oliver@weichhold.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 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; namespace Miningcore.Persistence.Model { public class Share { public string PoolId { get; set; } public ulong BlockHeight { get; set; } public string Miner { get; set; } public string Worker { get; set; } public string UserAgent { get; set; } public double Difficulty { get; set; } public double NetworkDifficulty { get; set; } public string IpAddress { get; set; } public string Source { get; set; } public DateTime Created { get; set; } public DateTime Accepted { get; set; } } }
43.075
103
0.731863
[ "MIT" ]
FishyJoel/miningcore
src/Miningcore/Persistence/Model/Share.cs
1,723
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ISerializationManager.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Runtime.Serialization { using System; using System.Collections.Generic; /// <summary> /// Manager which is responsible for discovering what fields and properties of an object should be serialized. /// </summary> public interface ISerializationManager { /// <summary> /// Occurs when the cache for a specific type has been invalidated. /// </summary> event EventHandler<CacheInvalidatedEventArgs> CacheInvalidated; /// <summary> /// Warmups the specified type by calling all the methods for the specified type. /// </summary> /// <param name="type">The type.</param> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> void Warmup(Type type); /// <summary> /// Clears the specified type from cache so it will be evaluated. /// </summary> /// <param name="type">The type.</param> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> void Clear(Type type); /// <summary> /// Gets the fields to serialize for the specified object. /// </summary> /// <param name="type">The type.</param> /// <returns>The list of fields to serialize.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetFieldsToSerialize(Type type); /// <summary> /// Gets the Catel properties to serialize for the specified object. /// </summary> /// <param name="type">The type.</param> /// <returns>The list of properties to serialize.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetCatelPropertiesToSerialize(Type type); /// <summary> /// Gets the regular properties to serialize for the specified object. /// </summary> /// <param name="type">The type.</param> /// <returns>The list of properties to serialize.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetRegularPropertiesToSerialize(Type type); /// <summary> /// Gets the catel property names. /// </summary> /// <param name="type">Type of the model.</param> /// <param name="includeModelBaseProperties">if set to <c>true</c>, also include model base properties.</param> /// <returns>A hash set containing the Catel property names.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> HashSet<string> GetCatelPropertyNames(Type type, bool includeModelBaseProperties = false); /// <summary> /// Gets the catel properties. /// </summary> /// <param name="type">Type of the model.</param> /// <param name="includeModelBaseProperties">if set to <c>true</c>, also include model base properties.</param> /// <returns>A hash set containing the Catel properties.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetCatelProperties(Type type, bool includeModelBaseProperties = false); /// <summary> /// Gets the regular property names. /// </summary> /// <param name="type">Type of the model.</param> /// <returns>A hash set containing the regular property names.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> HashSet<string> GetRegularPropertyNames(Type type); /// <summary> /// Gets the regular properties. /// </summary> /// <param name="type">Type of the model.</param> /// <returns>A hash set containing the regular properties.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetRegularProperties(Type type); /// <summary> /// Gets the field names. /// </summary> /// <param name="type">Type of the model.</param> /// <returns>A hash set containing the field names.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> HashSet<string> GetFieldNames(Type type); /// <summary> /// Gets the fields. /// </summary> /// <param name="type">Type of the model.</param> /// <returns>A hash set containing the fields.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> Dictionary<string, MemberMetadata> GetFields(Type type); /// <summary> /// Gets the serializer modifiers for the specified type. /// <para /> /// Note that the order is important because the modifiers will be called in the returned order during serialization /// and in reversed order during deserialization. /// </summary> /// <param name="type">The type.</param> /// <returns>An array containing the modifiers. Never <c>null</c>, but can be an empty array.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> ISerializerModifier[] GetSerializerModifiers(Type type); /// <summary> /// Adds the serializer modifier for a specific type. /// </summary> /// <param name="type">The type.</param> /// <param name="serializerModifierType">Type of the serializer modifier.</param> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="serializerModifierType"/> is <c>null</c>.</exception> void AddSerializerModifier(Type type, Type serializerModifierType); /// <summary> /// Removes the serializer modifier for a specific type. /// </summary> /// <param name="type">The type.</param> /// <param name="serializerModifierType">Type of the serializer modifier.</param> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="serializerModifierType"/> is <c>null</c>.</exception> void RemoveSerializerModifier(Type type, Type serializerModifierType); } }
51.807143
125
0.608576
[ "MIT" ]
14632791/Catel
src/Catel.Core/Runtime/Serialization/Interfaces/ISerializationManager.cs
7,255
C#
/* * Copyright 2018 JDCLOUD.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. * * Live-Video * 直播管理API * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; using JDCloudSDK.Live.Model; namespace JDCloudSDK.Live.Apis { /// <summary> /// 查询在线流列表 /// </summary> public class DescribeDomainOnlineStreamResult : JdcloudResult { ///<summary> /// StreamList ///</summary> public List<PublishOnlineStreamResultData> StreamList{ get; set; } ///<summary> /// 流数量 ///</summary> public int? Total{ get; set; } } }
25.215686
76
0.674184
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Live/Apis/DescribeDomainOnlineStreamResult.cs
1,314
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Axe.Windows.Core.Bases; using Axe.Windows.Desktop.Types; using Axe.Windows.Telemetry; using Axe.Windows.Win32; using System; using System.Collections.Generic; using System.Threading; using UIAutomationClient; namespace Axe.Windows.Desktop.UIAutomation.EventHandlers { /// <summary> /// Maintain the AutomationEvent handlers for UI interaction /// since different sets of event handlers can be created for each purpose, each factory keeps its own copy of CUIAutomation object. /// it will be released at disposal. /// </summary> public class EventListenerFactory:IDisposable { public FocusChangedEventListener EventListenerFocusChanged { get; private set; } public StructureChangedEventListener EventListenerStructureChanged { get; private set; } public PropertyChangedEventListener EventListenerPropertyChanged { get; private set; } public ChangesEventListener EventListenerChanges { get; private set; } public NotificationEventListener EventListenerNotification { get; private set; } public TextEditTextChangedEventListener EventListenerTextEditTextChanged { get; private set; } public ActiveTextPositionChangedEventListener EventListenerActiveTextPositionChanged { get; private set; } public Dictionary<int,EventListener> EventListeners { get; private set; } public TreeScope Scope { get; private set; } public CUIAutomation UIAutomation { get; private set; } public CUIAutomation8 UIAutomation8 { get; private set; } private readonly A11yElement RootElement; const int ThreadExitGracePeriod = 2; // 2 seconds #region Message Processing part /// <summary> /// Message Queue to keep the request from callers on other thread(s) /// </summary> private Queue<EventListenerFactoryMessage> _msgQueue = new Queue<EventListenerFactoryMessage>(); private Thread _threadBackground; private AutoResetEvent _autoEventInit; // Event used to allow background thread to take any required initialization action. private AutoResetEvent _autoEventMsg; // Event used to notify the background thread that action is required. private AutoResetEvent _autoEventFinish; // Event used to notify the end of worker thread /// <summary> /// Start a worker thread to handle UIAutomation request on a dedicated thread /// </summary> private void StartWorkerThread() { // This sample doesn't expect to enter here with a background thread already initialized. if (_threadBackground != null) { return; } _autoEventFinish = new AutoResetEvent(false); // The main thread will notify the background thread later when it's time to close down. _autoEventMsg = new AutoResetEvent(false); // Create the background thread, and wait until it's ready to start working. _autoEventInit = new AutoResetEvent(false); ThreadStart threadStart = new ThreadStart(ProcessMessageQueue); _threadBackground = new Thread(threadStart); _threadBackground.SetApartmentState(ApartmentState.MTA); // The event handler must run on an MTA thread. _threadBackground.Start(); _autoEventInit.WaitOne(); } /// <summary> /// Worker method for private thread to process Message Queue /// </summary> private void ProcessMessageQueue() { this.UIAutomation = new CUIAutomation(); // CUIAutomation8 was introduced in Windows 8, so don't try it on Windows 7. // Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/hh448746(v=vs.85).aspx?f=255&MSPPError=-2147217396 if (!Win32Helper.IsWindows7()) { this.UIAutomation8 = new CUIAutomation8(); } _autoEventInit.Set(); // fCloseDown will be set true when the thread is to close down. bool fCloseDown = false; while (!fCloseDown) { // Wait here until we're told we have some work to do. _autoEventMsg.WaitOne(); while (true) { EventListenerFactoryMessage msgData; // Note that none of the queue or message related action here is specific to UIA. // Rather it is only a means for the main UI thread and the background MTA thread // to communicate. // Get a message from the queue of action-related messages. lock (_msgQueue) { if(_msgQueue.Count != 0) { msgData = _msgQueue.Dequeue(); } else { break; } } switch(msgData.MessageType) { case EventListenerFactoryMessageType.FinishThread: // The main UI thread is telling this background thread to close down. fCloseDown = true; break; case EventListenerFactoryMessageType.RegisterEventListener: RegisterEventListener(msgData); break; case EventListenerFactoryMessageType.UnregisterEventListener: UnregisterEventListener(msgData); break; case EventListenerFactoryMessageType.UnregisterAllEventListeners: UnregisterAllEventListener(); break; } msgData.Processed(); } } _autoEventFinish.Set(); } private void UnregisterAllEventListener() { #pragma warning disable CA2000 // Call IDisposeable.Dispose() /// Need to find out a way to handle UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_AutomationFocusChangedEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_StructureChangedEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_AutomationPropertyChangedEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_NotificationEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_TextEdit_TextChangedEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_ActiveTextPositionChangedEventId }); UnregisterEventListener(new EventListenerFactoryMessage { EventId = EventType.UIA_ChangesEventId }); #pragma warning restore CA2000 HandleUIAutomationEventMessage listener = null; try { foreach (var e in this.EventListeners.Values) { listener = e.ListenEventMessage; e.Dispose(); } this.EventListeners.Clear(); if (listener != null) { #pragma warning disable CA2000 // Call IDisposable.Dispose() var m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Succeeded to unregister all event listeners.") }; listener(m); } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) { e.ReportException(); #pragma warning disable CA2000 // Call IDisposable.Dispose() var m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", $"Failed to unregister all listeners: {e.Message}") }; listener(m); } #pragma warning restore CA1031 // Do not catch general exception types } /// <summary> /// Process Unregister event message /// </summary> /// <param name="msgData"></param> private void UnregisterEventListener(EventListenerFactoryMessage msgData) { HandleUIAutomationEventMessage listener = null; try { switch (msgData.EventId) { case EventType.UIA_AutomationFocusChangedEventId: if (this.EventListenerFocusChanged != null) { listener = this.EventListenerFocusChanged.ListenEventMessage; this.EventListenerFocusChanged.Dispose(); this.EventListenerFocusChanged = null; } break; case EventType.UIA_StructureChangedEventId: if (this.EventListenerStructureChanged != null) { listener = this.EventListenerStructureChanged.ListenEventMessage; this.EventListenerStructureChanged.Dispose(); this.EventListenerStructureChanged = null; } break; case EventType.UIA_AutomationPropertyChangedEventId: if (this.EventListenerPropertyChanged != null) { listener = this.EventListenerPropertyChanged.ListenEventMessage; this.EventListenerPropertyChanged.Dispose(); this.EventListenerPropertyChanged = null; } break; case EventType.UIA_TextEdit_TextChangedEventId: if (this.EventListenerTextEditTextChanged != null) { listener = this.EventListenerTextEditTextChanged.ListenEventMessage; this.EventListenerTextEditTextChanged.Dispose(); this.EventListenerTextEditTextChanged = null; } break; case EventType.UIA_ChangesEventId: if (this.EventListenerChanges != null) { listener = this.EventListenerChanges.ListenEventMessage; this.EventListenerChanges.Dispose(); this.EventListenerChanges = null; } break; case EventType.UIA_NotificationEventId: if (this.EventListenerNotification != null) { listener = this.EventListenerNotification.ListenEventMessage; this.EventListenerNotification.Dispose(); this.EventListenerNotification = null; } break; case EventType.UIA_ActiveTextPositionChangedEventId: if (this.EventListenerActiveTextPositionChanged != null) { listener = this.EventListenerActiveTextPositionChanged.ListenEventMessage; this.EventListenerActiveTextPositionChanged.Dispose(); this.EventListenerActiveTextPositionChanged = null; } break; default: if (this.EventListeners.ContainsKey(msgData.EventId)) { var l = this.EventListeners[msgData.EventId]; listener = l.ListenEventMessage; this.EventListeners.Remove(msgData.EventId); l.Dispose(); } break; } if (listener != null) { #pragma warning disable CA2000 // Call IDisposable.Dispose() var m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Succeeded to unregister a event listeners"), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), }; listener(m); } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) { e.ReportException(); #pragma warning disable CA2000 // Call IDisposable.Dispose() var m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Failed to unregister a event listeners"), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), new KeyValuePair<string, dynamic>("Error", e.Message) }; listener(m); /// it is very unexpected situation. /// need to figure out a way to prevent it or handle it more gracefully } #pragma warning restore CA1031 // Do not catch general exception types } /// <summary> /// Process Register event message /// </summary> /// <param name="msgData"></param> private void RegisterEventListener(EventListenerFactoryMessage msgData) { try { EventMessage m = null; var win32Helper = new Win32Helper(); switch (msgData.EventId) { case EventType.UIA_AutomationFocusChangedEventId: if (this.EventListenerFocusChanged == null) { var uia = (IUIAutomation) UIAutomation8 ?? UIAutomation; this.EventListenerFocusChanged = new FocusChangedEventListener(uia, msgData.Listener); } break; case EventType.UIA_StructureChangedEventId: if (this.EventListenerStructureChanged == null) { this.EventListenerStructureChanged = new StructureChangedEventListener(this.UIAutomation, this.RootElement.PlatformObject, this.Scope, msgData.Listener); } break; case EventType.UIA_AutomationPropertyChangedEventId: if (this.EventListenerPropertyChanged == null) { this.EventListenerPropertyChanged = new PropertyChangedEventListener(this.UIAutomation, this.RootElement.PlatformObject, this.Scope, msgData.Listener,msgData.Properties); } break; case EventType.UIA_TextEdit_TextChangedEventId: if (this.EventListenerTextEditTextChanged == null) { this.EventListenerTextEditTextChanged = new TextEditTextChangedEventListener(this.UIAutomation8, this.RootElement.PlatformObject, this.Scope, msgData.Listener); } break; case EventType.UIA_ChangesEventId: if (this.EventListenerChanges == null) { this.EventListenerChanges = new ChangesEventListener(this.UIAutomation8, this.RootElement.PlatformObject, this.Scope, msgData.Listener); } break; case EventType.UIA_NotificationEventId: if (win32Helper.IsWindowsRS3OrLater()) { if (this.EventListenerNotification == null) { this.EventListenerNotification = new NotificationEventListener(this.UIAutomation8, this.RootElement.PlatformObject, this.Scope, msgData.Listener); } } else { #pragma warning disable CA2000 // Call IDisposable.Dispose() m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Event listener registration is rejected."), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), new KeyValuePair<string, dynamic>("Reason", "Not supported platform"), }; msgData.Listener(m); } break; case EventType.UIA_ActiveTextPositionChangedEventId: if (win32Helper.IsWindowsRS5OrLater()) { if (this.EventListenerNotification == null) { this.EventListenerActiveTextPositionChanged = new ActiveTextPositionChangedEventListener(this.UIAutomation8, this.RootElement.PlatformObject, this.Scope, msgData.Listener); } } else { #pragma warning disable CA2000 // Call IDisposable.Dispose() m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Event listener registration is rejected."), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), new KeyValuePair<string, dynamic>("Reason", "Not supported platform"), }; msgData.Listener(m); } break; default: if (this.EventListeners.ContainsKey(msgData.EventId) == false) { this.EventListeners.Add(msgData.EventId, new EventListener(this.UIAutomation, this.RootElement.PlatformObject, this.Scope, msgData.EventId, msgData.Listener)); } break; } #pragma warning disable CA2000 // Call IDisposable.Dispose() m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Succeeded to register an event listener"), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), }; msgData.Listener(m); if(msgData.EventId == EventType.UIA_AutomationFocusChangedEventId) { this.EventListenerFocusChanged.ReadyToListen = true; } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) { e.ReportException(); #pragma warning disable CA2000 // Call IDisposable.Dispose() var m = EventMessage.GetInstance(EventType.UIA_EventRecorderNotificationEventId, null); #pragma warning restore CA2000 m.Properties = new List<KeyValuePair<string, dynamic>>() { new KeyValuePair<string, dynamic>("Message", "Failed to register an event listener"), new KeyValuePair<string, dynamic>("Event Id", msgData.EventId), new KeyValuePair<string, dynamic>("Event Name", EventType.GetInstance().GetNameById(msgData.EventId)), new KeyValuePair<string, dynamic>("Error", e.Message) }; msgData.Listener(m); } #pragma warning restore CA1031 // Do not catch general exception types } /// <summary> /// Request Worker thread finish and wait for 2 seconds to finish. otherwise, there will be an exception. /// </summary> private void FinishWorkerThread() { #pragma warning disable CA2000 // Call IDisposable.Dispose() AddMessageToQueue(new EventListenerFactoryMessage() { MessageType = EventListenerFactoryMessageType.FinishThread }); #pragma warning restore CA2000 _autoEventFinish.WaitOne(TimeSpan.FromSeconds(ThreadExitGracePeriod)); if (this._threadBackground.IsAlive) { try { this._threadBackground.Abort(); } catch (PlatformNotSupportedException) { } // nothing we can do. Just continue } } /// <summary> /// Add a new Factory Message /// </summary> /// <param name="msgData"></param> private void AddMessageToQueue(EventListenerFactoryMessage msgData) { // Request the lock, and block until it is obtained. lock(_msgQueue) { // When the lock is obtained, add an element. _msgQueue.Enqueue(msgData); } _autoEventMsg.Set(); } #endregion public EventListenerFactory(A11yElement rootElement) : this(rootElement, ListenScope.Subtree) { } /// <summary> /// Cosntructor. /// </summary> /// <param name="peDelegate"></param> /// <param name="rootElement">can be null but it is only for global events like focusChanged</param> /// <param name="scope"></param> public EventListenerFactory(A11yElement rootElement, ListenScope scope) { this.RootElement = rootElement; this.Scope = GetUIAScope(scope); this.EventListeners = new Dictionary<int, EventListener>(); //Start worker thread StartWorkerThread(); } private static TreeScope GetUIAScope(ListenScope listenScope) { switch (listenScope) { case ListenScope.Element: return TreeScope.TreeScope_Element; case ListenScope.Descendants: return TreeScope.TreeScope_Descendants; default: return TreeScope.TreeScope_Subtree; } } /// <summary> /// Register a single event listener /// in case of property listening, since it is monolithic, you need to stop existing property listener first. /// the implicit cleanup is not defined. /// </summary> /// <param name="eventId"></param> /// <param name="peDelegate"></param> /// <param name="properties">required only for PropertyChanged Event listening</param> public void RegisterAutomationEventListener(int eventId, HandleUIAutomationEventMessage peDelegate, int[] properties = null) { #pragma warning disable CA2000 // Call IDisposable.Dispose() AddMessageToQueue(new EventListenerFactoryMessage() { MessageType = EventListenerFactoryMessageType.RegisterEventListener, Listener = peDelegate, EventId = eventId, Properties = properties }); #pragma warning restore CA2000 } /// <summary> /// Unregister a automation event listener /// </summary> /// <param name="eventId"></param> /// <param name="wait">wait to complete</param> public void UnregisterAutomationEventListener(int eventId,bool wait = false) { #pragma warning disable CA2000 // Call IDisposable.Dispose() var msg = new EventListenerFactoryMessage() { MessageType = EventListenerFactoryMessageType.UnregisterEventListener, EventId = eventId }; #pragma warning restore CA2000 AddMessageToQueue(msg); if (wait) { msg.WaitForProcessed(2000);// expect to be done in 2 seconds. } } /// <summary> /// Unregister all event listeners /// </summary> public void UnregisterAllAutomationEventListners() { #pragma warning disable CA2000 // Call IDisposable.Dispose() var msg = new EventListenerFactoryMessage() { MessageType = EventListenerFactoryMessageType.UnregisterAllEventListeners, }; #pragma warning restore CA2000 AddMessageToQueue(msg); msg.WaitForProcessed(2000);// expect to be done in 2 seconds. } #region IDisposable Support private bool disposedValue; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { UnregisterAllAutomationEventListners(); FinishWorkerThread(); if (_autoEventInit != null) { _autoEventInit.Dispose(); _autoEventInit = null; } if (_autoEventFinish != null) { _autoEventFinish.Dispose(); ; _autoEventFinish = null; } if (_autoEventMsg != null) { _autoEventMsg.Dispose(); _autoEventMsg = null; } } disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~AutomationEventHandlerFactory() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } #region private classes for messaging /// <summary> /// Message Type enum to support communication between UI Thread and Listener Factory Thread /// </summary> public enum EventListenerFactoryMessageType { Null, RegisterEventListener, UnregisterEventListener, UnregisterAllEventListeners, FinishThread }; /// <summary> /// EventListener Message data /// it contains message type and other information for further action /// </summary> public class EventListenerFactoryMessage:IDisposable { internal EventListenerFactoryMessageType MessageType; internal int EventId; internal HandleUIAutomationEventMessage Listener; internal int[] Properties; private AutoResetEvent _autoEventProcessed; // set when the message is processed. public EventListenerFactoryMessage() { this._autoEventProcessed = new AutoResetEvent(false); } /// <summary> /// Wait until message is processed. /// if not processed in given time, exception will be thrown. /// </summary> /// <param name="milliseconds"></param> public void WaitForProcessed(int milliseconds) { this._autoEventProcessed.WaitOne(milliseconds); } /// <summary> /// signal to finish processing this message. /// </summary> internal void Processed() { this._autoEventProcessed.Set(); } #region IDisposable Support private bool disposedValue; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this._autoEventProcessed.Dispose(); this._autoEventProcessed = null; } disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } #endregion }; #endregion }
44.094053
205
0.540056
[ "MIT" ]
decriptor/axe-windows
src/Desktop/UIAutomation/EventHandlers/EventListenerFactory.cs
31,158
C#
using System.Threading; using System.Threading.Tasks; using Dapper; using Hinode.Izumi.Framework.Database; using MediatR; namespace Hinode.Izumi.Services.GameServices.CardService.Queries { public record GetAllCardLengthQuery : IRequest<long>; public class GetAllCardLengthHandler : IRequestHandler<GetAllCardLengthQuery, long> { private readonly IConnectionManager _con; public GetAllCardLengthHandler(IConnectionManager con) { _con = con; } public async Task<long> Handle(GetAllCardLengthQuery request, CancellationToken cancellationToken) { return await _con.GetConnection() .QueryFirstOrDefaultAsync<long>(@" select count(*) from cards"); } } }
28.035714
106
0.681529
[ "MIT" ]
envyvox/Hinode.Izumi
Hinode.Izumi.Services/GameServices/CardService/Queries/GetAllCardLengthQuery.cs
787
C#
using System.Collections.Generic; namespace NPOI.POIFS.Properties { /// <summary> /// Behavior for parent (directory) properties /// @author Marc Johnson27591@hotmail.com /// </summary> public interface Parent : Child { /// <summary> /// Get an iterator over the children of this Parent /// all elements are instances of Property. /// </summary> /// <returns></returns> IEnumerator<Property> Children { get; } /// <summary> /// Sets the previous child. /// </summary> new Child PreviousChild { get; set; } /// <summary> /// Sets the next child. /// </summary> new Child NextChild { get; set; } /// <summary> /// Add a new child to the collection of children /// </summary> /// <param name="property">the new child to be added; must not be null</param> void AddChild(Property property); } }
18.826087
80
0.628176
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.POIFS.Properties/Parent.cs
866
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Page{ /// <summary> /// Transition type. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum TransitionType { Link, Typed, Auto_bookmark, Auto_subframe, Manual_subframe, Generated, Auto_toplevel, Form_submit, Reload, Keyword, Keyword_generated, Other, } }
17.821429
57
0.735471
[ "MIT" ]
Digitalbil/ChromeDevTools
source/ChromeDevTools/Protocol/Chrome/Page/TransitionType.cs
499
C#
// <copyright file="Benchmark0.cs" company="Endjin Limited"> // Copyright (c) Endjin Limited. All rights reserved. // </copyright> #pragma warning disable namespace ItemsDraft201909Feature.NestedItems { using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Corvus.JsonSchema.Benchmarking.Benchmarks; /// <summary> /// Additional properties benchmark. /// </summary> [MemoryDiagnoser] public class Benchmark0 : BenchmarkBase { /// <summary> /// Global setup. /// </summary> /// <returns>A <see cref="Task"/> which completes once setup is complete.</returns> [GlobalSetup] public Task GlobalSetup() { return this.GlobalSetup("draft2019-09\\items.json", "#/6/schema", "#/006/tests/000/data", true); } /// <summary> /// Validates using the Corvus types. /// </summary> [Benchmark] public void ValidateCorvus() { this.ValidateCorvusCore<ItemsDraft201909Feature.NestedItems.ItemsArrayArray>(); } /// <summary> /// Validates using the Newtonsoft types. /// </summary> [Benchmark] public void ValidateNewtonsoft() { this.ValidateNewtonsoftCore(); } } }
30.704545
108
0.603257
[ "Apache-2.0" ]
corvus-dotnet/Corvus.JsonSchema
Solutions/Corvus.JsonSchema.Benchmarking/201909/ItemsDraft201909/NestedItems/Benchmark0.cs
1,351
C#
// // System.Xml.Serialization.SchemaImporter.cs // // Author: // Lluis Sanchez Gual (lluis@novell.com) // // Copyright (C) Novell, Inc., 2004 // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; #if !TARGET_JVM using System.Xml.Serialization.Advanced; #endif namespace System.Xml.Serialization { public abstract class SchemaImporter { SchemaImporterExtensionCollection extensions; internal SchemaImporter () { } public SchemaImporterExtensionCollection Extensions { get { if (extensions == null) extensions = new SchemaImporterExtensionCollection (); return extensions; } } } } #endif
29.233333
74
0.717788
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/System.XML/System.Xml.Serialization/SchemaImporter.cs
1,754
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Common; namespace Microsoft.DotNet.Tools.Test.Utilities { public static partial class FileInfoExtensions { private class FileInfoNuGetLock : IDisposable { private CancellationTokenSource _cancellationTokenSource; private Task _task; public FileInfoNuGetLock(FileInfo fileInfo) { var taskCompletionSource = new TaskCompletionSource<string>(); _cancellationTokenSource = new CancellationTokenSource(); _task = Task.Run(async () => await ConcurrencyUtilities.ExecuteWithFileLockedAsync<int>( fileInfo.FullName, cancellationToken => { taskCompletionSource.SetResult("Lock is taken so test can continue"); Task.Delay(60000, cancellationToken).Wait(); return Task.FromResult(0); }, _cancellationTokenSource.Token)); taskCompletionSource.Task.Wait(); } public void Dispose() { _cancellationTokenSource.Cancel(); try { _task.Wait(); } catch (AggregateException) { } finally { _cancellationTokenSource.Dispose(); } } } } }
29.435484
104
0.544658
[ "MIT" ]
1Crazymoney/installer
test/Microsoft.DotNet.Tools.Tests.Utilities/Assertions/FileInfoExtensions.FileInfoNuGetLock.cs
1,827
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.ResourceManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class RequisitionObjectType : INotifyPropertyChanged { private RequisitionObjectIDType[] idField; private string descriptorField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("ID", Order = 0)] public RequisitionObjectIDType[] ID { get { return this.idField; } set { this.idField = value; this.RaisePropertyChanged("ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string Descriptor { get { return this.descriptorField; } set { this.descriptorField = value; this.RaisePropertyChanged("Descriptor"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.885246
136
0.732584
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.ResourceManagement/RequisitionObjectType.cs
1,335
C#
using Fidely.Framework.Compilation.Evaluators; using Fidely.Framework.Integration; using Fidely.Framework.Tests.Instrumentation; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; namespace Fidely.Framework.Tests.Compilation.Evaluators { [TestFixture] public class DynamicVariableEvaluatorTest { private DynamicVariableEvaluator testee; private Dictionary<Regex, Func<Match, object>> evaluators; [SetUp] public void SetUp() { testee = new DynamicVariableEvaluator(new OperandBuilderImpl()); evaluators = testee.GetType().GetField("evaluators", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(testee) as Dictionary<Regex, Func<Match, object>>; } [TestCase(null, "", ExpectedException = typeof(ArgumentNullException))] [TestCase("a", 0)] public void RegisterVariableShouldWorkCorrectly(string pattern, object value) { var item = new RegexAutoCompleteItem("", "", (v, o) => true, (v, o) => v); testee.RegisterVariable(pattern, o => value, item); Assert.AreEqual(1, evaluators.Count); Assert.AreEqual(1, testee.AutocompleteItems.Count()); Assert.AreSame(item, testee.AutocompleteItems.ElementAt(0)); } [Test] public void RegisterVariableShouldThrowExcepionWhenRegexIsNull() { Regex regex = null; var item = new RegexAutoCompleteItem("", "", (v, o) => true, (v, o) => v); Assert.Throws<ArgumentNullException>(() => testee.RegisterVariable(regex, o => o, item)); } [Test] public void RegisterVariableShouldThrowExceptionWhenProcedureIsNull() { var regex = new Regex(""); var item = new RegexAutoCompleteItem("", "", (v, o) => true, (v, o) => v); Assert.Throws<ArgumentNullException>(() => testee.RegisterVariable(regex, null, item)); } [Test] public void RegisterVariableShouldThrowExceptionWhenAutoCompleteItemIsNull() { var regex = new Regex(""); Assert.Throws<ArgumentNullException>(() => testee.RegisterVariable(regex, o => o, null)); } [TestCase(null, ExpectedException = typeof(ArgumentNullException))] [TestCase("x", Result = 10)] [TestCase("xyz", Result = 10)] [TestCase("y", Result = "foo")] [TestCase("yzx", Result = "foo")] [TestCase("z", Result = true)] [TestCase("zxy", Result = true)] public object EvaluateShouldWorkCorrectly(string value) { var item = new RegexAutoCompleteItem("", "", (v, o) => true, (v, o) => v); testee.RegisterVariable("^x.*$", o => 10, item); testee.RegisterVariable("^y.*$", o => "foo", item); testee.RegisterVariable("^z.*$", o => true, item); var operand = testee.Evaluate(null, value); return Expression.Lambda(operand.Expression).Compile().DynamicInvoke(); } [TestCase("X")] [TestCase("Y")] [TestCase("Z")] public void EvaluateShouldReturnNullWhenSpecifiedVariableIsNotMatchedAnyPattnens(string value) { var item = new RegexAutoCompleteItem("", "", (v, o) => true, (v, o) => v); testee.RegisterVariable("^x.*$", o => 10, item); testee.RegisterVariable("^y.*$", o => "foo", item); testee.RegisterVariable("^z.*$", o => true, item); Assert.IsNull(testee.Evaluate(null, value)); } } }
37.928571
172
0.606134
[ "Apache-2.0" ]
FrancielleWN/AutomateThePlanet-Learning-Series
TestCaseManager/Fidely/src/Core.Tests/Compilation/Evaluators/DynamicVariableEvaluatorTest.cs
3,719
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace BrightPeeps.Core.Services { public interface ISqlDataAccessService { Task<IEnumerable<TResult>> ExecuteStoredProcedure<TResult>(string procedureId); Task<IEnumerable<TResult>> ExecuteStoredProcedure<TResult, TParam>(string procedureId, TParam parameters); Task ExecuteCommand<T>(string command, T parameters); Task<IEnumerable<TResult>> ExecuteQuery<TResult, TParam>(string query, TParam parameters); Task TestConnection(); } }
39.571429
114
0.749097
[ "MIT" ]
BYUCS452F2021/bright-peeps
src/BrightPeeps.Core/Services/ISqlDataAccessService.cs
554
C#
using System; using System.Collections.Generic; using System.Text; namespace ArkBot4.Entities.ArkServer { public class ArkServer { // SERIALIZED ARK PROPERTIES public string rcon_ip { get; set; } public int rcon_port { get; set; } public string rcon_password { get; set; } public string server_name { get; set; } } }
21.882353
49
0.645161
[ "MIT" ]
Roman-Port/ArkBot
ArkBot4/Entities/ArkServer/ArkServer.cs
374
C#
using System; using System.Collections.Generic; using System.Text; namespace ClothShop.Core.Entity.Enum { public class ClothingColor { public int id { get; set; } public string Color { get; set; } public ICollection<ClothColor> ClothingOfColor { get; set; } } }
18.875
68
0.65894
[ "Apache-2.0" ]
thor1824/G3ClothingShop
ClothShop.Core.Entity/Enum/ClothingColor.cs
304
C#
#region using System; using Unity.Profiling; using UnityEngine; #endregion namespace collections.src { [Serializable] public abstract class AppaLookup3<TKey1, TKey2, TKey3, TValue, TKey1List, TKey2List, TKey3List, TValueList, TSubNested, TNested, TSubNestedList, TNestedList> : AppaLookup<TKey1, TNested, TKey1List, TNestedList> where TKey1List : AppaList<TKey1>, new() where TKey2List : AppaList<TKey2>, new() where TKey3List : AppaList<TKey3>, new() where TValueList : AppaList<TValue>, new() where TSubNested : AppaLookup<TKey3, TValue, TKey3List, TValueList>, new() where TNested : AppaLookup2<TKey2, TKey3, TValue, TKey2List, TKey3List, TValueList, TSubNested, TSubNestedList>, new() where TSubNestedList : AppaList<TSubNested>, new() where TNestedList : AppaList<TNested>, new() { private const string _PRF_PFX = nameof(AppaLookup3<TKey1, TKey2, TKey3, TValue, TKey1List, TKey2List, TKey3List, TValueList, TSubNested , TNested, TSubNestedList, TNestedList>) + "."; private static readonly ProfilerMarker _PRF_AddOrUpdate = new ProfilerMarker(_PRF_PFX + nameof(AddOrUpdate)); public void AddOrUpdate(TKey1 primary, TKey2 secondary, TKey3 tertiary, TValue value) { using (_PRF_AddOrUpdate.Auto()) { if (!TryGetValue(primary, out var sub)) { sub = new TNested(); Add(primary, sub); } if (!sub.TryGetValue(secondary, out var subSub)) { subSub = new TSubNested(); sub.Add(secondary, subSub); } subSub.AddOrUpdate(tertiary, value); } } private static readonly ProfilerMarker _PRF_TryGetValue = new ProfilerMarker(_PRF_PFX + nameof(TryGetValue)); public bool TryGetValue(TKey1 primary, TKey2 secondary, TKey3 tertiary, out TValue value) { using (_PRF_TryGetValue.Auto()) { if (base.TryGetValue(primary, out var sub1)) { if (sub1.TryGetValue(secondary, out var sub2)) { if (sub2.TryGetValue(tertiary, out value)) { return true; } } } value = default; return false; } } private static readonly ProfilerMarker _PRF_TryGetValueWithFallback = new ProfilerMarker(_PRF_PFX + nameof(TryGetValueWithFallback)); public bool TryGetValueWithFallback( TKey1 primary, TKey2 secondary, TKey3 tertiary, out TValue value, Predicate<TValue> fallbackCheck, string logFallbackAttempt = null, string logFallbackFailure = null) { using (_PRF_TryGetValueWithFallback.Auto()) { if (base.TryGetValue(primary, out var sub1)) { if (sub1.TryGetValue(secondary, out var sub2)) { if (sub2.TryGet(tertiary, out value)) { return true; } if (logFallbackAttempt != null) { Debug.LogWarning(logFallbackAttempt); } value = sub2.FirstWithPreference_NoAlloc(fallbackCheck, out var foundFallback); if (foundFallback) { return true; } if (logFallbackFailure != null) { Debug.LogWarning(logFallbackFailure); } } } value = default; return false; } } } }
34.885246
146
0.493421
[ "MIT" ]
ChristopherSchubert/com.appalachia.unity3d.appa.collections
src/AppaLookup3.cs
4,256
C#
/**************************************************************************** * Copyright (c) 2017 liangxie * * http://qframework.io * https://github.com/liangxiegame/QFramework * https://github.com/liangxiegame/QSingleton * https://github.com/liangxiegame/QChain * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ****************************************************************************/ namespace QFramework { using UnityEngine.Events; /// <summary> /// 全局唯一继承于MonoBehaviour的单例类,保证其他公共模块都以App的生命周期为准 /// 这个东西很基类,没什么用。概念也不太清晰 /// </summary> [QMonoSingletonPath("[Framework]/QFramework")] public class Framework : QMgrBehaviour, ISingleton { /// <summary> /// 组合的方式实现单例的模板 /// </summary> /// <value>The instance.</value> public static Framework Instance { get { return QMonoSingletonProperty<Framework>.Instance; } } protected override void SetupMgrId() { mMgrId = QMgrID.Framework; } public void OnSingletonInit() { } public void Dispose() { } private Framework() { } #region 全局生命周期回调 public UnityAction OnUpdateEvent = delegate { }; public UnityAction OnFixedUpdateEvent = delegate { }; public UnityAction OnLateUpdateEvent = delegate { }; public UnityAction OnGUIEvent = delegate { }; public UnityAction OnDestroyEvent = delegate { }; public UnityAction OnApplicationQuitEvent = delegate { }; void Update() { OnUpdateEvent.InvokeGracefully(); } void FixedUpdate() { OnFixedUpdateEvent.InvokeGracefully(); } void LateUpdate() { OnLateUpdateEvent.InvokeGracefully(); } void OnGUI() { OnGUIEvent.InvokeGracefully(); } protected void OnDestroy() { OnDestroyEvent.InvokeGracefully(); } void OnApplicationQuit() { OnApplicationQuitEvent.InvokeGracefully(); } #endregion } }
27.056604
80
0.67887
[ "MIT" ]
Bian-Sh/QFramework
Assets/QFramework/Framework/5.FrameworkConfig/QFramework.cs
3,006
C#
using System; using System.Collections.Generic; using System.Text; namespace GrandSql.PGsql.controller.Login.config { internal class InterceptorConfig { } }
15.545455
48
0.748538
[ "Apache-2.0" ]
light-come/IOT-Meta
lib/GrandSql/PGsql/controller/Login/config/InterceptorConfig.cs
173
C#
using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { GameObject cameraTarget; public float rotateSpeed; float rotate; public float offsetDistance; public float offsetHeight; public float smoothing; Vector3 offset; bool following = false; Vector3 lastPosition; void Start() { cameraTarget = GameObject.FindGameObjectWithTag("Player"); lastPosition = new Vector3(cameraTarget.transform.position.x, cameraTarget.transform.position.y + offsetHeight, cameraTarget.transform.position.z - offsetDistance); offset = new Vector3(cameraTarget.transform.position.x, cameraTarget.transform.position.y + offsetHeight, cameraTarget.transform.position.z - offsetDistance); } void Update() { if(Input.GetKey(KeyCode.Q)) { rotate = -1; } else if(Input.GetKey(KeyCode.E)) { rotate = 1; } else { rotate = 0; } offset = Quaternion.AngleAxis(rotate * rotateSpeed, Vector3.up) * offset; transform.position = cameraTarget.transform.position + offset; transform.position = new Vector3(Mathf.Lerp(lastPosition.x, cameraTarget.transform.position.x + offset.x, smoothing * Time.deltaTime), Mathf.Lerp(lastPosition.y, cameraTarget.transform.position.y + offset.y, smoothing * Time.deltaTime), Mathf.Lerp(lastPosition.z, cameraTarget.transform.position.z + offset.z, smoothing * Time.deltaTime)); transform.LookAt(cameraTarget.transform.position); } void LateUpdate() { lastPosition = transform.position; } }
30.04
166
0.749667
[ "MIT" ]
Lolz1243/Neanderthal.io
Assets/RPG Character Animation Pack/Code/CameraController.cs
1,504
C#
namespace DrawSharp { partial class DrawSharp { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースを破棄する場合は true を指定し、その他の場合は false を指定します。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileInfo = new System.Windows.Forms.ToolStripMenuItem(); this.newSave = new System.Windows.Forms.ToolStripMenuItem(); this.closeApp = new System.Windows.Forms.ToolStripMenuItem(); this.tools = new System.Windows.Forms.ToolStripMenuItem(); this.drawInfo = new System.Windows.Forms.ToolStripMenuItem(); this.pencil = new System.Windows.Forms.ToolStripMenuItem(); this.eraser = new System.Windows.Forms.ToolStripMenuItem(); this.fill = new System.Windows.Forms.ToolStripMenuItem(); this.rect = new System.Windows.Forms.ToolStripMenuItem(); this.none = new System.Windows.Forms.ToolStripMenuItem(); this.colorInfo = new System.Windows.Forms.ToolStripMenuItem(); this.Stroke = new System.Windows.Forms.ToolStripMenuItem(); this.Default = new System.Windows.Forms.ToolStripMenuItem(); this.L1 = new System.Windows.Forms.ToolStripMenuItem(); this.L2 = new System.Windows.Forms.ToolStripMenuItem(); this.L3 = new System.Windows.Forms.ToolStripMenuItem(); this.L4 = new System.Windows.Forms.ToolStripMenuItem(); this.L5 = new System.Windows.Forms.ToolStripMenuItem(); this.L6 = new System.Windows.Forms.ToolStripMenuItem(); this.allErase = new System.Windows.Forms.ToolStripMenuItem(); this.drawArea = new System.Windows.Forms.PictureBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.status = new System.Windows.Forms.ToolStripStatusLabel(); this.circle = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.drawArea)).BeginInit(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileInfo, this.tools}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(484, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileInfo // this.fileInfo.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newSave, this.closeApp}); this.fileInfo.Name = "fileInfo"; this.fileInfo.Size = new System.Drawing.Size(67, 20); this.fileInfo.Text = "ファイル(&F)"; // // newSave // this.newSave.Name = "newSave"; this.newSave.Size = new System.Drawing.Size(175, 22); this.newSave.Text = "名前を付けて保存(&S)"; // // closeApp // this.closeApp.Name = "closeApp"; this.closeApp.Size = new System.Drawing.Size(175, 22); this.closeApp.Text = "閉じる(&E)"; // // tools // this.tools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.drawInfo, this.colorInfo, this.Stroke, this.allErase}); this.tools.Name = "tools"; this.tools.Size = new System.Drawing.Size(60, 20); this.tools.Text = "ツール(&T)"; // // drawInfo // this.drawInfo.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pencil, this.eraser, this.fill, this.circle, this.rect, this.none}); this.drawInfo.Name = "drawInfo"; this.drawInfo.Size = new System.Drawing.Size(152, 22); this.drawInfo.Text = "描画線(&D)"; // // pencil // this.pencil.Name = "pencil"; this.pencil.Size = new System.Drawing.Size(152, 22); this.pencil.Text = "ペン"; // // eraser // this.eraser.Name = "eraser"; this.eraser.Size = new System.Drawing.Size(152, 22); this.eraser.Text = "消しゴム"; // // fill // this.fill.Name = "fill"; this.fill.Size = new System.Drawing.Size(152, 22); this.fill.Text = "塗りつぶし"; // // rect // this.rect.Name = "rect"; this.rect.Size = new System.Drawing.Size(152, 22); this.rect.Text = "四角形"; // // none // this.none.Name = "none"; this.none.Size = new System.Drawing.Size(152, 22); this.none.Text = "なし"; // // colorInfo // this.colorInfo.Name = "colorInfo"; this.colorInfo.Size = new System.Drawing.Size(152, 22); this.colorInfo.Text = "色(&C)"; // // Stroke // this.Stroke.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Default, this.L1, this.L2, this.L3, this.L4, this.L5, this.L6}); this.Stroke.Name = "Stroke"; this.Stroke.Size = new System.Drawing.Size(152, 22); this.Stroke.Text = "太さ(&S)"; // // Default // this.Default.Name = "Default"; this.Default.Size = new System.Drawing.Size(111, 22); this.Default.Text = "default"; // // L1 // this.L1.Name = "L1"; this.L1.Size = new System.Drawing.Size(111, 22); this.L1.Text = "レベル1"; // // L2 // this.L2.Name = "L2"; this.L2.Size = new System.Drawing.Size(111, 22); this.L2.Text = "レベル2"; // // L3 // this.L3.Name = "L3"; this.L3.Size = new System.Drawing.Size(111, 22); this.L3.Text = "レベル3"; // // L4 // this.L4.Name = "L4"; this.L4.Size = new System.Drawing.Size(111, 22); this.L4.Text = "レベル4"; // // L5 // this.L5.Name = "L5"; this.L5.Size = new System.Drawing.Size(111, 22); this.L5.Text = "レベル5"; // // L6 // this.L6.Name = "L6"; this.L6.Size = new System.Drawing.Size(111, 22); this.L6.Text = "レベル6"; // // allErase // this.allErase.Name = "allErase"; this.allErase.Size = new System.Drawing.Size(152, 22); this.allErase.Text = "全消し(&A)"; // // drawArea // this.drawArea.BackColor = System.Drawing.Color.White; this.drawArea.Location = new System.Drawing.Point(2, 24); this.drawArea.Name = "drawArea"; this.drawArea.Size = new System.Drawing.Size(480, 433); this.drawArea.TabIndex = 1; this.drawArea.TabStop = false; this.drawArea.MouseDown += new System.Windows.Forms.MouseEventHandler(this.drawArea_MouseDown); this.drawArea.MouseMove += new System.Windows.Forms.MouseEventHandler(this.drawArea_MouseMove); this.drawArea.MouseUp += new System.Windows.Forms.MouseEventHandler(this.drawArea_MouseUp); // // statusStrip1 // this.statusStrip1.BackColor = System.Drawing.Color.LightSeaGreen; this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.status}); this.statusStrip1.Location = new System.Drawing.Point(0, 458); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(484, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // status // this.status.ForeColor = System.Drawing.Color.White; this.status.Name = "status"; this.status.Size = new System.Drawing.Size(55, 17); this.status.Text = "準備完了"; // // circle // this.circle.Name = "circle"; this.circle.Size = new System.Drawing.Size(152, 22); this.circle.Text = "円"; // // DrawSharp // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(484, 480); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.drawArea); this.Controls.Add(this.menuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MainMenuStrip = this.menuStrip1; this.Name = "DrawSharp"; this.Text = "DrawSharp"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.drawArea)).EndInit(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileInfo; private System.Windows.Forms.ToolStripMenuItem newSave; private System.Windows.Forms.ToolStripMenuItem closeApp; private System.Windows.Forms.ToolStripMenuItem tools; private System.Windows.Forms.ToolStripMenuItem drawInfo; private System.Windows.Forms.ToolStripMenuItem pencil; private System.Windows.Forms.ToolStripMenuItem eraser; private System.Windows.Forms.ToolStripMenuItem fill; private System.Windows.Forms.ToolStripMenuItem rect; private System.Windows.Forms.ToolStripMenuItem none; private System.Windows.Forms.ToolStripMenuItem colorInfo; private System.Windows.Forms.PictureBox drawArea; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel status; private System.Windows.Forms.ToolStripMenuItem allErase; private System.Windows.Forms.ToolStripMenuItem Stroke; private System.Windows.Forms.ToolStripMenuItem Default; private System.Windows.Forms.ToolStripMenuItem L1; private System.Windows.Forms.ToolStripMenuItem L2; private System.Windows.Forms.ToolStripMenuItem L3; private System.Windows.Forms.ToolStripMenuItem L4; private System.Windows.Forms.ToolStripMenuItem L5; private System.Windows.Forms.ToolStripMenuItem L6; private System.Windows.Forms.ToolStripMenuItem circle; } }
32.463816
98
0.687405
[ "MIT" ]
Asteriskx/DrawSharp
DrawSharp/Form1.Designer.cs
10,281
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CalculateSequenceWithQueue { class Program { static void Main(string[] args) { decimal startingNumber = decimal.Parse(Console.ReadLine()); // here we will add and remove numbers that we calculate var calculateNumbers = new Queue<decimal>(); calculateNumbers.Enqueue(startingNumber); // here we will keep all numbers that we calculate var sequence = new List<decimal>(); sequence.Add(startingNumber); while (sequence.Count < 50) { var baseForFormula = calculateNumbers.Dequeue(); var firstFormula = baseForFormula + 1; calculateNumbers.Enqueue(firstFormula); sequence.Add(firstFormula); var secondFormula = 2 * baseForFormula + 1; calculateNumbers.Enqueue(secondFormula); sequence.Add(secondFormula); var thirdFormula = baseForFormula + 2; calculateNumbers.Enqueue(thirdFormula); sequence.Add(thirdFormula); } var first50Numbers = new StringBuilder(); for (int i = 0; i < 50; i++) { first50Numbers.Append(sequence[i]); if (i < 49) { first50Numbers.Append(" "); } } Console.WriteLine(first50Numbers.ToString()); } } }
30.396226
71
0.548107
[ "MIT" ]
NikolaVodenicharov/C-Advanced
StacksAndQueues/CalculateSequenceWithQueue/Program.cs
1,613
C#
using System; using System.Xml; using NUnit.Framework; using Rhino.Mocks; using Rhino.Mocks.Constraints; using StoryTeller.Domain; using StoryTeller.Execution; using StoryTeller.Model; using StoryTeller.UserInterface; using StoryTeller.UserInterface.Running; namespace StoryTeller.Testing.UserInterface { [TestFixture] public class TestServiceTester : InteractionContext<TestService> { private FixtureLibrary initialLibrary; private FixtureLibrary newLibrary; protected override void beforeEach() { initialLibrary = new FixtureLibrary(); Services.Inject(initialLibrary); newLibrary = new FixtureLibrary(); } [Test] public void cancel_test_delegates_to_queue() { var test = new Test("test 1"); ClassUnderTest.CancelTest(test); MockFor<IExecutionQueue>().AssertWasCalled(x => x.Cancel(test)); } [Test] public void creating_preview_uses_the_test_converter_and_the_initial_library() { var test = new Test("some test"); string html1 = "<test/>"; MockFor<ITestConverter>().Expect(x => x.ToPreview(initialLibrary, test)).Return(html1); ClassUnderTest.CreatePreview(test).ShouldEqual(html1); MockFor<ITestConverter>().VerifyAllExpectations(); } [Test] public void deleting_a_test_sends_a_message() { var test = new Test("test 1"); ClassUnderTest.DeleteTest(test); MockFor<IEventAggregator>().AssertWasCalled(x => x.SendMessage(new DeleteTestMessage(test))); } [Test] public void get_status_when_the_test_is_executing() { var test = new Test("a test"); MockFor<IExecutionQueue>().Stub(x => x.ExecutingTest).Return(test); ClassUnderTest.GetStatus(test).ShouldEqual(TestState.Executing); } [Test] public void get_status_when_the_test_is_neither_queued_not_executing() { var test = new Test("a test"); MockFor<IExecutionQueue>().Stub(x => x.ExecutingTest).Return(new Test("other test")); MockFor<IExecutionQueue>().Stub(x => x.IsQueued(test)).Return(false); ClassUnderTest.GetStatus(test).ShouldEqual(TestState.NotQueued); } [Test] public void get_status_when_the_test_is_queued() { var test = new Test("a test"); MockFor<IExecutionQueue>().Stub(x => x.ExecutingTest).Return(new Test("other test")); MockFor<IExecutionQueue>().Stub(x => x.IsQueued(test)).Return(true); ClassUnderTest.GetStatus(test).ShouldEqual(TestState.Queued); } [Test] public void queue_test_delegates_to_queue() { var test = new Test("test 1"); ClassUnderTest.QueueTest(test); MockFor<IExecutionQueue>().AssertWasCalled(x => x.QueueTest(test)); } [Test] public void saving_a_test_sends_a_message() { var test = new Test("test 1"); ClassUnderTest.Save(test); MockFor<IEventAggregator>().AssertWasCalled(x => x.SendMessage(new SaveTestMessage(test))); } [Test] public void test_service_should_replace_its_current_fixture_library_when_the_fixturelibraryloaded_message_is_called() { ClassUnderTest.Library.ShouldBeTheSameAs(initialLibrary); ClassUnderTest.HandleMessage(new BinaryRecycleFinished(newLibrary)); ClassUnderTest.Library.ShouldBeTheSameAs(newLibrary); } } }
31.710744
118
0.607766
[ "Apache-2.0" ]
ericln/storyteller
source/StoryTeller.Testing/UserInterface/TestServiceTester.cs
3,837
C#