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
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.DiaSymReader.Tools; using System; using System.Globalization; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; namespace Microsoft.DotNet.Build.Tasks { public class ConvertPortablePdbsToWindowsPdbs : BuildTask, ICancelableTask { private const string PdbPathMetadata = "PdbPath"; private const string TargetPathMetadata = "TargetPath"; private const string NoDebugDirectoryEntriesMessage = "has no Debug directory entries. If this DLL is created by GenFacades " + "(Microsoft.Win32.Registry.AccessControl, System.Security.Permissions), this is a " + "known issue tracked by 'https://github.com/dotnet/buildtools/issues/1739'."; [Required] public ITaskItem[] Files { get; set; } public string[] ConversionOptions { get; set; } private bool _cancel; public override bool Execute() { var parsedConversionOptions = PdbConversionOptions.Default; foreach (string option in ConversionOptions ?? Enumerable.Empty<string>()) { PdbConversionOptions parsedOption; if (!Enum.TryParse(option, out parsedOption)) { throw new ArgumentException( $"Passed conversion option '{option}'" + $"is not a value of {nameof(PdbConversionOptions)}."); } parsedConversionOptions |= parsedOption; } var converter = new PdbConverter( d => Log.LogError(d.ToString(CultureInfo.InvariantCulture))); foreach (ITaskItem file in Files) { if (_cancel) { break; } try { ConvertPortableToWindows(file, converter, parsedConversionOptions); } catch (Exception e) { Log.LogErrorFromException(e, true, true, file.ItemSpec); } } return !Log.HasLoggedErrors; } public void Cancel() { _cancel = true; } private void ConvertPortableToWindows( ITaskItem file, PdbConverter converter, PdbConversionOptions parsedConversionOptions) { string pdbPath = file.GetMetadata(PdbPathMetadata); if (string.IsNullOrEmpty(pdbPath)) { Log.LogError($"No '{PdbPathMetadata}' metadata found for '{file}'."); return; } string targetPath = file.GetMetadata(TargetPathMetadata); if (string.IsNullOrEmpty(targetPath)) { Log.LogError($"No '{TargetPathMetadata}' metadata found for '{file}'."); return; } using (var sourcePdbStream = new FileStream(pdbPath, FileMode.Open, FileAccess.Read)) { if (PdbConverter.IsPortable(sourcePdbStream)) { Log.LogMessage( MessageImportance.Low, $"Converting portable PDB '{file.ItemSpec}'..."); Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); using (var peStream = new FileStream(file.ItemSpec, FileMode.Open, FileAccess.Read)) using (var peReader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) { if (peReader.ReadDebugDirectory().Length > 0) { using (var outPdbStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write)) { converter.ConvertPortableToWindows( peReader, sourcePdbStream, outPdbStream, parsedConversionOptions); } Log.LogMessage( MessageImportance.Normal, $"Portable PDB '{file.ItemSpec}' -> '{targetPath}'"); } else { Log.LogWarning($"'{file.ItemSpec}' {NoDebugDirectoryEntriesMessage}"); } } } else { Log.LogMessage( MessageImportance.Normal, $"PDB is not portable, skipping: '{file.ItemSpec}'"); } } } } }
36.257143
116
0.506698
[ "MIT" ]
dseefeld/buildtools
src/Microsoft.DotNet.Build.Tasks/ConvertPortablePdbsToWindowsPdbs.cs
5,078
C#
namespace Patterns.Interpreter.Contracts { public interface IBread : IExpression { } }
15
41
0.766667
[ "MIT" ]
Xeinaemm/Patterns
Patterns/Interpreter/Contracts/IBread.cs
92
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 mediaconnect-2018-11-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MediaConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConnect.Model.Internal.MarshallTransformations { /// <summary> /// UpdateFailoverConfig Marshaller /// </summary> public class UpdateFailoverConfigMarshaller : IRequestMarshaller<UpdateFailoverConfig, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(UpdateFailoverConfig requestObject, JsonMarshallerContext context) { if(requestObject.IsSetRecoveryWindow()) { context.Writer.WritePropertyName("recoveryWindow"); context.Writer.Write(requestObject.RecoveryWindow); } if(requestObject.IsSetState()) { context.Writer.WritePropertyName("state"); context.Writer.Write(requestObject.State); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static UpdateFailoverConfigMarshaller Instance = new UpdateFailoverConfigMarshaller(); } }
33.764706
114
0.678571
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/MediaConnect/Generated/Model/Internal/MarshallTransformations/UpdateFailoverConfigMarshaller.cs
2,296
C#
using System; using System.Data; using System.Data.Common; using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; namespace CSF.NHibernate { public class SchemaCreator { public virtual void CreateSchema(Configuration config, DbConnection connection) { if (config == null) throw new ArgumentNullException(nameof(config)); if (connection == null) throw new ArgumentNullException(nameof(connection)); var exporter = new SchemaExport(config); exporter.Execute(false, true, false, connection, null); } } }
26.5
87
0.646226
[ "MIT" ]
csf-dev/CSF.Data.NHibernate
CSF.NHibernate5.Tests/SchemaCreator.cs
638
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #if IGNITOR namespace Ignitor #else namespace Microsoft.AspNetCore.Components.RenderTree #endif { /// <summary> /// Types in the Microsoft.AspNetCore.Components.RenderTree are not recommended for use outside /// of the Blazor framework. These types will change in future release. /// </summary> // // Describes changes to a component's render tree between successive renders. public readonly struct RenderTreeDiff { /// <summary> /// Gets the ID of the component. /// </summary> public readonly int ComponentId; /// <summary> /// Gets the changes to the render tree since a previous state. /// </summary> public readonly ArrayBuilderSegment<RenderTreeEdit> Edits; internal RenderTreeDiff( int componentId, ArrayBuilderSegment<RenderTreeEdit> entries) { ComponentId = componentId; Edits = entries; } } }
30.945946
111
0.649782
[ "Apache-2.0" ]
06b/AspNetCore
src/Components/Components/src/RenderTree/RenderTreeDiff.cs
1,145
C#
using FluentValidation; namespace Template.Application.TodoItems.Commands.CreateTodoItem { public class CreateTodoItemCommandValidator : AbstractValidator<CreateTodoItemCommand> { public CreateTodoItemCommandValidator() { RuleFor(v => v.Title) .MaximumLength(200) .NotEmpty(); } } }
24.333333
90
0.638356
[ "MIT" ]
VeselinBPavlov/web-application-templates
Clean Architecture 3.1 MVC Template/Src/Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommandValidator.cs
367
C#
using System; using GOTO.Common; using System.Diagnostics; namespace GOTO.ConsoleTest { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); int readvalue = 0; Console.WriteLine("当前时间:" + DateTime.Now); while (true) { Console.WriteLine("请输入操作选项:获取所有记录数(1),根据条件查询(2),数据写入(3),分离数据库(4),附加数据库(5),表添加索引(6),表删除索引(7),服务器缓存清除(9),检查服务器连接(11),检查数据库连接(12),检查表连接(13),删除记录(14),修改记录(15),清空某一数据结构存储(16),退出(q)"); string getread = Console.ReadLine(); if (getread.ToLower().Trim() == "q") { System.Environment.Exit(0); } readvalue = CommonHelper.ToInt(getread); sw.Restart(); switch (readvalue) { case 1: TestDB.getrowallcount(); break; case 2: TestDB.getlistcondition(); break; case 3: TestDB.addrow(); break; case 4: TestDB.databasedetach(); break; case 5: TestDB.databaseattach(); break; case 6: TestDB.tableindexadd(); break; case 7: TestDB.tableindexdel(); break; case 9: TestDB.servercacheclear(); break; case 11: TestDB.serverconnectioncheck(); break; case 12: TestDB.databaseexistsall(); break; case 13: TestDB.tableexistsall(); break; case 14: TestDB.delete(); break; case 15: TestDB.update(); break; case 16: TestDB.sqlbaseclear(); break; } sw.Stop(); Console.WriteLine(" 执行时间:" + sw.ElapsedMilliseconds+"毫秒"); } Console.WriteLine("当前时间:"+DateTime.Now); Console.ReadKey(); } } }
37.960784
194
0.48812
[ "Apache-2.0" ]
aryice/GOTO.Segment
GOTO.ConsoleTest/Program.cs
2,146
C#
using System; using Microsoft.WindowsAzure.Storage.Table; namespace SupportAssistant { internal sealed class MessageEntity : TableEntity { public string Message { get; set; } public string Details { get; set; } public DateTime CreateTime { get; set; } public MessageEntity() { } public MessageEntity(string exceptionType, string message, string details) : base(exceptionType, Guid.NewGuid().ToString()) { Message = message; Details = details; CreateTime = DateTime.UtcNow; } } }
24.6
82
0.598374
[ "MIT" ]
MarketKernel/webmoney-business-tools
Src/SupportAssistant/MessageEntity.cs
617
C#
#region using System; using System.IO; using System.Text; using Newtonsoft.Json; using UlteriusServer.Api.Network.Messages; using UlteriusServer.Utilities; using UlteriusServer.WebSocketAPI.Authentication; using vtortola.WebSockets; #endregion namespace UlteriusServer.Api.Network.PacketHandlers { public class SettingsPacketHandler : PacketHandler { private AuthClient _authClient; private MessageBuilder _builder; private WebSocket _client; private Packet _packet; public void GetCurrentSettings() { _builder.WriteMessage(Config.GetRaw()); } /// <summary> /// Saves the Ulterius settings /// </summary> public void SaveSettings() { try { var base64Settings = _packet.Args[0].ToString(); var data = Convert.FromBase64String(base64Settings); var decodedString = Encoding.UTF8.GetString(data); var fileName = "Config.json"; var filePath = Path.Combine(AppEnvironment.DataPath, fileName); var config = JsonConvert.DeserializeObject<Config>(decodedString); File.WriteAllText(filePath, JsonConvert.SerializeObject(config, Formatting.Indented)); var response = new { changedStatus = true }; _builder.WriteMessage(response); } catch (Exception ex) { var response = new { changedStatus = true, message = ex.Message }; _builder.WriteMessage(response); } } public override void HandlePacket(Packet packet) { _client = packet.Client; _authClient = packet.AuthClient; _packet = packet; _builder = new MessageBuilder(_authClient, _client, _packet.EndPointName, _packet.SyncKey); switch (_packet.EndPoint) { case PacketManager.EndPoints.SaveSettings: SaveSettings(); break; case PacketManager.EndPoints.GetCurrentSettings: GetCurrentSettings(); break; } } } }
31.25
103
0.554105
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Codeusa/StrikeTaskManager
RemoteTaskServer/Api/Network/PacketHandlers/SettingsPacketHandler.cs
2,377
C#
using System; using DevExpress.ExpressApp.Xpo; namespace SenDev.DashboardsDemo.Blazor.Server.Services { public class XpoDataStoreProviderAccessor { public IXpoDataStoreProvider DataStoreProvider { get; set; } } }
25.666667
68
0.766234
[ "MIT" ]
tuminskiy/SenDevXafDashboards
src/Demo/SenDev.DashboardsDemo.Blazor.Server/Services/XpoDataStoreProviderAccessor.cs
233
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.SqlServer.TDS.ColMetadata { /// <summary> /// Metadata associated with Shiloh variable character column /// </summary> public class TDSShilohVarCharColumnSpecific { /// <summary> /// Length of the data /// </summary> public ushort Length { get; set; } /// <summary> /// Collation /// </summary> public TDSColumnDataCollation Collation { get; set; } /// <summary> /// Default constructor /// </summary> public TDSShilohVarCharColumnSpecific() { } /// <summary> /// Initialization constructor /// </summary> public TDSShilohVarCharColumnSpecific(ushort length) { Length = length; } /// <summary> /// Initialization constructor /// </summary> public TDSShilohVarCharColumnSpecific(ushort length, TDSColumnDataCollation collation) { Length = length; Collation = collation; } } }
27.06383
94
0.579403
[ "MIT" ]
0xced/SqlClient
src/Microsoft.Data.SqlClient/tests/tools/TDS/TDS/ColMetadata/TDSShilohVarCharColumnSpecific.cs
1,274
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Linq; using BuildXL.Cache.ContentStore.Distributed.NuCache; using BuildXL.Cache.ContentStore.Distributed.NuCache.EventStreaming; using BuildXL.Cache.ContentStore.Interfaces.Tracing; using BuildXL.Cache.ContentStore.Tracing.Internal; using BuildXL.Utilities.Collections; using BuildXL.Cache.ContentStore.Hashing; using ContentStoreTest.Test; using FluentAssertions; using Xunit; using Xunit.Abstractions; using System.Diagnostics.ContractsLight; using System.Collections.Generic; using BuildXL.Cache.ContentStore.Distributed.Utilities; using BuildXL.Cache.MemoizationStore.Interfaces.Sessions; using BuildXL.Cache.ContentStore.Tracing; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Interfaces.Results; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Time; using BuildXL.Cache.ContentStore.UtilitiesCore; using System.IO; using System.Threading; using BuildXL.Cache.ContentStore.InterfacesTest.Results; using BuildXL.Cache.ContentStore.Utils; namespace ContentStoreTest.Distributed.ContentLocation.NuCache { public class ContentLocationEventDataSerializerTests : TestBase { /// <nodoc /> public ContentLocationEventDataSerializerTests(ITestOutputHelper output) : base(TestGlobal.Logger, output) { } public static IEnumerable<object[]> EventKinds => Enum.GetValues(typeof(EventKind)).OfType<EventKind>().Select(k => new object[] { k, k.ToString() }); [Theory] [MemberData(nameof(EventKinds))] public async Task LargeInstanceEventsTest(EventKind kind, string kindName) { BuildXL.Utilities.Analysis.IgnoreArgument(kindName, "Kind name is only specified so enum value name shows up in test name"); if (kind == EventKind.Blob) { // Blob events don't have a large equivalent since they just have a storage id return; } var context = new OperationContext(new Context(Logger)); var harness = new LargeEventTestHarness(); var sender = harness.Sender; var configuration = new MemoryContentLocationEventStoreConfiguration(); var memoryEventHub = new MemoryEventHubClient(configuration); var eventStore = new EventHubContentLocationEventStore(configuration, harness, "TestMachine", harness, TestRootDirectoryPath / "eventwork", SystemClock.Instance); await eventStore.StartupAsync(context).ThrowIfFailure(); eventStore.StartProcessing(context, new EventSequencePoint(DateTime.UtcNow)).ThrowIfFailure(); var serializer = CreateContentLocationEventDataSerializer(); await sendAndVerifyLargeEvent(kind); using var stream = new MemoryStream(); using var writer = BuildXL.Utilities.BuildXLWriter.Create(stream); serializer.SerializeEvents(writer, harness.Events); stream.Position.Should().BeGreaterThan(ContentLocationEventDataSerializer.MaxEventDataPayloadSize, "Event should be larger than max event payload size to properly test serialization logic"); bool canSplit = kind == EventKind.AddLocation || kind == EventKind.AddLocationWithoutTouching || kind == EventKind.RemoveLocation || kind == EventKind.RemoveLocation || kind == EventKind.Touch; foreach (var eventData in harness.Events) { eventData.SerializationKind.Should().Be(kind); } configuration.Hub.EventStream.Count.Should().BeGreaterThan(0); foreach (var rawEvent in configuration.Hub.EventStream) { rawEvent.Body.Count.Should().BeLessOrEqualTo(ContentLocationEventDataSerializer.MaxEventDataPayloadSize); } if (canSplit) { // Events should be split harness.Events.Count.Should().BeGreaterThan(1); configuration.Hub.EventStream.Count.Should().BeGreaterThan(1); // No uploads/downloads should happen for splittable events harness.State.DownloadedCount.Should().Be(0); harness.State.UploadedCount.Should().Be(0); harness.State.UploadedSize.Should().Be(0); harness.State.DownloadedSize.Should().Be(0); } else { harness.Events.Count.Should().Be(1); configuration.Hub.EventStream.Count.Should().Be(1); harness.State.DownloadedCount.Should().Be(1); harness.State.UploadedCount.Should().Be(1); harness.State.UploadedSize.Should().BeGreaterOrEqualTo(stream.Position); harness.State.UploadedSize.Should().Be(harness.State.DownloadedSize); } async Task sendAndVerifyLargeEvent(EventKind kind) { const int largeEventContentCount = 50000; switch (kind) { case EventKind.AddLocation: case EventKind.AddLocationWithoutTouching: { var sent = Enumerable.Range(0, largeEventContentCount).Select(_ => new ContentHashWithSize(ContentHash.Random(), ThreadSafeRandom.Generator.Next(0, 100000))).ToList(); eventStore.AddLocations( context, sender, sent, touch: kind == EventKind.AddLocation).ThrowIfFailure(); var received = harness.Events.Cast<AddContentLocationEventData>().SelectMany(e => e.ContentHashes.SelectList((hash, index) => (hash, size: e.ContentSizes[index]))).ToList(); received.Count.Should().Be(sent.Count); for (int i = 0; i < received.Count; i++) { received[i].hash.Should().Be(new ShortHash(sent[i].Hash)); received[i].size.Should().Be(sent[i].Size); } return; } case EventKind.RemoveLocation: { var sent = Enumerable.Range(0, largeEventContentCount).Select(_ => ContentHash.Random()).ToList(); eventStore.RemoveLocations( context, sender, sent).ThrowIfFailure(); var received = harness.Events.Cast<RemoveContentLocationEventData>().SelectMany(e => e.ContentHashes).ToList(); received.Count.Should().Be(sent.Count); for (int i = 0; i < received.Count; i++) { received[i].Should().Be(new ShortHash(sent[i])); } return; } case EventKind.Touch: { var sent = Enumerable.Range(0, largeEventContentCount).Select(_ => ContentHash.Random()).ToList(); eventStore.Touch( context, sender, sent, DateTime.UtcNow).ThrowIfFailure(); var received = harness.Events.Cast<TouchContentLocationEventData>().SelectMany(e => e.ContentHashes).ToList(); received.Count.Should().Be(sent.Count); for (int i = 0; i < received.Count; i++) { received[i].Should().Be(new ShortHash(sent[i])); } return; } case EventKind.UpdateMetadataEntry: { var contentHashes = Enumerable.Range(0, largeEventContentCount).Select(_ => ContentHash.Random()).ToArray(); var sent = new UpdateMetadataEntryEventData( sender, StrongFingerprint.Random(), new MetadataEntry( new ContentHashListWithDeterminism( new ContentHashList(contentHashes), CacheDeterminism.None), DateTime.UtcNow)); await eventStore.UpdateMetadataEntryAsync(context, sent).ShouldBeSuccess(); var received = harness.Events.Cast<UpdateMetadataEntryEventData>().SelectMany(e => e.Entry.ContentHashListWithDeterminism.ContentHashList.Hashes).ToList(); received.Count.Should().Be(contentHashes.Length); for (int i = 0; i < received.Count; i++) { received[i].Should().Be(contentHashes[i]); } return; } default: throw Contract.AssertFailure($"No large event for kind {kind}. Add large event to ensure this case is tested"); } } } [Fact] public void LargeInstanceIsSplitAutomatically() { const int numberOfHashesPerItem = 20000; DateTime touchTime = DateTime.UtcNow; var serializer = CreateContentLocationEventDataSerializer(); var largeMessage = GenerateRandomEventData(0, numberOfHashesPerItem, touchTime); var serializedMessages = serializer.Serialize(OperationContext(), new[] { largeMessage }).ToList(); // Round trip validation is performed by the serializer Output.WriteLine($"Number of serialized records: {serializedMessages.Count}"); serializedMessages.Count.Should().NotBe(1); } [Fact] public void TwoHunderdEventsShouldBeSerializedIntoOneEventDAta() { DateTime touchTime = DateTime.UtcNow; var serializer = CreateContentLocationEventDataSerializer(); var largeMessage = Enumerable.Range(1, 200).Select<int, ContentLocationEventData>(n => GenerateRandomEventData(0, numberOfHashes: 2, touchTime: touchTime)).ToArray(); var serializedMessages = serializer.Serialize(OperationContext(), largeMessage).ToList(); // Round trip validation is performed by the serializer Output.WriteLine($"Number of serialized records: {serializedMessages.Count}"); serializedMessages.Count.Should().Be(1); } [Fact] public void CreateEventDatasReturnsMoreThanOneValueDueToTheSize() { const int numberOfItems = 1000; const int numberOfHashesPerItem = 200; DateTime touchTime = DateTime.UtcNow; var serializer = CreateContentLocationEventDataSerializer(); var messages = Enumerable.Range(1, numberOfItems).Select<int, ContentLocationEventData>(n => GenerateRandomEventData(n, numberOfHashesPerItem, touchTime)).ToArray(); // Round trip validation is performed by the serializer var serializedMessages = serializer.Serialize(OperationContext(), messages).ToList(); Output.WriteLine($"Number of serialized records: {serializedMessages.Count}"); serializedMessages.Count.Should().NotBe(1); } [Theory] [InlineData(1, 1)] [InlineData(10, 2)] public void SerializationRoundtripWithSmallNumberOfElements(int numberOfItems, int numberOfHashesPerItem) { DateTime touchTime = DateTime.UtcNow; var serializer = CreateContentLocationEventDataSerializer(); var messages = Enumerable.Range(1, numberOfItems).Select<int, ContentLocationEventData>(n => GenerateRandomEventData(n, numberOfHashesPerItem, touchTime)).ToArray(); // Round trip validation is performed by the serializer var serializedMessages = serializer.Serialize(OperationContext(), messages).ToList(); serializedMessages.Count.Should().Be(1); // All the cases we have should fit into one message. } private static ContentLocationEventData GenerateRandomEventData(int index, int numberOfHashes, DateTime touchTime) { var random = new Random(index); var hashesAndSizes = Enumerable.Range(1, numberOfHashes).Select(n => (hash: new ShortHash(ContentHash.Random()), size: (long)random.Next(10_000_000))).ToList(); return (index % 3) switch { 0 => (ContentLocationEventData)new AddContentLocationEventData(new MachineId(index), hashesAndSizes.SelectArray(n => n.hash), hashesAndSizes.SelectArray(n => n.size)), 1 => new TouchContentLocationEventData(new MachineId(index), hashesAndSizes.SelectArray(n => n.hash), touchTime), _ => new RemoveContentLocationEventData(new MachineId(index), hashesAndSizes.SelectArray(n => n.hash)), }; } private static ContentLocationEventDataSerializer CreateContentLocationEventDataSerializer() => new ContentLocationEventDataSerializer(ValidationMode.Fail); private static OperationContext OperationContext() => new OperationContext(new Context(TestGlobal.Logger)); private class LargeEventTestHarness : CentralStorage, IContentLocationEventHandler { protected override Tracer Tracer { get; } = new Tracer(nameof(LargeEventTestHarness)); public InnerState State { get; set; } public List<ContentLocationEventData> Events => State.Events; internal class InnerState { public List<ContentLocationEventData> Events { get; } = new List<ContentLocationEventData>(); public Dictionary<string, byte[]> Storage { get; } = new Dictionary<string, byte[]>(); public long UploadedSize = 0; public long UploadedCount = 0; public long DownloadedSize = 0; public long DownloadedCount = 0; } public MachineId Sender { get; } = new MachineId(23); public LargeEventTestHarness() { ResetState(); } public void ResetState() { State = new InnerState(); } public long ContentTouched(OperationContext context, MachineId sender, IReadOnlyList<ShortHash> hashes, UnixTime accessTime) { Events.Add(new TouchContentLocationEventData(sender, hashes, accessTime.ToDateTime())); return hashes.Count; } public long LocationAdded(OperationContext context, MachineId sender, IReadOnlyList<ShortHashWithSize> hashes, bool reconciling, bool updateLastAccessTime) { Events.Add(new AddContentLocationEventData(sender, hashes, touch: updateLastAccessTime) { Reconciling = reconciling }); return hashes.Count; } public long LocationRemoved(OperationContext context, MachineId sender, IReadOnlyList<ShortHash> hashes, bool reconciling) { Events.Add(new RemoveContentLocationEventData(sender, hashes) { Reconciling = reconciling }); return hashes.Count; } public long MetadataUpdated(OperationContext context, StrongFingerprint strongFingerprint, MetadataEntry entry) { Events.Add(new UpdateMetadataEntryEventData(Sender, strongFingerprint, entry)); return 1; } protected override Task<BoolResult> TouchBlobCoreAsync(OperationContext context, AbsolutePath file, string storageId, bool isUploader, bool isImmutable) { return BoolResult.SuccessTask; } protected override Task<BoolResult> TryGetFileCoreAsync(OperationContext context, string storageId, AbsolutePath targetFilePath, bool isImmutable) { var bytes = State.Storage[storageId]; File.WriteAllBytes(targetFilePath.Path, bytes); Interlocked.Increment(ref State.DownloadedCount); Interlocked.Add(ref State.DownloadedSize, bytes.Length); return BoolResult.SuccessTask; } protected override Task<Result<string>> UploadFileCoreAsync(OperationContext context, AbsolutePath file, string name, bool garbageCollect = false) { var bytes = File.ReadAllBytes(file.Path); Interlocked.Add(ref State.UploadedSize, bytes.Length); Interlocked.Increment(ref State.UploadedCount); State.Storage[name] = bytes; return Task.FromResult(Result.Success(name)); } } } }
46.488189
198
0.587681
[ "MIT" ]
Microsoft/BuildXL
Public/Src/Cache/ContentStore/DistributedTest/ContentLocation/NuCache/ContentLocationEventDataSerializerTests.cs
17,712
C#
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V27.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V27.Segment{ ///<summary> /// Represents an HL7 CNS message segment. /// This segment has the following fields:<ol> ///<li>CNS-1: Starting Notification Reference Number (NM)</li> ///<li>CNS-2: Ending Notification Reference Number (NM)</li> ///<li>CNS-3: Starting Notification Date/Time (DTM)</li> ///<li>CNS-4: Ending Notification Date/Time (DTM)</li> ///<li>CNS-5: Starting Notification Code (CWE)</li> ///<li>CNS-6: Ending Notification Code (CWE)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class CNS : AbstractSegment { /** * Creates a CNS (Clear Notification) segment object that belongs to the given * message. */ public CNS(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(NM), false, 1, 0, new System.Object[]{message}, "Starting Notification Reference Number"); this.add(typeof(NM), false, 1, 0, new System.Object[]{message}, "Ending Notification Reference Number"); this.add(typeof(DTM), false, 1, 0, new System.Object[]{message}, "Starting Notification Date/Time"); this.add(typeof(DTM), false, 1, 0, new System.Object[]{message}, "Ending Notification Date/Time"); this.add(typeof(CWE), false, 1, 0, new System.Object[]{message}, "Starting Notification Code"); this.add(typeof(CWE), false, 1, 0, new System.Object[]{message}, "Ending Notification Code"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns Starting Notification Reference Number(CNS-1). ///</summary> public NM StartingNotificationReferenceNumber { get{ NM ret = null; try { IType t = this.GetField(1, 0); ret = (NM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Ending Notification Reference Number(CNS-2). ///</summary> public NM EndingNotificationReferenceNumber { get{ NM ret = null; try { IType t = this.GetField(2, 0); ret = (NM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Starting Notification Date/Time(CNS-3). ///</summary> public DTM StartingNotificationDateTime { get{ DTM ret = null; try { IType t = this.GetField(3, 0); ret = (DTM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Ending Notification Date/Time(CNS-4). ///</summary> public DTM EndingNotificationDateTime { get{ DTM ret = null; try { IType t = this.GetField(4, 0); ret = (DTM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Starting Notification Code(CNS-5). ///</summary> public CWE StartingNotificationCode { get{ CWE ret = null; try { IType t = this.GetField(5, 0); ret = (CWE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Ending Notification Code(CNS-6). ///</summary> public CWE EndingNotificationCode { get{ CWE ret = null; try { IType t = this.GetField(6, 0); ret = (CWE)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } }}
32.924731
113
0.677498
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V27/Segment/CNS.cs
6,124
C#
/** * MIT License * * Copyright (c) 2019-2021 Manuel Bottini * * 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.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ValInNewX_script : MonoBehaviour { private GameObject virtualBodynodeToConfigure; private Button thisButton; private Text thisText; void changeSign(){ if (thisText.text [0] == 'x') { thisText.text = 'y'.ToString (); } else if (thisText.text [0] == 'y') { thisText.text = 'z'.ToString (); } else if (thisText.text [0] == 'z') { thisText.text = 'w'.ToString (); } else { thisText.text = 'x'.ToString (); } virtualBodynodeToConfigure.GetComponent<BodynodeControllerX>().mMainPlayer.setAxisVal('x', thisText.text[0]); virtualBodynodeToConfigure.GetComponent<BodynodeControllerX>().resetPosition(); } // Use this for initialization void Start () { thisButton = GetComponent<Button> (); thisText=thisButton.GetComponentInChildren<Text> (); thisText.text = 'x'.ToString(); thisButton.onClick.AddListener (changeSign); virtualBodynodeToConfigure = gameObject.transform.parent.gameObject.GetComponent<CanvasScript>().virtualBodynodeToConfigure; } // Update is called once per frame void Update () { } }
36.65625
127
0.728048
[ "MIT" ]
ManuDev9/body-nodes-host
pc/unity/BodynodesD/Scripts/AxisConfiguration/ValInNewX_script.cs
2,348
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using NUnit.Framework; using SurveySolutionsClient.Apis; using SurveySolutionsClient.Exceptions; using SurveySolutionsClient.Models; namespace SurveySolutionsClient.Tests { public class AssignmentsTests { private HttpClient httpClient; private ISurveySolutionsApi service; private QuestionnaireIdentity questionnaireIdentity; private int assignmentId; [OneTimeSetUp] public async Task OneTimeSetup() { httpClient = new HttpClient(); service = new SurveySolutionsApi(httpClient, ClientSettings.GetConfiguration()); questionnaireIdentity = ClientSettings.Questionnaire; var creationResult = await this.service.Assignments.CreateAsync(new CreateAssignmentRequest { QuestionnaireId = questionnaireIdentity, Quantity = 5, Responsible = "inter", }); this.assignmentId = creationResult.Assignment.Id; } [Test] public async Task can_get_assignment_details() { var response = await service.Assignments.DetailsAsync(1); Assert.That(response, Is.Not.Null); } [Test] public async Task can_get_list_of_assignments() { var response = await service.Assignments.ListAsync(new AssignmentsListFilter { Limit = 5 }); Assert.That(response, Is.Not.Null); } [Test] public async Task can_get_history_of_assignment() { var response = await service.Assignments.HistoryAsync(9); Assert.That(response, Is.Not.Null); } [Test] public async Task can_get_audio_recording_setting() { var response = await service.Assignments.GetAudioRecordingAsync(this.assignmentId); Assert.That(response, Is.Not.Null); } [Test] public async Task can_set_audio_recording() { await service.Assignments.SetAudioRecordingAsync(this.assignmentId, new UpdateRecordingRequest { Enabled = true }); var response = await service.Assignments.GetAudioRecordingAsync(this.assignmentId); Assert.That(response.Enabled, Is.True); } [Test] public async Task can_archive_assignment() { var archiveAsync = await this.service.Assignments.ArchiveAsync(this.assignmentId); Assert.That(archiveAsync.Archived, Is.True); } [Test] public async Task can_unarchive_assignment() { var archiveAsync = await this.service.Assignments.UnArchiveAsync(this.assignmentId); Assert.That(archiveAsync.Archived, Is.False); } [Test] public async Task can_assign() { var archiveAsync = await this.service.Assignments.AssignAsync(this.assignmentId, new AssignmentResponsible("inter1")); Assert.That(archiveAsync.ResponsibleName, Is.EqualTo("inter1")); } [Test] public async Task can_change_quanity() { var archiveAsync = await this.service.Assignments.ChangeQuantityAsync(this.assignmentId, 10); Assert.That(archiveAsync.Quantity, Is.EqualTo(10)); } [Test] public async Task should_be_able_to_close_assignment() { var archiveAsync = await this.service.Assignments.CloseAsync(1); Assert.That(archiveAsync.Quantity, Is.EqualTo(0)); } [Test] public void should_be_able_to_receive_validation_errors_during_assignment_creation() { var exception = Assert.ThrowsAsync<AssignmentCreationException>(() => this.service.Assignments.CreateAsync(new CreateAssignmentRequest { QuestionnaireId = questionnaireIdentity, Comments = "comment", Email = "test@test.com", IsAudioRecordingEnabled = true, Password = "pwd123411", ProtectedVariables = new List<string> {"yn1"}, Quantity = 5, Responsible = "inter", WebMode = true })); Assert.That(exception.CreationResult.VerificationStatus.Errors, Is.Not.Empty); } [Test] public async Task should_be_able_to_create_assignment_without_values() { var creationResult = await this.service.Assignments.CreateAsync(new CreateAssignmentRequest { QuestionnaireId = questionnaireIdentity, Comments = "comment", IsAudioRecordingEnabled = true, ProtectedVariables = new List<string> {"yn1"}, Quantity = 5, Responsible = "inter", }); Assert.That(creationResult.Assignment, Is.Not.Null); } [Test] public async Task should_be_able_to_create_assignment_with_answer() { var creationResult = await this.service.Assignments.CreateAsync(new CreateAssignmentRequest { QuestionnaireId = questionnaireIdentity, Quantity = 5, Responsible = "inter", IdentifyingData = new List<AssignmentIdentifyingDataItem> { new AssignmentIdentifyingDataItem // text question { Answer = "text question", Variable = "text6" }, new AssignmentIdentifyingDataItem // numeric question { Answer = "1", Variable = "numeric7" }, new AssignmentIdentifyingDataItem // list question { Answer = JsonSerializer.Serialize(new []{ "one", "two", "three" }), Variable = "listR1" }, new AssignmentIdentifyingDataItem // gps question { Variable = "gps", Answer = "48.7630568$30.1807397" }, new AssignmentIdentifyingDataItem // multiple choice question { Variable = "ms16", Answer = JsonSerializer.Serialize(new []{ "-2", "3" }), }, new AssignmentIdentifyingDataItem // question in roster { Answer = "test answer inside roster", Identity = new Identity(Guid.Parse("7cc0482b99db1f48a4aff9e04fbd2f71"), new RosterVector(-2)) }, new AssignmentIdentifyingDataItem // yes no question { Variable = "yn1", Answer = JsonSerializer.Serialize(new [] { "20 -> yes", "30 -> no" }) } } }); Assert.That(creationResult.Assignment, Is.Not.Null); } [OneTimeTearDown] public void OneTimeTearDown() { httpClient?.Dispose(); } } }
35.70283
130
0.547364
[ "MIT" ]
V-B/SurveySolutionsClient
src/SurveySolutionsClient.Tests/AssignmentsTests.cs
7,569
C#
using System; namespace Meziantou.GitLabClient.Generator { internal sealed class EntityBuilder { private readonly Action<Entity> _configure; public EntityBuilder(string name, Action<Entity> configure) { Value = new Entity(name); _configure = configure; } public Entity Value { get; } public void Build() { _configure(Value); } public ModelRef MakeCollection() { ModelRef result = Value; return result.MakeCollection(); } public ModelRef MakeCollectionNullable() { ModelRef result = Value; return result.MakeCollectionNullable(); } public ModelRef MakeNullable() { ModelRef result = Value; return result.MakeNullable(); } } }
21.682927
67
0.547807
[ "MIT" ]
meziantou/Meziantou.GitLabClient
src/Meziantou.GitLabClient.Generator/Internals/EntityBuilder.cs
891
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface ActMonitoringProtocolType : Code { } }
36.586207
83
0.711593
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/ActMonitoringProtocolType.cs
1,061
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Data; public partial class Default : System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Transport"].ConnectionString); SqlCommand cmd; string map; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGrid(); } } protected void btn_insert_Click(object sender, EventArgs e) { if (fup_map != null) { fup_map.SaveAs(Server.MapPath("~/Images/Bus/Bus Service/") + fup_map.FileName); map = "~/Images/Bus/Bus Service/" + fup_map.FileName; } cmd = new SqlCommand("INSERT INTO tbl_admin_bus_service (Name, Number, Email, Address, MapURL) VALUES ('" + txt_name.Text.Trim() + "', '" + txt_number.Text.Trim() + "', '" + txt_email.Text.Trim() + "', '" + txt_add.Text.Trim() + "', '" + map + "')", con); cmd.Connection.Open(); cmd.ExecuteNonQuery(); txt_name.Text = ""; txt_number.Text = ""; txt_email.Text = ""; txt_add.Text = ""; cmd.Connection.Close(); BindGrid(); } protected void btn_update_Click(object sender, EventArgs e) { if (fup_map != null) { fup_map.SaveAs(Server.MapPath("~/Images/Bus/Bus Service/") + fup_map.FileName); map = "~/Images/Bus/Bus Service/" + fup_map.FileName; } int Id = Convert.ToInt32(Session["Update"]); cmd = new SqlCommand("UPDATE tbl_admin_bus_service SET Name= '" + txt_name.Text.Trim() + "', Number= '" + txt_number.Text.Trim() + "', Email= '" + txt_email.Text.Trim() + "', Address= '" + txt_add.Text.Trim() + "', MapURL= '" + map + "' WHERE Id= '" + Id + "' ", con); cmd.Connection.Open(); cmd.ExecuteNonQuery(); txt_name.Text = ""; txt_number.Text = ""; txt_email.Text = ""; txt_add.Text = ""; cmd.Connection.Close(); BindGrid(); } protected void btn_delete_Click(object sender, EventArgs e) { cmd = new SqlCommand("DELETE FROM tbl_admin_bus_service WHERE Id= '" + hddn_bus.Value + "' ", con); cmd.Connection.Open(); cmd.ExecuteNonQuery(); txt_name.Text = ""; txt_number.Text = ""; txt_email.Text = ""; txt_add.Text = ""; cmd.Connection.Close(); BindGrid(); } protected void btn_refresh_Click(object sender, EventArgs e) { txt_name.Text = ""; txt_number.Text = ""; txt_email.Text = ""; txt_add.Text = ""; } protected void gv_bus_service_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.ToString() == "gv_edit") { int Id = Convert.ToInt32(e.CommandArgument.ToString()); cmd = new SqlCommand("SELECT * FROM tbl_admin_bus_service WHERE Id='" + Id + "' ", con); cmd.Connection.Open(); Session["Update"] = Id.ToString(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { txt_name.Text = dr["Name"].ToString(); txt_number.Text = dr["Number"].ToString(); txt_email.Text = dr["Email"].ToString(); txt_add.Text = dr["Address"].ToString(); } dr.Dispose(); cmd.Connection.Close(); } if (e.CommandName.ToString() == "gv_delete") { int Id = Convert.ToInt32(e.CommandArgument.ToString()); cmd = new SqlCommand("DELETE FROM tbl_admin_bus_service WHERE Id ='" + Id + "' ", con); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } BindGrid(); } protected void gv_bus_service_PageIndexChanging(object sender, GridViewPageEventArgs e) { gv_bus_service.PageIndex = e.NewPageIndex; BindGrid(); } //protected void gv_bus_RowDataBound(object sender, GridViewRowEventArgs e) //{ // if (e.Row.RowType == DataControlRowType.DataRow) // { // string No = "011"; // string Mob = gv_bus.Rows[0].Cells[3].Text.ToString(); // string Mob_No = No + Mob; // } //} protected void BindGrid() { SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tbl_admin_bus_service", con); DataSet ds = new DataSet(); da.Fill(ds); gv_bus_service.DataSource = ds; gv_bus_service.DataBind(); } }
30.382166
277
0.563103
[ "MIT" ]
ParasGarg/Transport-Management-System
Web Pages/Admin Web Pages/Bus Service.aspx.cs
4,772
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:WeixinNullReferenceException.cs 文件功能描述:对象为null的异常 创建标识:Senparc - 20170912 ----------------------------------------------------------------*/ using System; namespace Senparc.Weixin.Exceptions { /// <summary> /// 菜单异常 /// </summary> public class WeixinNullReferenceException : WeixinException { /// <summary> /// 上一级不为null的对象(或对调试很重要的对象)。 /// 如果需要调试多个对象,可以传入数组,如:new {obj1, obj2} /// </summary> public object ParentObject { get; set; } public WeixinNullReferenceException(string message) : this(message, null, null) { } public WeixinNullReferenceException(string message, object parentObject) : this(message, parentObject, null) { ParentObject = parentObject; } public WeixinNullReferenceException(string message, object parentObject, Exception inner) : base(message, inner) { ParentObject = parentObject; } } }
31.5625
97
0.589109
[ "Apache-2.0" ]
JeremyShih/WeiXinMPSDK
src/Senparc.Weixin/Senparc.Weixin/Exceptions/WeixinNullReferenceException.cs
2,156
C#
using System.Collections.Generic; using System.Runtime.CompilerServices; namespace com.spacepuppy.Collections { /// <summary> /// Tests for equality based solely on if the references are equal. This is useful for UnityEngine.Objects that overrides the default Equals /// operator returning false if it's been destroyed. /// </summary> /// <typeparam name="T"></typeparam> public class ObjectReferenceEqualityComparer<T> : EqualityComparer<T> where T : class { private static IEqualityComparer<T> _defaultComparer; public new static IEqualityComparer<T> Default { get { return _defaultComparer ?? (_defaultComparer = new ObjectReferenceEqualityComparer<T>()); } } #region IEqualityComparer<T> Members public override bool Equals(T x, T y) { return ReferenceEquals(x, y); } public override int GetHashCode(T obj) { return RuntimeHelpers.GetHashCode(obj); } #endregion } }
28.972222
145
0.650048
[ "Unlicense" ]
dipique/spacepuppy-unity-framework-3.0
SpacepuppyUnityFramework/Collections/ObjectReferenceEqualityComparer.cs
1,045
C#
using System; using Stardust.Interstellar; using Stardust.Interstellar.Trace; namespace Stardust.Core.Service.Web { public interface IStardustController { IRuntime Runtime { get; } bool DoInitializationOnActionInvocation { get; } string GetMethodName(Uri requestUri, string action); string GetServiceName(Uri requestUri); void SetTracer(ITracer tracer); } }
20.75
60
0.706024
[ "Apache-2.0" ]
JonasSyrstad/Stardust
Stardust.Core.Service.Web/IStardustController.cs
415
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace AspNetCoreIdentityFido2Mfa.Areas.Identity.Pages.Account { [AllowAnonymous] public class LoginWith2faModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly ILogger<LoginWith2faModel> _logger; public LoginWith2faModel(SignInManager<IdentityUser> signInManager, ILogger<LoginWith2faModel> logger) { _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public bool RememberMe { get; set; } public string ReturnUrl { get; set; } public class InputModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Authenticator code")] public string TwoFactorCode { get; set; } [Display(Name = "Remember this machine")] public bool RememberMachine { get; set; } } public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null) { // Ensure the user has gone through the username & password screen first var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } ReturnUrl = returnUrl; RememberMe = rememberMe; return Page(); } public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null) { if (!ModelState.IsValid) { return Page(); } returnUrl = returnUrl ?? Url.Content("~/"); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id); return LocalRedirect(returnUrl); } else if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return RedirectToPage("./Lockout"); } else { _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id); ModelState.AddModelError(string.Empty, "Invalid authenticator code."); return Page(); } } } }
35.787879
135
0.590742
[ "MIT" ]
PrestigeDevop/AspNetCoreIdentityFido2Mfa
AspNetCoreIdentityFido2Mfa/Areas/Identity/Pages/Account/LoginWith2fa.cshtml.cs
3,545
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 mobileanalytics-2014-06-05.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.MobileAnalytics.Model { /// <summary> /// This is the response object from the PutEvents operation. /// </summary> public partial class PutEventsResponse : AmazonWebServiceResponse { } }
29.972973
113
0.733995
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/MobileAnalytics/Generated/Model/PutEventsResponse.cs
1,109
C#
#region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved. // KEngine - Toolset and framework for Unity3D // =================================== // // Filename: AppEngine.cs // Date: 2015/12/03 // Author: Kelly // Email: 23110388@qq.com // Github: https://github.com/mr-kelly/KEngine // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3.0 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library. #endregion using System; using System.Collections.Generic; using UnityEngine; using System.IO; using System.Text; using TableML; //using KEngine.Table; namespace KEngine.Modules { /// <summary> /// Unity SettingModule, with Resources.Load in product, with File.Read in editor /// </summary> public class SettingModule : SettingModuleBase { public delegate byte[] LoadSettingFuncDelegate(string filePath); public delegate byte[] SettingBytesFilterDelegate(byte[] bytes); /// <summary> /// Filter the loaded bytes, which settings file may be encrypted, so you can manipulate the bytes /// </summary> public static SettingBytesFilterDelegate SettingBytesFilter; /// <summary> /// Override the default load file strategy /// </summary> public static LoadSettingFuncDelegate CustomLoadSetting; private static readonly bool IsEditor; static SettingModule() { IsEditor = Application.isEditor; } /// <summary> /// internal constructor /// </summary> internal SettingModule() { } /// <summary> /// Load KEngineConfig.txt 's `SettingPath` /// </summary> protected static string SettingFolderName { get { return AppEngine.GetConfig("KEngine.Setting", "SettingResourcesPath"); } } /// <summary> /// Singleton /// </summary> private static SettingModule _instance; /// <summary> /// Quick method to get TableFile from instance /// </summary> /// <param name="path"></param> /// <param name="useCache"></param> /// <returns></returns> public static TableFile Get(string path, bool useCache = true) { if (_instance == null) _instance = new SettingModule(); return _instance.GetTableFile(path, useCache); } /// <summary> /// Unity Resources.Load setting file in Resources folder /// </summary> /// <param name="path"></param> /// <returns></returns> protected override string LoadSetting(string path) { byte[] fileContent = CustomLoadSetting != null ? CustomLoadSetting(path) : DefaultLoadSetting(path); return Encoding.UTF8.GetString(fileContent); } /// <summary> /// Default load setting strategry, editor load file, runtime resources.load /// </summary> /// <param name="path"></param> /// <returns></returns> public static byte[] DefaultLoadSetting(string path) { byte[] fileContent; var loader = HotBytesLoader.Load(SettingFolderName + "/" + path, LoaderMode.Sync); Debuger.Assert(!loader.IsError); fileContent = loader.Bytes; loader.Release(); return fileContent; } private static string GetFileSystemPath(string path) { var compilePath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath"); var resPath = Path.Combine(compilePath, path); return resPath; } #if UNITY_EDITOR /// <summary> /// Cache all the FileSystemWatcher, prevent the duplicated one /// </summary> private static Dictionary<string, FileSystemWatcher> _cacheWatchers; /// <summary> /// Watch the setting file, when changed, trigger the delegate /// </summary> /// <param name="path"></param> /// <param name="action"></param> public static void WatchSetting(string path, System.Action<string> action) { if (!IsFileSystemMode) { Log.Error("[WatchSetting] Available in Unity Editor mode only!"); return; } if (_cacheWatchers == null) _cacheWatchers = new Dictionary<string, FileSystemWatcher>(); FileSystemWatcher watcher; var dirPath = Path.GetDirectoryName(GetFileSystemPath(path)); dirPath = dirPath.Replace("\\", "/"); if (!Directory.Exists(dirPath)) { Log.Error("[WatchSetting] Not found Dir: {0}", dirPath); return; } if (!_cacheWatchers.TryGetValue(dirPath, out watcher)) { _cacheWatchers[dirPath] = watcher = new FileSystemWatcher(dirPath); Log.Info("Watching Setting Dir: {0}", dirPath); } watcher.IncludeSubdirectories = false; watcher.Path = dirPath; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Filter = "*"; watcher.EnableRaisingEvents = true; watcher.InternalBufferSize = 2048; watcher.Changed += (sender, e) => { Log.LogConsole_MultiThread("Setting changed: {0}", e.FullPath); action(path); }; } #endif /// <summary> /// whether or not using file system file, in unity editor mode only /// </summary> public static bool IsFileSystemMode { get { if (IsEditor) return true; return false; } } } }
32.969231
112
0.57645
[ "Apache-2.0" ]
GideonDragonHe/MyFrameWork
KSFramework/Assets/Plugins/KEngine/KEngine/CoreModules/SettingModule.cs
6,431
C#
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Dock.Model.Controls; namespace Dock.Model { /// <summary> /// Dock window contract. /// </summary> public interface IDockWindow { /// <summary> /// Gets or sets id. /// </summary> string Id { get; set; } /// <summary> /// Gets or sets window X coordinate. /// </summary> double X { get; set; } /// <summary> /// Gets or sets window X coordinate. /// </summary> double Y { get; set; } /// <summary> /// Gets or sets window width. /// </summary> double Width { get; set; } /// <summary> /// Gets or sets window height. /// </summary> double Height { get; set; } /// <summary> /// Gets or sets whether this window appears on top of all other windows. /// </summary> bool Topmost { get; set; } /// <summary> /// Gets or sets window title. /// </summary> string Title { get; set; } /// <summary> /// Gets or sets window owner dockable. /// </summary> IDockable? Owner { get; set; } /// <summary> /// Gets or sets dock factory. /// </summary> IFactory? Factory { get; set; } /// <summary> /// Gets or sets layout. /// </summary> IRootDock? Layout { get; set; } /// <summary> /// Gets or sets dock window. /// </summary> IHostWindow? Host { get; set; } /// <summary> /// Saves window properties. /// </summary> void Save(); /// <summary> /// Presents window. /// </summary> /// <param name="isDialog">The value that indicates whether window is dialog.</param> void Present(bool isDialog); /// <summary> /// Exits window. /// </summary> void Exit(); /// <summary> /// Clones <see cref="IDockWindow"/> object. /// </summary> /// <returns>The new instance or reference of the <see cref="IDockWindow"/> class.</returns> IDockWindow? Clone(); } }
25.648352
101
0.494859
[ "MIT" ]
ShadowDancer/Dock
src/Dock.Model/Core/IDockWindow.cs
2,339
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Globalization; using NodaTime; using Squidex.Domain.Apps.Core.Schemas; using Squidex.Infrastructure; using Squidex.Infrastructure.Json.Objects; namespace Squidex.Domain.Apps.Core.DefaultValues { public sealed class DefaultValueFactory : IFieldPropertiesVisitor<IJsonValue, DefaultValueFactory.Args> { private static readonly DefaultValueFactory Instance = new DefaultValueFactory(); public readonly struct Args { public readonly Instant Now; public readonly string Partition; public Args(Instant now, string partition) { Now = now; Partition = partition; } } private DefaultValueFactory() { } public static IJsonValue CreateDefaultValue(IField field, Instant now, string partition) { Guard.NotNull(field, nameof(field)); Guard.NotNull(partition, nameof(partition)); return field.RawProperties.Accept(Instance, new Args(now, partition)); } public IJsonValue Visit(ArrayFieldProperties properties, Args args) { return JsonValue.Array(); } public IJsonValue Visit(AssetsFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return Array(value); } public IJsonValue Visit(BooleanFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return JsonValue.Create(value); } public IJsonValue Visit(GeolocationFieldProperties properties, Args args) { return JsonValue.Null; } public IJsonValue Visit(JsonFieldProperties properties, Args args) { return JsonValue.Null; } public IJsonValue Visit(NumberFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return JsonValue.Create(value); } public IJsonValue Visit(ReferencesFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return Array(value); } public IJsonValue Visit(StringFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return JsonValue.Create(value); } public IJsonValue Visit(TagsFieldProperties properties, Args args) { var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return Array(value); } public IJsonValue Visit(UIFieldProperties properties, Args args) { return JsonValue.Null; } public IJsonValue Visit(DateTimeFieldProperties properties, Args args) { if (properties.CalculatedDefaultValue == DateTimeCalculatedDefaultValue.Now) { return JsonValue.Create(args.Now); } if (properties.CalculatedDefaultValue == DateTimeCalculatedDefaultValue.Today) { return JsonValue.Create($"{args.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}T00:00:00Z"); } var value = GetDefaultValue(properties.DefaultValue, properties.DefaultValues, args.Partition); return JsonValue.Create(value); } private static T GetDefaultValue<T>(T value, LocalizedValue<T>? values, string partition) { if (values != null && values.TryGetValue(partition, out var @default)) { return @default; } return value; } private static IJsonValue Array(IEnumerable<string>? values) { if (values != null) { return JsonValue.Array(values); } else { return JsonValue.Array(); } } } }
31.758389
118
0.588969
[ "MIT" ]
Jaben/squidex
backend/src/Squidex.Domain.Apps.Core.Operations/DefaultValues/DefaultValueFactory.cs
4,734
C#
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmssp * * * * 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.Dynamic; using System.Reflection; using Newtonsoft.Json; namespace HMS.SP{ /// <summary> /// <para>https://msdn.microsoft.com/en-us/library/office/jj246309.aspx#properties</para> /// </summary> public class NavigationNodeCollection : SPBase{ [JsonProperty("__HMSError")] public HMS.Util.__HMSError __HMSError_ { set; get; } [JsonProperty("__status")] public SP.__status __status_ { set; get; } [JsonProperty("__deferred")] public SP.__deferred __deferred_ { set; get; } [JsonProperty("__metadata")] public SP.__metadata __metadata_ { set; get; } public Dictionary<string, string> __rest; public List<NavigationNode> items { set; get; } public long Count; // undefined class Function : Object { } /// <summary> /// <para>(s. https://msdn.microsoft.com/en-us/library/office/jj245231.aspx)[Function]</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("ChildItemType")] public Object ChildItemType_ { set; get; } /// <summary> /// <para>Gets the navigation node at the specified index of the collection.(s. https://msdn.microsoft.com/en-us/library/office/jj244939.aspx)</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Item")] public String Item_ { set; get; } /// <summary> /// <para> Endpoints </para> /// </summary> static string[] endpoints = { }; public NavigationNodeCollection(ExpandoObject expObj) { try { var use_EO = ((dynamic)expObj).entry.content.properties; HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(NavigationNodeCollection)); } catch (Exception ex) { } } // used by Newtonsoft.JSON public NavigationNodeCollection() { } public NavigationNodeCollection(string json) { if( json == String.Empty ) return; dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json); dynamic refObj = jobject; if (jobject.d != null) refObj = jobject.d; string errInfo = ""; List<string> usedFields = new List<string>(); usedFields.Add("__HMSError"); HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this); usedFields.Add("__deferred"); this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred)); usedFields.Add("__metadata"); this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata)); usedFields.Add("ChildItemType"); HMS.SP.SPUtil.dyn_ValueSet("ChildItemType", refObj, this); usedFields.Add("Item"); HMS.SP.SPUtil.dyn_ValueSet("Item", refObj, this); if (refObj.results != null) { Count = refObj.results.Count; items = new List<NavigationNode>(); long maxCount = Math.Min(refObj.results.Count, HMS.SP.SPUtil.maxCollectionCount); for (int r = 0; r < (int)maxCount; r++) { NavigationNode fld = new NavigationNode(refObj.results[r].ToString()); items.Add(fld); } } this.__rest = new Dictionary<string, string>(); var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First; while (dyn != null) { string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name; string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString(); if ( !usedFields.Contains( Name )) this.__rest.Add( Name, Value); dyn = dyn.Next; } if( errInfo != "") this.__HMSError_.info = errInfo; } } }
46.29771
157
0.538335
[ "MIT" ]
helmuttheis/hmsspx
hmssp/SP.gen/NavigationNodeCollection.cs
6,065
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Custom.Math; namespace RayTracer2010 { public class TextureShader : Shader { Sampler tex; public vect3d specular_color = new vect3d(1, 1, 1); public double specular_coeff = 100; public TextureShader(string fn) { tex = new Sampler23Lerp(fn); } public override void colorize(Ray r) { vect3d diff_accum = new vect3d(0, 0, 0); vect3d spec_accum = new vect3d(0, 0, 0); lightDirectPointSpec(r, specular_coeff, ref diff_accum, ref spec_accum); vect3d diffuse_color = tex.sample(r.hit_tex_coord); r.color = diff_accum.times(diffuse_color) + spec_accum.times(specular_color); } } }
24.382353
89
0.620024
[ "MIT" ]
AlexAlbala/Alter-Native
Examples/To do/Image synthesis/RayTracer2010/RayTracer2010/TextureShader.cs
831
C#
using nVideo.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace nVideo.Codecs.MPEG12 { public class HLSFixPMT { public void fix(string file) { FileStream ra = null; try { ra = new FileStream(file, FileMode.Open); byte[] tsPkt = new byte[188]; while (ra.Read(tsPkt, 0, 188) == 188) { //Assert.assertEquals(0x47, tsPkt[0] & 0xff); int guidFlags = ((tsPkt[1] & 0xff) << 8) | (tsPkt[2] & 0xff); int guid = (int)guidFlags & 0x1fff; int payloadStart = (guidFlags >> 14) & 0x1; int b0 = tsPkt[3] & 0xff; int counter = b0 & 0xf; int payloadOff = 0; if ((b0 & 0x20) != 0) { payloadOff = (tsPkt[4 + payloadOff] & 0xff) + 1; } if (payloadStart == 1) { payloadOff += (tsPkt[4 + payloadOff] & 0xff) + 1; } if (guid == 0) { if (payloadStart == 0) throw new Exception("PAT spans multiple TS packets, not supported!!!!!!"); MemoryStream bb = StreamExtensions.wrap(tsPkt, 4 + payloadOff, 184 - payloadOff); fixPAT(bb); ra.Seek(ra.Position - 188, SeekOrigin.Current); ra.Write(tsPkt, 0, tsPkt.Length); } } } finally { if (ra != null) ra.Dispose(); } } public static void fixPAT(MemoryStream data) { MemoryStream table = data.duplicate(); //MTSUtils.parseSection(data); MemoryStream newPmt = data.duplicate(); while (data.remaining() > 4) { short num = data.getShort(); short pid = data.getShort(); if (num != 0) { newPmt.putShort(num); newPmt.putShort(pid); } } if (newPmt.position() != data.position()) { // rewrite Section len MemoryStream section = table.duplicate(); section.get(); int sectionLen = newPmt.position() - table.position() + 1; section.putShort((short)((sectionLen & 0xfff) | 0xB000)); // Redo crc32 //CRC32 crc32 = new CRC32(); //table.limit(newPmt.position()); //crc32.update(NIOUtils.toArray(table)); //newPmt.putInt((int) crc32.getValue()); // fill with 0xff while (newPmt.hasRemaining()) newPmt.put((byte)0xff); } } public static void main(String[] args) { //if (args.length < 1) // exit("Please specify package location"); //File hlsPkg = new File(args[0]); //if (!hlsPkg.isDirectory()) // exit("Not an HLS package, expected a folder"); //File[] listFiles = hlsPkg.listFiles(new FilenameFilter() { // public bool accept(File dir, String name) { // return name.endsWith(".ts"); // } //}); //HLSFixPMT fix = new HLSFixPMT(); //for (File file : listFiles) { // System.err.println("Processing: " + file.getName()); // fix.fix(file); //} } private static void exit(String message) { //System.err.println("Syntax: hls_fixpmt <hls package location>"); //System.err.println(message); //System.exit(-1); } } }
34.258065
106
0.41855
[ "Apache-2.0" ]
dxball/mma
nCodec/Codecs/MPEG12/HLSFixPMT.cs
4,250
C#
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The act of interacting with another person or organization. /// </summary> [DataContract] public partial class InteractAction : Action { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "InteractAction"; } }
25.6
67
0.607422
[ "MIT" ]
AndreSteenbergen/Schema.ORG
Source/Schema.NET/core/InteractAction.cs
512
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace PhotoWrap.Droid { [Activity(Label = "PhotoWrap", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
28.357143
186
0.687657
[ "Apache-2.0" ]
DLozanoNavas/xamarin-forms-book-samples
Chapter26/PhotoWrap/PhotoWrap/PhotoWrap.Droid/MainActivity.cs
796
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.IoTDA.V5.Model { /// <summary> /// csv文件格式转换列表 /// </summary> public class CsvMappings { /// <summary> /// **参数说明**:OBS文件中的列名 /// </summary> [JsonProperty("column_name", NullValueHandling = NullValueHandling.Ignore)] public string ColumnName { get; set; } /// <summary> /// **参数说明**:流转数据的属性名 /// </summary> [JsonProperty("json_key", NullValueHandling = NullValueHandling.Ignore)] public string JsonKey { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CsvMappings {\n"); sb.Append(" columnName: ").Append(ColumnName).Append("\n"); sb.Append(" jsonKey: ").Append(JsonKey).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as CsvMappings); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(CsvMappings input) { if (input == null) return false; return ( this.ColumnName == input.ColumnName || (this.ColumnName != null && this.ColumnName.Equals(input.ColumnName)) ) && ( this.JsonKey == input.JsonKey || (this.JsonKey != null && this.JsonKey.Equals(input.JsonKey)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ColumnName != null) hashCode = hashCode * 59 + this.ColumnName.GetHashCode(); if (this.JsonKey != null) hashCode = hashCode * 59 + this.JsonKey.GetHashCode(); return hashCode; } } } }
28.555556
83
0.496887
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net
Services/IoTDA/V5/Model/CsvMappings.cs
2,634
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("IronPython.Modules")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration(BuildInfo.Configuration)] [assembly: AssemblyProduct("IronPython.Modules")] [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("20808534-55dd-4d10-b8f9-96e8f5a1af16")] // 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: SecurityTransparent] [assembly: AllowPartiallyTrustedCallers] #if FEATURE_SECURITY_RULES [assembly: SecurityRules(SecurityRuleSet.Level1)] #endif
38.472727
98
0.699433
[ "Apache-2.0" ]
SueDou/python
Src/IronPython.Modules/Properties/AssemblyInfo.cs
2,118
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 cloudfront-2017-10-30.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.CloudFront.Model { /// <summary> /// A complex type that contains information about the SSL/TLS protocols that CloudFront /// can use when establishing an HTTPS connection with your origin. /// </summary> public partial class OriginSslProtocols { private List<string> _items = new List<string>(); private int? _quantity; /// <summary> /// Gets and sets the property Items. /// <para> /// A list that contains allowed SSL/TLS protocols for this distribution. /// </para> /// </summary> public List<string> Items { get { return this._items; } set { this._items = value; } } // Check to see if Items property is set internal bool IsSetItems() { return this._items != null && this._items.Count > 0; } /// <summary> /// Gets and sets the property Quantity. /// <para> /// The number of SSL/TLS protocols that you want to allow CloudFront to use when establishing /// an HTTPS connection with this origin. /// </para> /// </summary> public int Quantity { get { return this._quantity.GetValueOrDefault(); } set { this._quantity = value; } } // Check to see if Quantity property is set internal bool IsSetQuantity() { return this._quantity.HasValue; } } }
30.935065
108
0.623846
[ "Apache-2.0" ]
HaiNguyenMediaStep/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/OriginSslProtocols.cs
2,382
C#
using System; namespace TestFu.Grammars { /// <summary> /// Expection class used to stop production. /// </summary> public class ProductionException : Exception { private IProduction production; /// <summary> /// /// </summary> /// <param name="production"></param> public ProductionException(IProduction production) { this.production = production; } /// <summary> /// Gets the production that stopped. /// </summary> public IProduction Production { get { return this.production; } } } }
17.515152
53
0.603806
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v2
src/mbunit/TestFu/Grammars/ProductionException.cs
578
C#
namespace ShoelessJoeWebApi.App.ApiModels.PostModels { public class PostUser : ApiUser { public string ConfirmPassword { get; set; } public bool CheckPassword() { if (Password == ConfirmPassword) { return true; } return false; } } }
19.111111
53
0.511628
[ "MIT" ]
TClaypool00/ShoelessJoeApiV2
ShoelessJoeWebApi.App/ApiModels/PostModels/PostUser.cs
346
C#
using System; namespace BaGet.Core.Configuration { public class MirrorOptions { /// <summary> /// If true, packages that aren't found locally will be indexed /// using the upstream source. /// </summary> public bool Enabled { get; set; } /// <summary> /// The v3 index that will be mirrored. /// </summary> public Uri PackageSource { get; set; } /// <summary> /// The time before a download from the package source times out. /// </summary> public int PackageDownloadTimeoutSeconds { get; set; } = 600; } }
27.083333
74
0.544615
[ "MIT" ]
2m0nd/BaGet
src/BaGet.Core/Configuration/MirrorOptions.cs
652
C#
/* * SensorPush Public API * * This is a swagger definition for the SensorPush public REST API. Download the definition file [here](https://api.sensorpush.com/api/v1/support/swagger/swagger-v1.json). * * OpenAPI spec version: v1.0.20200327 * Contact: support@sensorpush.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = Mrc.SensorPushCore.Client.SwaggerDateConverter; namespace Mrc.SensorPushCore.Model { /// <summary> /// Status /// </summary> [DataContract] public partial class Status : IEquatable<Status>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Status" /> class. /// </summary> [JsonConstructorAttribute] protected Status() { } /// <summary> /// Initializes a new instance of the <see cref="Status" /> class. /// </summary> /// <param name="deployed">Date time when this service was last updated..</param> /// <param name="message">Greeting message. (required).</param> /// <param name="stack">Active stack hosting this service..</param> /// <param name="status">Current status of the api service..</param> /// <param name="time">Current date time on the server..</param> /// <param name="version">Version of this service currently deployed.</param> public Status(string deployed = default(string), string message = default(string), string stack = default(string), string status = default(string), string time = default(string), string version = default(string)) { // to ensure "message" is required (not null) if (message == null) { throw new InvalidDataException("message is a required property for Status and cannot be null"); } else { this.Message = message; } this.Deployed = deployed; this.Stack = stack; this._Status = status; this.Time = time; this.Version = version; } /// <summary> /// Date time when this service was last updated. /// </summary> /// <value>Date time when this service was last updated.</value> [DataMember(Name="deployed", EmitDefaultValue=false)] public string Deployed { get; set; } /// <summary> /// Greeting message. /// </summary> /// <value>Greeting message.</value> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; set; } /// <summary> /// Active stack hosting this service. /// </summary> /// <value>Active stack hosting this service.</value> [DataMember(Name="stack", EmitDefaultValue=false)] public string Stack { get; set; } /// <summary> /// Current status of the api service. /// </summary> /// <value>Current status of the api service.</value> [DataMember(Name="status", EmitDefaultValue=false)] public string _Status { get; set; } /// <summary> /// Current date time on the server. /// </summary> /// <value>Current date time on the server.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// Version of this service currently deployed /// </summary> /// <value>Version of this service currently deployed</value> [DataMember(Name="version", EmitDefaultValue=false)] public string Version { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Status {\n"); sb.Append(" Deployed: ").Append(Deployed).Append("\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append(" Stack: ").Append(Stack).Append("\n"); sb.Append(" _Status: ").Append(_Status).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" Version: ").Append(Version).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Status); } /// <summary> /// Returns true if Status instances are equal /// </summary> /// <param name="input">Instance of Status to be compared</param> /// <returns>Boolean</returns> public bool Equals(Status input) { if (input == null) return false; return ( this.Deployed == input.Deployed || (this.Deployed != null && this.Deployed.Equals(input.Deployed)) ) && ( this.Message == input.Message || (this.Message != null && this.Message.Equals(input.Message)) ) && ( this.Stack == input.Stack || (this.Stack != null && this.Stack.Equals(input.Stack)) ) && ( this._Status == input._Status || (this._Status != null && this._Status.Equals(input._Status)) ) && ( this.Time == input.Time || (this.Time != null && this.Time.Equals(input.Time)) ) && ( this.Version == input.Version || (this.Version != null && this.Version.Equals(input.Version)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Deployed != null) hashCode = hashCode * 59 + this.Deployed.GetHashCode(); if (this.Message != null) hashCode = hashCode * 59 + this.Message.GetHashCode(); if (this.Stack != null) hashCode = hashCode * 59 + this.Stack.GetHashCode(); if (this._Status != null) hashCode = hashCode * 59 + this._Status.GetHashCode(); if (this.Time != null) hashCode = hashCode * 59 + this.Time.GetHashCode(); if (this.Version != null) hashCode = hashCode * 59 + this.Version.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
37.357143
220
0.537285
[ "MIT" ]
malako/sensorpush-core
Model/Status.cs
8,368
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Newtonsoft.Json; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] public class AttributeFilterTests { private TestFixture<Startup> _fixture; private Faker<TodoItem> _todoItemFaker; private readonly Faker<Person> _personFaker; public AttributeFilterTests(TestFixture<Startup> fixture) { _fixture = fixture; _todoItemFaker = new Faker<TodoItem>() .RuleFor(t => t.Description, f => f.Lorem.Sentence()) .RuleFor(t => t.Ordinal, f => f.Random.Number()) .RuleFor(t => t.CreatedDate, f => f.Date.Past()); _personFaker = new Faker<Person>() .RuleFor(p => p.FirstName, f => f.Name.FirstName()) .RuleFor(p => p.LastName, f => f.Name.LastName()); } [Fact] public async Task Can_Filter_On_Guid_Properties() { // Arrange var context = _fixture.GetService<AppDbContext>(); var todoItem = _todoItemFaker.Generate(); context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?filter[guidProperty]={todoItem.GuidProperty}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList<TodoItem>(body).Data; var todoItemResponse = list.Single(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(todoItem.Id, todoItemResponse.Id); Assert.Equal(todoItem.GuidProperty, todoItemResponse.GuidProperty); } [Fact] public async Task Can_Filter_On_Related_Attrs() { // Arrange var context = _fixture.GetService<AppDbContext>(); var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoItem.Owner = person; context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?include=owner&filter[owner.firstName]={person.FirstName}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList<TodoItem>(body).Data.First(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); list.Owner.FirstName = person.FirstName; } [Fact] public async Task Cannot_Filter_If_Explicitly_Forbidden() { // Arrange var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?include=owner&filter[achievedDate]={DateTime.UtcNow.Date}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task Can_Filter_On_Not_Equal_Values() { // Arrange var context = _fixture.GetService<AppDbContext>(); var todoItem = _todoItemFaker.Generate(); context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); var totalCount = context.TodoItems.Count(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?page[size]={totalCount}&filter[ordinal]=ne:{todoItem.Ordinal}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList<TodoItem>(body).Data; // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.DoesNotContain(list, x => x.Ordinal == todoItem.Ordinal); } [Fact] public async Task Can_Filter_On_In_Array_Values() { // Arrange var context = _fixture.GetService<AppDbContext>(); var todoItems = _todoItemFaker.Generate(5); var guids = new List<Guid>(); var notInGuids = new List<Guid>(); foreach (var item in todoItems) { context.TodoItems.Add(item); // Exclude 2 items if (guids.Count < (todoItems.Count() - 2)) guids.Add(item.GuidProperty); else notInGuids.Add(item.GuidProperty); } context.SaveChanges(); var totalCount = context.TodoItems.Count(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?filter[guidProperty]=in:{string.Join(",", guids)}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializedTodoItems = _fixture .GetDeserializer() .DeserializeList<TodoItem>(body).Data; // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(guids.Count(), deserializedTodoItems.Count()); foreach (var item in deserializedTodoItems) { Assert.Contains(item.GuidProperty, guids); Assert.DoesNotContain(item.GuidProperty, notInGuids); } } [Fact] public async Task Can_Filter_On_Related_In_Array_Values() { // Arrange var context = _fixture.GetService<AppDbContext>(); var todoItems = _todoItemFaker.Generate(3); var ownerFirstNames = new List<string>(); foreach (var item in todoItems) { var person = _personFaker.Generate(); ownerFirstNames.Add(person.FirstName); item.Owner = person; context.TodoItems.Add(item); } context.SaveChanges(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?include=owner&filter[owner.firstName]=in:{string.Join(",", ownerFirstNames)}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject<Document>(await response.Content.ReadAsStringAsync()); var included = documents.Included; // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(ownerFirstNames.Count(), documents.ManyData.Count()); Assert.NotNull(included); Assert.NotEmpty(included); foreach (var item in included) Assert.Contains(item.Attributes["firstName"], ownerFirstNames); } [Fact] public async Task Can_Filter_On_Not_In_Array_Values() { // Arrange var context = _fixture.GetService<AppDbContext>(); context.TodoItems.RemoveRange(context.TodoItems); context.SaveChanges(); var todoItems = _todoItemFaker.Generate(5); var guids = new List<Guid>(); var notInGuids = new List<Guid>(); foreach (var item in todoItems) { context.TodoItems.Add(item); // Exclude 2 items if (guids.Count < (todoItems.Count() - 2)) guids.Add(item.GuidProperty); else notInGuids.Add(item.GuidProperty); } context.SaveChanges(); var totalCount = context.TodoItems.Count(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?page[size]={totalCount}&filter[guidProperty]=nin:{string.Join(",", notInGuids)}"; var request = new HttpRequestMessage(httpMethod, route); // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializedTodoItems = _fixture .GetDeserializer() .DeserializeList<TodoItem>(body).Data; // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(totalCount - notInGuids.Count(), deserializedTodoItems.Count()); foreach (var item in deserializedTodoItems) { Assert.DoesNotContain(item.GuidProperty, notInGuids); } } } }
39.192
125
0.587977
[ "MIT" ]
ngboardway/JsonApiDotNetCore
test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs
9,798
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DG.Tweening; public class MenuMove : MonoBehaviour { public float sx; public float sy; public float sz; private float x; private float y; private float z; public float time; private float scaleX; private float scaleY; private float scaleZ; private GameObject canvas; public float delay = 0f; void Start(){ canvas = GameObject.Find("Canvas"); // 比率取得 scaleX = canvas.GetComponent<RectTransform>().localScale.x; scaleY = canvas.GetComponent<RectTransform>().localScale.y; scaleZ = canvas.GetComponent<RectTransform>().localScale.z; // 移動先(現在)座標 x = GetComponent<RectTransform>().localPosition.x + canvas.GetComponent<RectTransform>().localPosition.x / scaleX; y = GetComponent<RectTransform>().localPosition.y + canvas.GetComponent<RectTransform>().localPosition.y / scaleY; z = GetComponent<RectTransform>().localPosition.z + canvas.GetComponent<RectTransform>().localPosition.z / scaleZ; // 移動前座標 GetComponent<RectTransform>().localPosition = new Vector3(sx,sy,sz); // 移動 Invoke("Move", delay); } void Move() { // 目的座標に移動 GetComponent<RectTransform>().DOMove(new Vector3(x * scaleX, y * scaleY, z * scaleZ), time); } }
27.826087
116
0.734375
[ "MIT" ]
Dy-gtlf/BeatCluster
Assets/Script/SongSelect/MenuMove.cs
1,332
C#
using AutoFixture; using FakeItEasy; using LinkyLink.Tests.Helpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.Threading; using System.Threading.Tasks; using Xunit; namespace LinkyLink.Tests { public class SaveLinksTests : TestBase { [Fact] public async Task SaveLinks_Empty_Payload_Returns_BadRequest() { // Arrange ILogger fakeLogger = A.Fake<ILogger>(); HttpRequest req = this.DefaultRequest; req.Body = this.GetHttpRequestBodyStream(""); IAsyncCollector<LinkBundle> collector = A.Fake<IAsyncCollector<LinkBundle>>(); // Act IActionResult result = await LinkOperations.SaveLinks(req, collector, fakeLogger); // Assert Assert.IsType<BadRequestObjectResult>(result); A.CallTo(() => collector.AddAsync(A<LinkBundle>.Ignored, CancellationToken.None)).MustNotHaveHappened(); } [Theory] [InlineData("new url")] [InlineData("url.com")] [InlineData("my@$(Surl@F(@LV((")] [InlineData("someurl/")] [InlineData(".com.com")] public async Task SaveLinks_Returns_BadRequest_If_Vanity_Url_Fails_Regex(string vanityUrl) { // Arrange ILogger fakeLogger = A.Fake<ILogger>(); HttpRequest req = this.DefaultRequest; LinkBundle payload = this.Fixture.Create<LinkBundle>(); payload.VanityUrl = vanityUrl; req.Body = this.GetHttpRequestBodyStream(JsonConvert.SerializeObject(payload)); IAsyncCollector<LinkBundle> collector = A.Fake<IAsyncCollector<LinkBundle>>(); // Act IActionResult result = await LinkOperations.SaveLinks(req, collector, fakeLogger); // Assert Assert.IsType<BadRequestResult>(result); A.CallTo(() => collector.AddAsync(A<LinkBundle>.Ignored, CancellationToken.None)).MustNotHaveHappened(); } [Fact] public async Task SaveLinks_Valid_Payload_Returns_CreatRequest() { // Arrange ILogger fakeLogger = A.Fake<ILogger>(); LinkBundle bundle = Fixture.Create<LinkBundle>(); HttpRequest req = this.AuthenticatedRequest; req.Body = this.GetHttpRequestBodyStream(JsonConvert.SerializeObject(bundle)); IAsyncCollector<LinkBundle> collector = A.Fake<IAsyncCollector<LinkBundle>>(); // Act IActionResult result = await LinkOperations.SaveLinks(req, collector, fakeLogger); // Assert Assert.IsType<CreatedResult>(result); CreatedResult createdResult = result as CreatedResult; LinkBundle createdBundle = createdResult.Value as LinkBundle; Assert.Equal("userid", createdBundle.UserId); A.CallTo(() => collector.AddAsync(A<LinkBundle>.That.Matches(b => b.UserId == "userid"), default)).MustHaveHappened(); } [Theory] [InlineData("lower")] [InlineData("UPPER")] [InlineData("MiXEd")] public async Task SaveLinks_Converts_VanityUrl_To_LowerCase(string vanityUrl) { // Arrange ILogger fakeLogger = A.Fake<ILogger>(); LinkBundle bundle = Fixture.Create<LinkBundle>(); bundle.VanityUrl = vanityUrl; HttpRequest req = this.AuthenticatedRequest; req.Body = this.GetHttpRequestBodyStream(JsonConvert.SerializeObject(bundle)); IAsyncCollector<LinkBundle> collector = A.Fake<IAsyncCollector<LinkBundle>>(); // Act IActionResult result = await LinkOperations.SaveLinks(req, collector, fakeLogger); // Assert Assert.IsType<CreatedResult>(result); CreatedResult createdResult = result as CreatedResult; LinkBundle createdBundle = createdResult.Value as LinkBundle; Assert.Equal(vanityUrl.ToLower(), createdBundle.VanityUrl); A.CallTo(() => collector.AddAsync(A<LinkBundle>.That.Matches(b => b.VanityUrl == vanityUrl.ToLower()), default)).MustHaveHappened(); } [Fact] public async Task SaveLinks_Populates_VanityUrl_If_Not_Provided() { // Arrange ILogger fakeLogger = A.Fake<ILogger>(); LinkBundle bundle = Fixture.Create<LinkBundle>(); bundle.VanityUrl = string.Empty; HttpRequest req = this.AuthenticatedRequest; req.Body = this.GetHttpRequestBodyStream(JsonConvert.SerializeObject(bundle)); IAsyncCollector<LinkBundle> collector = A.Fake<IAsyncCollector<LinkBundle>>(); // Act IActionResult result = await LinkOperations.SaveLinks(req, collector, fakeLogger); // Assert Assert.IsType<CreatedResult>(result); CreatedResult createdResult = result as CreatedResult; LinkBundle createdBundle = createdResult.Value as LinkBundle; Assert.False(string.IsNullOrEmpty(createdBundle.VanityUrl)); Assert.Equal(createdBundle.VanityUrl.ToLower(), createdBundle.VanityUrl); A.CallTo(() => collector.AddAsync(A<LinkBundle>.That.Matches(b => !string.IsNullOrEmpty(b.VanityUrl)), default)).MustHaveHappened(); } } }
38.823944
116
0.634682
[ "MIT" ]
softchris/the-urlist
backend/tests/LinkyLink.Tests/SaveLinksTests.cs
5,515
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// ZolozAuthenticationCustomerFaceverifyMatchResponse. /// </summary> public class ZolozAuthenticationCustomerFaceverifyMatchResponse : AlipayResponse { /// <summary> /// 是否为攻击 /// </summary> [JsonPropertyName("attack")] public bool Attack { get; set; } /// <summary> /// 人脸比对结果:成功或者失败 /// </summary> [JsonPropertyName("result")] public string Result { get; set; } } }
24.913043
84
0.598604
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Response/ZolozAuthenticationCustomerFaceverifyMatchResponse.cs
611
C#
using System; using System.Threading.Tasks; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { /// <summary> /// Deletes a profile photo /// </summary> public class DeleteProfilePhoto : Function<Ok> { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "deleteProfilePhoto"; /// <summary> /// Extra data attached to the function /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Identifier of the profile photo to delete /// </summary> [JsonConverter(typeof(Converter.Int64))] [JsonProperty("profile_photo_id")] public long ProfilePhotoId { get; set; } } /// <summary> /// Deletes a profile photo /// </summary> public static Task<Ok> DeleteProfilePhotoAsync( this Client client, long profilePhotoId = default) { return client.ExecuteAsync(new DeleteProfilePhoto { ProfilePhotoId = profilePhotoId }); } } }
28.612245
81
0.523538
[ "MIT" ]
0x25CBFC4F/tdsharp
TDLib.Api/Functions/DeleteProfilePhoto.cs
1,402
C#
 using ETLBox.Connection; using ETLBox.ControlFlow; using ETLBox.ControlFlow.Tasks; using System.Collections.Generic; namespace ETLBox.Logging { /// <summary> /// Will create the default load process table for the default database logging. /// You can then use the `StartLoadProcessTask`, `AbortLoadProcessTask`, `EndLoadProcessTask`. /// These will generate entries in this table and populate the right fields. /// </summary> /// <see cref="StartLoadProcessTask"/> /// <see cref="EndLoadProcessTask" /> /// <see cref="AbortLoadProcessTask" /> public class CreateLoadProcessTableTask : ControlFlowTask { /* ITask Interface */ public override string TaskName => $"Create default etlbox load process table"; public string LoadProcessTableName { get; set; } = Logging.DEFAULTLOADPROCESSTABLENAME; public string Sql => LoadProcessTable.Sql; public CreateTableTask LoadProcessTable { get; private set; } public void Execute() { LoadProcessTable.CopyLogTaskProperties(this); LoadProcessTable.ConnectionManager = this.ConnectionManager; LoadProcessTable.DisableLogging = true; LoadProcessTable.Create(); Logging.LoadProcessTable = LoadProcessTableName; } public CreateLoadProcessTableTask(string loadProcessTableName) { this.LoadProcessTableName = loadProcessTableName; InitCreateTableTask(); } public CreateLoadProcessTableTask(IConnectionManager connectionManager, string loadProcessTableName) : this(loadProcessTableName) { this.ConnectionManager = connectionManager; } private void InitCreateTableTask() { List<TableColumn> lpColumns = new List<TableColumn>() { new TableColumn("id","BIGINT", allowNulls: false, isPrimaryKey: true, isIdentity:true), new TableColumn("start_date","DATETIME", allowNulls: false), new TableColumn("end_date","DATETIME", allowNulls: true), new TableColumn("source","NVARCHAR(20)", allowNulls: true), new TableColumn("process_name","NVARCHAR(100)", allowNulls: false) { DefaultValue = "N/A" }, new TableColumn("start_message","NVARCHAR(2000)", allowNulls: true) , new TableColumn("is_running","SMALLINT", allowNulls: false) { DefaultValue = "1" }, new TableColumn("end_message","NVARCHAR(2000)", allowNulls: true) , new TableColumn("was_successful","SMALLINT", allowNulls: false) { DefaultValue = "0" }, new TableColumn("abort_message","NVARCHAR(2000)", allowNulls: true) , new TableColumn("was_aborted","SMALLINT", allowNulls: false) { DefaultValue = "0" } }; LoadProcessTable = new CreateTableTask(LoadProcessTableName, lpColumns) { DisableLogging = true }; } public static void Create(string loadProcessTableName = Logging.DEFAULTLOADPROCESSTABLENAME) => new CreateLoadProcessTableTask(loadProcessTableName).Execute(); public static void Create(IConnectionManager connectionManager, string loadProcessTableName = Logging.DEFAULTLOADPROCESSTABLENAME) => new CreateLoadProcessTableTask(connectionManager, loadProcessTableName).Execute(); } }
48.661972
138
0.658466
[ "MIT" ]
gjvanvuuren/etlbox
ETLBox/src/Toolbox/Logging/CreateLoadProcessTableTask.cs
3,457
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests.Nano { /// <summary> /// Default Test /// </summary> public abstract class DefaultTest : BaseTest { /// <inheritdoc/> [TestCleanup] public override void Cleanup() { } /// <inheritdoc/> [TestInitialize] public override void Initialize() { } } }
17.958333
51
0.522042
[ "MIT" ]
kilnan/Nano.Library
.tests/Tests.Nano/DefaultTest.cs
431
C#
// Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/ // Licensed under MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using DataLayer.EfCode; using DataLayer.MultiTenantClasses; using PermissionParts; [assembly: InternalsVisibleTo("Test")] namespace ServiceLayer.SeedDemo.Internal { /// <summary> /// This is a extension method that converts a given format of text data (see default companyDefinitions) /// in to a set of tenants with hierarchical links between them. Just used to demo tenant data for display or unit testing /// ONLY USED FOR DEMO and UNIT TESTING /// </summary> public static class HierarchicalSeeder { public static List<Company> AddCompanyAndChildrenInDatabase(this CompanyDbContext context, params string[] companyDefinitions) { if (!companyDefinitions.Any()) companyDefinitions = new[] { "4U Inc.|West Coast|San Fran|SF Dress4U, SF Tie4U, SF Shirt4U", "4U Inc.|West Coast|LA|LA Dress4U, LA Tie4U, LA Shirt4U" }; var companyDict = new Dictionary<string, Company>(); var subGroupsDict = new Dictionary<int, List<SubGroup>>(); foreach (var companyDefinition in companyDefinitions) { var hierarchyNames = companyDefinition.Split('|'); if (!companyDict.ContainsKey(hierarchyNames[0])) { companyDict[hierarchyNames[0]] = Company.AddTenantToDatabaseWithSaveChanges( hierarchyNames[0], PaidForModules.None, context); subGroupsDict.Clear(); } TenantBase parent = companyDict[hierarchyNames[0]]; for (int i = 1; i < hierarchyNames.Length; i++) { if (!subGroupsDict.ContainsKey(i)) { subGroupsDict[i] = new List<SubGroup>(); } if (i + 1 == hierarchyNames.Length) { //End, which are shops var shopNames = hierarchyNames[i].Split(',').Select(x => x.Trim()); foreach (var shopName in shopNames) { RetailOutlet.AddTenantToDatabaseWithSaveChanges(shopName, parent, context); } } else { //Groups SubGroup subGroup = null; if (subGroupsDict[i].Any(x => x.Name == hierarchyNames[i])) { subGroup = subGroupsDict[i].Single(x => x.Name == hierarchyNames[i]); } else { subGroup = SubGroup.AddTenantToDatabaseWithSaveChanges(hierarchyNames[i], parent, context); subGroupsDict[i].Add(subGroup); } parent = subGroup; } } } return new List<Company>(companyDict.Values); } } }
42.148148
134
0.521675
[ "MIT" ]
TDK1964/PermissionAccessControl2
ServiceLayer/SeedDemo/Internal/HierarchicalSeeder.cs
3,416
C#
#pragma checksum "C:\Users\alptu\Source\Repos\RaspberryPi2Application\RaspberryPi2Application\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "88517B4EB4739F640BC2403FA7BAD903" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RaspberryPi2Application { #if !DISABLE_XAML_GENERATED_MAIN /// <summary> /// Program class /// </summary> public static class Program { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] static void Main(string[] args) { global::Windows.UI.Xaml.Application.Start((p) => new App()); } } #endif partial class App : global::Windows.UI.Xaml.Application { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; #if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT DebugSettings.BindingFailed += (sender, args) => { global::System.Diagnostics.Debug.WriteLine(args.Message); }; #endif #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += (sender, e) => { if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break(); }; #endif } } }
36.366667
180
0.597159
[ "MIT" ]
carpediem23/RaspberryPi2Application
RaspberryPi2Application/obj/ARM/Release/App.g.i.cs
2,184
C#
using System.Collections.Generic; using System.Linq; namespace Kata.December2017 { public class PhoneNumber { public static string CreatePhoneNumber(int[] numbers) { var areaCode = IntegerArrayToString(numbers.Take(3)); var prefix = IntegerArrayToString(numbers.Skip(3).Take(3)); var suffix = IntegerArrayToString(numbers.Skip(6).Take(4)); return $"({areaCode}) {prefix}-{suffix}"; } public static string IntegerArrayToString(IEnumerable<int> input) { return new string(input.Select(x => char.Parse(x.ToString())).ToArray()); } } }
29.5
85
0.625578
[ "MIT" ]
ssfcultra/Katas
KeithKatas/201712/PhoneNumber.cs
651
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using MySqlConnector.Core; using MySqlConnector.Diagnostics; using MySqlConnector.Logging; using MySqlConnector.Protocol.Payloads; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySql.Data.MySqlClient { public sealed class MySqlConnection : DbConnection #if !NETSTANDARD1_3 , ICloneable #endif { public MySqlConnection() : this(default) { } public MySqlConnection(string? connectionString) { GC.SuppressFinalize(this); m_connectionString = connectionString ?? ""; } public new MySqlTransaction BeginTransaction() => (MySqlTransaction) base.BeginTransaction(); public new MySqlTransaction BeginTransaction(IsolationLevel isolationLevel) => (MySqlTransaction) base.BeginTransaction(isolationLevel); protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => BeginDbTransactionAsync(isolationLevel, IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public ValueTask<MySqlTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default) => BeginDbTransactionAsync(IsolationLevel.Unspecified, AsyncIOBehavior, cancellationToken); public ValueTask<MySqlTransaction> BeginTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken = default) => BeginDbTransactionAsync(isolationLevel, AsyncIOBehavior, cancellationToken); #else public new ValueTask<MySqlTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default) => BeginDbTransactionAsync(IsolationLevel.Unspecified, AsyncIOBehavior, cancellationToken); public new ValueTask<MySqlTransaction> BeginTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken = default) => BeginDbTransactionAsync(isolationLevel, AsyncIOBehavior, cancellationToken); protected override async ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken) => await BeginDbTransactionAsync(isolationLevel, AsyncIOBehavior, cancellationToken).ConfigureAwait(false); #endif private async ValueTask<MySqlTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, IOBehavior ioBehavior, CancellationToken cancellationToken) { if (State != ConnectionState.Open) throw new InvalidOperationException("Connection is not open."); if (CurrentTransaction is object) throw new InvalidOperationException("Transactions may not be nested."); #if !NETSTANDARD1_3 if (m_enlistedTransaction is object) throw new InvalidOperationException("Cannot begin a transaction when already enlisted in a transaction."); #endif var isolationLevelValue = isolationLevel switch { IsolationLevel.ReadUncommitted => "read uncommitted", IsolationLevel.ReadCommitted => "read committed", IsolationLevel.RepeatableRead => "repeatable read", IsolationLevel.Serializable => "serializable", IsolationLevel.Snapshot => "repeatable read", // "In terms of the SQL:1992 transaction isolation levels, the default InnoDB level is REPEATABLE READ." - http://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-model.html IsolationLevel.Unspecified => "repeatable read", _ => throw new NotSupportedException("IsolationLevel.{0} is not supported.".FormatInvariant(isolationLevel)) }; using (var cmd = new MySqlCommand($"set session transaction isolation level {isolationLevelValue};", this)) { await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false); var consistentSnapshotText = isolationLevel == IsolationLevel.Snapshot ? " with consistent snapshot" : ""; cmd.CommandText = $"start transaction{consistentSnapshotText};"; await cmd.ExecuteNonQueryAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } var transaction = new MySqlTransaction(this, isolationLevel); CurrentTransaction = transaction; return transaction; } #if !NETSTANDARD1_3 public override void EnlistTransaction(System.Transactions.Transaction? transaction) { if (State != ConnectionState.Open) throw new InvalidOperationException("Connection is not open."); // ignore reenlistment of same connection in same transaction if (m_enlistedTransaction?.Transaction.Equals(transaction) ?? false) return; if (m_enlistedTransaction is object) throw new MySqlException("Already enlisted in a Transaction."); if (CurrentTransaction is object) throw new InvalidOperationException("Can't enlist in a Transaction when there is an active MySqlTransaction."); if (transaction is object) { var existingConnection = FindExistingEnlistedSession(transaction); if (existingConnection is object) { // can reuse the existing connection CloseAsync(changeState: false, IOBehavior.Synchronous).GetAwaiter().GetResult(); TakeSessionFrom(existingConnection); return; } else { m_enlistedTransaction = GetInitializedConnectionSettings().UseXaTransactions ? (EnlistedTransactionBase)new XaEnlistedTransaction(transaction, this) : new StandardEnlistedTransaction(transaction, this); m_enlistedTransaction.Start(); lock (s_lock) { if (!s_transactionConnections.TryGetValue(transaction, out var enlistedTransactions)) s_transactionConnections[transaction] = enlistedTransactions = new List<EnlistedTransactionBase>(); enlistedTransactions.Add(m_enlistedTransaction); } } } } internal void UnenlistTransaction() { var transaction = m_enlistedTransaction!.Transaction; m_enlistedTransaction = null; // find this connection in the list of connections associated with the transaction bool? wasIdle = null; lock (s_lock) { var enlistedTransactions = s_transactionConnections[transaction]; for (int i = 0; i < enlistedTransactions.Count; i++) { if (enlistedTransactions[i].Connection == this) { wasIdle = enlistedTransactions[i].IsIdle; enlistedTransactions.RemoveAt(i); break; } } if (enlistedTransactions.Count == 0) s_transactionConnections.Remove(transaction); } // if the connection was idle (i.e., the client already closed it), really close it now if (wasIdle is null) throw new InvalidOperationException("Didn't find transaction"); if (wasIdle.Value) Close(); } // If there is an idle (i.e., no client has it open) MySqlConnection thats part of 'transaction', // returns it; otherwise, returns null. If a valid MySqlConnection is returned, the current connection // has been stored in 's_transactionConnections' and the caller must call TakeSessionFrom to // transfer its session to this MySqlConnection. // Also performs validation checks to ensure that XA and non-XA transactions aren't being mixed. private MySqlConnection? FindExistingEnlistedSession(System.Transactions.Transaction transaction) { var hasEnlistedTransactions = false; var hasXaTransaction = false; lock (s_lock) { if (s_transactionConnections.TryGetValue(transaction, out var enlistedTransactions)) { hasEnlistedTransactions = true; foreach (var enlistedTransaction in enlistedTransactions) { hasXaTransaction = enlistedTransaction.Connection.GetInitializedConnectionSettings().UseXaTransactions; if (enlistedTransaction.IsIdle && enlistedTransaction.Connection.m_connectionString == m_connectionString) { var existingConnection = enlistedTransaction.Connection; enlistedTransaction.Connection = this; enlistedTransaction.IsIdle = false; return existingConnection; } } } } // no valid existing connection was found; verify that constraints aren't violated if (GetInitializedConnectionSettings().UseXaTransactions) { if (hasEnlistedTransactions && !hasXaTransaction) throw new NotSupportedException("Cannot start an XA transaction when there is an existing non-XA transaction."); } else if (hasEnlistedTransactions) { throw new NotSupportedException("Multiple simultaneous connections or connections with different connection strings inside the same transaction are not supported when UseXaTransactions=False."); } return null; } private void TakeSessionFrom(MySqlConnection other) { #if DEBUG if (other is null) throw new ArgumentNullException(nameof(other)); if (m_session is object) throw new InvalidOperationException("This connection must not have a session"); if (other.m_session is null) throw new InvalidOperationException("Other connection must have a session"); if (m_enlistedTransaction is object) throw new InvalidOperationException("This connection must not have an enlisted transaction"); if (other.m_enlistedTransaction is null) throw new InvalidOperationException("Other connection must have an enlisted transaction"); if (m_activeReader is object) throw new InvalidOperationException("This connection must not have an active reader"); if (other.m_activeReader is object) throw new InvalidOperationException("Other connection must not have an active reader"); #endif m_session = other.m_session; m_session!.OwningConnection = new WeakReference<MySqlConnection>(this); other.m_session = null; m_cachedProcedures = other.m_cachedProcedures; other.m_cachedProcedures = null; m_enlistedTransaction = other.m_enlistedTransaction; other.m_enlistedTransaction = null; } EnlistedTransactionBase? m_enlistedTransaction; #endif public override void Close() => CloseAsync(changeState: true, IOBehavior.Synchronous).GetAwaiter().GetResult(); #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public Task CloseAsync() => CloseAsync(changeState: true, SimpleAsyncIOBehavior); #else public override Task CloseAsync() => CloseAsync(changeState: true, SimpleAsyncIOBehavior); #endif internal Task CloseAsync(IOBehavior ioBehavior) => CloseAsync(changeState: true, ioBehavior); public override void ChangeDatabase(string databaseName) => ChangeDatabaseAsync(IOBehavior.Synchronous, databaseName, CancellationToken.None).GetAwaiter().GetResult(); #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public Task ChangeDatabaseAsync(string databaseName, CancellationToken cancellationToken = default) => ChangeDatabaseAsync(AsyncIOBehavior, databaseName, cancellationToken); #else public override Task ChangeDatabaseAsync(string databaseName, CancellationToken cancellationToken = default) => ChangeDatabaseAsync(AsyncIOBehavior, databaseName, cancellationToken); #endif private async Task ChangeDatabaseAsync(IOBehavior ioBehavior, string databaseName, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(databaseName)) throw new ArgumentException("Database name is not valid.", nameof(databaseName)); if (State != ConnectionState.Open) throw new InvalidOperationException("Connection is not open."); using (var initDatabasePayload = InitDatabasePayload.Create(databaseName)) await m_session!.SendAsync(initDatabasePayload, ioBehavior, cancellationToken).ConfigureAwait(false); var payload = await m_session.ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); OkPayload.Create(payload.Span, m_session.SupportsDeprecateEof, m_session.SupportsSessionTrack); m_session.DatabaseOverride = databaseName; } public new MySqlCommand CreateCommand() => (MySqlCommand)base.CreateCommand(); public bool Ping() => PingAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); public Task<bool> PingAsync(CancellationToken cancellationToken = default) => PingAsync(SimpleAsyncIOBehavior, cancellationToken).AsTask(); private async ValueTask<bool> PingAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { if (m_session is null) return false; try { if (await m_session.TryPingAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) return true; } catch (InvalidOperationException) { } SetState(ConnectionState.Closed); return false; } public override void Open() => OpenAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); public override Task OpenAsync(CancellationToken cancellationToken) => OpenAsync(default, cancellationToken); private async Task OpenAsync(IOBehavior? ioBehavior, CancellationToken cancellationToken) { VerifyNotDisposed(); if (State != ConnectionState.Closed) throw new InvalidOperationException("Cannot Open when State is {0}.".FormatInvariant(State)); var openStartTickCount = Environment.TickCount; SetState(ConnectionState.Connecting); var pool = ConnectionPool.GetPool(m_connectionString); m_connectionSettings ??= pool?.ConnectionSettings ?? new ConnectionSettings(new MySqlConnectionStringBuilder(m_connectionString)); #if !NETSTANDARD1_3 // check if there is an open session (in the current transaction) that can be adopted if (m_connectionSettings.AutoEnlist && System.Transactions.Transaction.Current is object) { var existingConnection = FindExistingEnlistedSession(System.Transactions.Transaction.Current); if (existingConnection is object) { TakeSessionFrom(existingConnection); m_hasBeenOpened = true; SetState(ConnectionState.Open); return; } } #endif Exception? e = null; var operationId = _diagnosticListener.WriteConnectionOpenBefore(this); try { m_session = await CreateSessionAsync(pool, openStartTickCount, ioBehavior, cancellationToken).ConfigureAwait(false); m_hasBeenOpened = true; SetState(ConnectionState.Open); } catch (MySqlException ex) { e = ex; SetState(ConnectionState.Closed); throw; } catch (SocketException ex) { e = ex; SetState(ConnectionState.Closed); throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, "Unable to connect to any of the specified MySQL hosts.", ex); } finally { if (e != null) { _diagnosticListener.WriteConnectionOpenError(operationId, this, e); } else { _diagnosticListener.WriteConnectionOpenAfter(operationId, this); } } #if !NETSTANDARD1_3 if (m_connectionSettings.AutoEnlist && System.Transactions.Transaction.Current is object) EnlistTransaction(System.Transactions.Transaction.Current); #endif } [AllowNull] public override string ConnectionString { get { if (!m_hasBeenOpened) return m_connectionString; var connectionStringBuilder = GetConnectionSettings().ConnectionStringBuilder; return connectionStringBuilder.GetConnectionString(connectionStringBuilder.PersistSecurityInfo); } set { if (m_connectionState == ConnectionState.Open) throw new InvalidOperationException("Cannot change the connection string on an open connection."); m_hasBeenOpened = false; m_connectionString = value ?? ""; m_connectionSettings = null; } } public override string Database => m_session?.DatabaseOverride ?? GetConnectionSettings().Database; public override ConnectionState State => m_connectionState; public override string DataSource => GetConnectionSettings().ConnectionStringBuilder.Server; public override string ServerVersion => Session.ServerVersion.OriginalString; public int ServerThread => Session.ConnectionId; public static void ClearPool(MySqlConnection connection) => ClearPoolAsync(connection, IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); public static Task ClearPoolAsync(MySqlConnection connection, CancellationToken cancellationToken = default) => ClearPoolAsync(connection, connection.AsyncIOBehavior, cancellationToken); public static void ClearAllPools() => ConnectionPool.ClearPoolsAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); public static Task ClearAllPoolsAsync(CancellationToken cancellationToken = default) => ConnectionPool.ClearPoolsAsync(IOBehavior.Asynchronous, cancellationToken); private static async Task ClearPoolAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken) { if (connection is null) throw new ArgumentNullException(nameof(connection)); var pool = ConnectionPool.GetPool(connection.m_connectionString); if (pool is object) await pool.ClearAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } protected override DbCommand CreateDbCommand() => new MySqlCommand(this, null); #if !NETSTANDARD1_3 protected override DbProviderFactory DbProviderFactory => MySqlClientFactory.Instance; /// <inheritdoc cref="DbConnection.GetSchema()"/> public override DataTable GetSchema() => GetSchemaProvider().GetSchema(); /// <inheritdoc cref="DbConnection.GetSchema(string)"/> public override DataTable GetSchema(string collectionName) => GetSchemaProvider().GetSchema(collectionName); /// <inheritdoc cref="DbConnection.GetSchema(string)"/> public override DataTable GetSchema(string collectionName, string?[] restrictions) => GetSchemaProvider().GetSchema(collectionName); private SchemaProvider GetSchemaProvider() { if (m_schemaProvider is null) m_schemaProvider = new SchemaProvider(this); return m_schemaProvider; } SchemaProvider? m_schemaProvider; #endif /// <summary> /// Gets the time (in seconds) to wait while trying to establish a connection /// before terminating the attempt and generating an error. This value /// is controlled by <see cref="MySqlConnectionStringBuilder.ConnectionTimeout"/>, /// which defaults to 15 seconds. /// </summary> public override int ConnectionTimeout => GetConnectionSettings().ConnectionTimeout; public event MySqlInfoMessageEventHandler? InfoMessage; public MySqlBatch CreateBatch() => CreateDbBatch(); private MySqlBatch CreateDbBatch() => new MySqlBatch(this); public MySqlBatchCommand CreateBatchCommand() => CreateDbBatchCommand(); private MySqlBatchCommand CreateDbBatchCommand() => new MySqlBatchCommand(); public bool CanCreateBatch => true; protected override void Dispose(bool disposing) { try { if (disposing) CloseAsync(changeState: true, IOBehavior.Synchronous).GetAwaiter().GetResult(); } finally { m_isDisposed = true; base.Dispose(disposing); } } #if !NETSTANDARD2_1 && !NETCOREAPP3_0 public async Task DisposeAsync() #else public override async ValueTask DisposeAsync() #endif { try { await CloseAsync(changeState: true, SimpleAsyncIOBehavior).ConfigureAwait(false); } finally { m_isDisposed = true; } } public MySqlConnection Clone() => new MySqlConnection(m_connectionString, m_hasBeenOpened); #if !NETSTANDARD1_3 object ICloneable.Clone() => Clone(); #endif /// <summary> /// Returns an unopened copy of this connection with a new connection string. If the <c>Password</c> /// in <paramref name="connectionString"/> is not set, the password from this connection will be used. /// This allows creating a new connection with the same security information while changing other options, /// such as database or pooling. /// </summary> /// <param name="connectionString">The new connection string to be used.</param> /// <returns>A new <see cref="MySqlConnection"/> with different connection string options but /// the same password as this connection (unless overridden by <paramref name="connectionString"/>).</returns> public MySqlConnection CloneWith(string connectionString) { var newBuilder = new MySqlConnectionStringBuilder(connectionString ?? throw new ArgumentNullException(nameof(connectionString))); var currentBuilder = new MySqlConnectionStringBuilder(m_connectionString); var shouldCopyPassword = newBuilder.Password.Length == 0 && (!newBuilder.PersistSecurityInfo || currentBuilder.PersistSecurityInfo); if (shouldCopyPassword) newBuilder.Password = currentBuilder.Password; return new MySqlConnection(newBuilder.ConnectionString, m_hasBeenOpened && shouldCopyPassword && !currentBuilder.PersistSecurityInfo); } internal ServerSession Session { get { VerifyNotDisposed(); if (m_session is null || State != ConnectionState.Open) throw new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(State)); return m_session; } } internal void SetSessionFailed(Exception exception) => m_session!.SetFailed(exception); internal void Cancel(ICancellableCommand command) { var session = Session; if (!session.TryStartCancel(command)) return; try { // open a dedicated connection to the server to kill the active query var csb = new MySqlConnectionStringBuilder(m_connectionString); csb.Pooling = false; if (m_session!.IPAddress is object) csb.Server = m_session.IPAddress.ToString(); csb.ConnectionTimeout = 3u; using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); using var killCommand = new MySqlCommand("KILL QUERY {0}".FormatInvariant(command.Connection!.ServerThread), connection); session.DoCancel(command, killCommand); } catch (MySqlException ex) { // cancelling the query failed; setting the state back to 'Querying' will allow another call to 'Cancel' to try again Log.Warn(ex, "Session{0} cancelling command {1} failed", m_session!.Id, command.CommandId); session.AbortCancel(command); } } internal async Task<CachedProcedure?> GetCachedProcedure(string name, bool revalidateMissing, IOBehavior ioBehavior, CancellationToken cancellationToken) { if (Log.IsDebugEnabled()) Log.Debug("Session{0} getting cached procedure Name={1}", m_session!.Id, name); if (State != ConnectionState.Open) throw new InvalidOperationException("Connection is not open."); var cachedProcedures = m_session!.Pool?.GetProcedureCache() ?? m_cachedProcedures; if (cachedProcedures is null) { Log.Warn("Session{0} pool Pool{1} doesn't have a shared procedure cache; procedure will only be cached on this connection", m_session.Id, m_session.Pool?.Id); cachedProcedures = m_cachedProcedures = new Dictionary<string, CachedProcedure?>(); } var normalized = NormalizedSchema.MustNormalize(name, Database); if (string.IsNullOrEmpty(normalized.Schema)) { Log.Warn("Session{0} couldn't normalize Database={1} Name={2}; not caching procedure", m_session.Id, Database, name); return null; } CachedProcedure? cachedProcedure; bool foundProcedure; lock (cachedProcedures) foundProcedure = cachedProcedures.TryGetValue(normalized.FullyQualified, out cachedProcedure); if (!foundProcedure || (cachedProcedure is null && revalidateMissing)) { cachedProcedure = await CachedProcedure.FillAsync(ioBehavior, this, normalized.Schema!, normalized.Component!, cancellationToken).ConfigureAwait(false); if (Log.IsWarnEnabled()) { if (cachedProcedure is null) Log.Warn("Session{0} failed to cache procedure Schema={1} Component={2}", m_session.Id, normalized.Schema, normalized.Component); else Log.Info("Session{0} caching procedure Schema={1} Component={2}", m_session.Id, normalized.Schema, normalized.Component); } int count; lock (cachedProcedures) { cachedProcedures[normalized.FullyQualified] = cachedProcedure; count = cachedProcedures.Count; } if (Log.IsInfoEnabled()) Log.Info("Session{0} procedure cache Count={1}", m_session.Id, count); } if (Log.IsWarnEnabled()) { if (cachedProcedure is null) Log.Warn("Session{0} did not find cached procedure Schema={1} Component={2}", m_session.Id, normalized.Schema, normalized.Component); else Log.Debug("Session{0} returning cached procedure Schema={1} Component={2}", m_session.Id, normalized.Schema, normalized.Component); } return cachedProcedure; } internal MySqlTransaction? CurrentTransaction { get; set; } internal bool AllowLoadLocalInfile => GetInitializedConnectionSettings().AllowLoadLocalInfile; internal bool AllowUserVariables => GetInitializedConnectionSettings().AllowUserVariables; internal bool AllowZeroDateTime => GetInitializedConnectionSettings().AllowZeroDateTime; internal bool ConvertZeroDateTime => GetInitializedConnectionSettings().ConvertZeroDateTime; internal DateTimeKind DateTimeKind => GetInitializedConnectionSettings().DateTimeKind; internal int DefaultCommandTimeout => GetConnectionSettings().DefaultCommandTimeout; internal MySqlGuidFormat GuidFormat => GetInitializedConnectionSettings().GuidFormat; #if NETSTANDARD1_3 internal bool IgnoreCommandTransaction => GetInitializedConnectionSettings().IgnoreCommandTransaction; #else internal bool IgnoreCommandTransaction => GetInitializedConnectionSettings().IgnoreCommandTransaction || m_enlistedTransaction is StandardEnlistedTransaction; #endif internal bool IgnorePrepare => GetInitializedConnectionSettings().IgnorePrepare; internal bool NoBackslashEscapes => GetInitializedConnectionSettings().NoBackslashEscapes; internal bool TreatTinyAsBoolean => GetInitializedConnectionSettings().TreatTinyAsBoolean; internal IOBehavior AsyncIOBehavior => GetConnectionSettings().ForceSynchronous ? IOBehavior.Synchronous : IOBehavior.Asynchronous; // Defaults to IOBehavior.Synchronous if the connection hasn't been opened yet; only use if it's a no-op for a closed connection. internal IOBehavior SimpleAsyncIOBehavior => (m_connectionSettings?.ForceSynchronous ?? false) ? IOBehavior.Synchronous : IOBehavior.Asynchronous; internal MySqlSslMode SslMode => GetInitializedConnectionSettings().SslMode; internal bool HasActiveReader => m_activeReader is object; internal void SetActiveReader(MySqlDataReader dataReader) { if (dataReader is null) throw new ArgumentNullException(nameof(dataReader)); if (m_activeReader is object) throw new InvalidOperationException("Can't replace active reader."); m_activeReader = dataReader; } internal void FinishQuerying(bool hasWarnings) { m_session!.FinishQuerying(); m_activeReader = null; if (hasWarnings && InfoMessage is object) { var errors = new List<MySqlError>(); using (var command = new MySqlCommand("SHOW WARNINGS;", this)) using (var reader = command.ExecuteReader()) { while (reader.Read()) errors.Add(new MySqlError(reader.GetString(0), reader.GetInt32(1), reader.GetString(2))); } InfoMessage(this, new MySqlInfoMessageEventArgs(errors.ToArray())); } } private async ValueTask<ServerSession> CreateSessionAsync(ConnectionPool? pool, int startTickCount, IOBehavior? ioBehavior, CancellationToken cancellationToken) { var connectionSettings = GetInitializedConnectionSettings(); var actualIOBehavior = ioBehavior ?? (connectionSettings.ForceSynchronous ? IOBehavior.Synchronous : IOBehavior.Asynchronous); CancellationTokenSource? timeoutSource = null; CancellationTokenSource? linkedSource = null; try { // the cancellation token for connection is controlled by 'cancellationToken' (if it can be cancelled), ConnectionTimeout // (from the connection string, if non-zero), or a combination of both if (connectionSettings.ConnectionTimeout != 0) timeoutSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(Math.Max(1, connectionSettings.ConnectionTimeoutMilliseconds - unchecked(Environment.TickCount - startTickCount)))); if (cancellationToken.CanBeCanceled && timeoutSource is object) linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutSource.Token); var connectToken = linkedSource?.Token ?? timeoutSource?.Token ?? cancellationToken; // get existing session from the pool if possible if (pool is object) { // this returns an open session return await pool.GetSessionAsync(this, startTickCount, actualIOBehavior, connectToken).ConfigureAwait(false); } else { // only "fail over" and "random" load balancers supported without connection pooling var loadBalancer = connectionSettings.LoadBalance == MySqlLoadBalance.Random && connectionSettings.HostNames!.Count > 1 ? RandomLoadBalancer.Instance : FailOverLoadBalancer.Instance; var session = new ServerSession(); session.OwningConnection = new WeakReference<MySqlConnection>(this); Log.Info("Created new non-pooled Session{0}", session.Id); await session.ConnectAsync(connectionSettings, startTickCount, loadBalancer, actualIOBehavior, connectToken).ConfigureAwait(false); return session; } } catch (OperationCanceledException ex) when (timeoutSource?.IsCancellationRequested ?? false) { var messageSuffix = (pool?.IsEmpty ?? false) ? " All pooled connections are in use." : ""; throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, "Connect Timeout expired." + messageSuffix, ex); } catch (MySqlException ex) when ((timeoutSource?.IsCancellationRequested ?? false) || ((MySqlErrorCode)ex.Number == MySqlErrorCode.CommandTimeoutExpired)) { throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, "Connect Timeout expired.", ex); } finally { linkedSource?.Dispose(); timeoutSource?.Dispose(); } } internal bool SslIsEncrypted => m_session!.SslIsEncrypted; internal bool SslIsSigned => m_session!.SslIsSigned; internal bool SslIsAuthenticated => m_session!.SslIsAuthenticated; internal bool SslIsMutuallyAuthenticated => m_session!.SslIsMutuallyAuthenticated; internal SslProtocols SslProtocol => m_session!.SslProtocol; internal void SetState(ConnectionState newState) { if (m_connectionState != newState) { var previousState = m_connectionState; m_connectionState = newState; var eventArgs = previousState == ConnectionState.Closed && newState == ConnectionState.Connecting ? s_stateChangeClosedConnecting : previousState == ConnectionState.Connecting && newState == ConnectionState.Open ? s_stateChangeConnectingOpen : previousState == ConnectionState.Open && newState == ConnectionState.Closed ? s_stateChangeOpenClosed : new StateChangeEventArgs(previousState, newState); OnStateChange(eventArgs); } } private MySqlConnection(string connectionString, bool hasBeenOpened) : this(connectionString) { m_hasBeenOpened = hasBeenOpened; } private void VerifyNotDisposed() { if (m_isDisposed) throw new ObjectDisposedException(GetType().Name); } private Task CloseAsync(bool changeState, IOBehavior ioBehavior) { if (m_connectionState == ConnectionState.Closed) return Utility.CompletedTask; // check fast path if (m_activeReader is null && CurrentTransaction is null && #if !NETSTANDARD1_3 m_enlistedTransaction is null && #endif (m_connectionSettings?.Pooling ?? false)) { m_cachedProcedures = null; if (m_session is object) { m_session.ReturnToPool(); m_session = null; } if (changeState) SetState(ConnectionState.Closed); return Utility.CompletedTask; } return DoCloseAsync(changeState, ioBehavior); } private async Task DoCloseAsync(bool changeState, IOBehavior ioBehavior) { #if !NETSTANDARD1_3 // If participating in a distributed transaction, keep the connection open so we can commit or rollback. // This handles the common pattern of disposing a connection before disposing a TransactionScope (e.g., nested using blocks) if (m_enlistedTransaction is object) { // make sure all DB work is done if (m_activeReader is object) await m_activeReader.DisposeAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); m_activeReader = null; // This connection is being closed, so create a new MySqlConnection that will own the ServerSession // (which remains open). This ensures the ServerSession always has a valid OwningConnection (even // if 'this' is GCed. var connection = new MySqlConnection { m_connectionString = m_connectionString, m_connectionSettings = m_connectionSettings, m_connectionState = m_connectionState, m_hasBeenOpened = true, }; connection.TakeSessionFrom(this); // put the new, idle, connection into the list of sessions for this transaction (replacing this MySqlConnection) lock (s_lock) { foreach (var enlistedTransaction in s_transactionConnections[connection.m_enlistedTransaction!.Transaction]) { if (enlistedTransaction.Connection == this) { enlistedTransaction.Connection = connection; enlistedTransaction.IsIdle = true; break; } } } if (changeState) SetState(ConnectionState.Closed); return; } #endif if (m_connectionState != ConnectionState.Closed) { Exception? e = null; var operationId = _diagnosticListener.WriteConnectionCloseBefore(this); try { await CloseDatabaseAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { e = ex; throw; } finally { string? sessionId = null; if (m_session is object) { sessionId = m_session.Id; if (GetInitializedConnectionSettings().Pooling) { m_session.ReturnToPool(); } else { await m_session.DisposeAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false); m_session.OwningConnection = null; } m_session = null; } if (changeState) SetState(ConnectionState.Closed); if (e != null) { _diagnosticListener.WriteConnectionCloseError(operationId, sessionId!, this, e); } else { _diagnosticListener.WriteConnectionCloseAfter(operationId, sessionId!, this); } } } } private Task CloseDatabaseAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { m_cachedProcedures = null; if (m_activeReader is null && CurrentTransaction is null) return Utility.CompletedTask; return DoCloseDatabaseAsync(ioBehavior, cancellationToken); } private async Task DoCloseDatabaseAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { if (m_activeReader is object) await m_activeReader.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false); if (CurrentTransaction is object && m_session!.IsConnected) { await CurrentTransaction.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false); CurrentTransaction = null; } } private ConnectionSettings GetConnectionSettings() => m_connectionSettings ??= new ConnectionSettings(new MySqlConnectionStringBuilder(m_connectionString)); // This method may be called when it's known that the connection settings have been initialized. private ConnectionSettings GetInitializedConnectionSettings() => m_connectionSettings!; static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(MySqlConnection)); static readonly StateChangeEventArgs s_stateChangeClosedConnecting = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Connecting); static readonly StateChangeEventArgs s_stateChangeConnectingOpen = new StateChangeEventArgs(ConnectionState.Connecting, ConnectionState.Open); static readonly StateChangeEventArgs s_stateChangeOpenClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed); #if !NETSTANDARD1_3 static readonly object s_lock = new object(); static readonly Dictionary<System.Transactions.Transaction, List<EnlistedTransactionBase>> s_transactionConnections = new Dictionary<System.Transactions.Transaction, List<EnlistedTransactionBase>>(); #endif string m_connectionString; ConnectionSettings? m_connectionSettings; ServerSession? m_session; ConnectionState m_connectionState; bool m_hasBeenOpened; bool m_isDisposed; Dictionary<string, CachedProcedure?>? m_cachedProcedures; MySqlDataReader? m_activeReader; static readonly DiagnosticListener _diagnosticListener = new DiagnosticListener(MySqlClientDiagnosticListenerExtensions.DiagnosticListenerName); } }
40.591111
220
0.76136
[ "MIT" ]
HEF-Sharp/MySqlConnector
src/MySqlConnector/MySql.Data.MySqlClient/MySqlConnection.cs
36,532
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /* This script is the all type Duck.cs's main script */ public abstract class Duck { public FlyBehavior flyBehavior; public QuackBehavior quackBehavior; // init you cloud setup the unique Behavior when init public Duck() { } // could be override at otehr type duck public abstract void DoDisplay(); // Behavior A public void doFly() { flyBehavior.fly(); } // Behavior B public void DoQuack() { quackBehavior.quack(); } // Replace behavior A when need public void setFlyBehavior(FlyBehavior newFlyBehavior) { flyBehavior = newFlyBehavior; } // Replace behavior B when need public void setQuackBehavior(QuackBehavior newQuackBehavior) { quackBehavior = newQuackBehavior; } // Same Asction public void swin() { Debug.Log("All ducks float, even decoys!"); } }
21.638298
64
0.631268
[ "MIT" ]
qaz442200156/Design-Patterns
DesignPatterns/Assets/Scripte/DesignPatterns/StrategyPattern/Book/Base/Duck.cs
1,019
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatterm.Decorator { /// <summary> /// 抽象界面构件类:抽象构件类 /// </summary> public abstract class Component { public abstract void Display(); } }
17.823529
39
0.676568
[ "Apache-2.0" ]
hippieZhou/GofForCSharp
DesignPatterm.Decorator/Component.cs
331
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("vetores 2.0")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("vetores 2.0")] [assembly: System.Reflection.AssemblyTitleAttribute("vetores 2.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.916667
81
0.627237
[ "MIT" ]
Josyas/Vetores-2.0
vetores 2.0/obj/Debug/netcoreapp3.1/vetores 2.0.AssemblyInfo.cs
1,006
C#
using System; using System.Collections.Generic; namespace UITesting.Framework.Core { public class Context { private Context() { } private static Dictionary<String, Dictionary<String, Object>> contextVariables = new Dictionary<String, Dictionary<String, Object>>(); public static void Put(String name, Object value) { Dictionary<String, Object> dataMap = new Dictionary<String, Object>(); String threadName = Driver.GetThreadName(); if (contextVariables.ContainsKey(threadName)) { dataMap = contextVariables[threadName]; contextVariables.Remove(threadName); } if (dataMap.ContainsKey(name)) { dataMap.Remove(name); } dataMap.Add(name, value); contextVariables.Add(threadName, dataMap); } public static Object Get(String name) { String threadName = Driver.GetThreadName(); if (contextVariables.ContainsKey(threadName)) { return contextVariables[threadName][name]; } return null; } public static void ClearCurrent() { String threadName = Driver.GetThreadName(); if (contextVariables.ContainsKey(threadName)) { contextVariables.Remove(threadName); } contextVariables.Add(threadName, new Dictionary<String, Object>()); } public static Dictionary<String, Object>.KeyCollection Variables { get { String threadName = Driver.GetThreadName(); return contextVariables[threadName].Keys; } } } }
24.929825
80
0.710063
[ "MIT" ]
PacktPublishing/Automted-UI-Testing-in-C-
UITesting/Framework/Core/Context.cs
1,423
C#
using System; using System.Reflection; namespace JsonTable { public abstract class BaseTable { protected string FullPath => GetType().GetCustomAttribute<TableAttribute>()?.FullPath ?? throw new Exception("cannot find TableAttribute."); protected string Key => GetType().GetCustomAttribute<TableAttribute>()?.Key ?? throw new Exception("cannot find TableAttribute."); protected BaseTable() { Load(); } protected abstract void Load(); } }
25
96
0.612727
[ "MIT" ]
elky84/JsonTable
JsonTable/BaseTable.cs
552
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; namespace TubeTalk { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } }
20.222222
65
0.700549
[ "MIT" ]
KatVHarris/YourTube
TubeTalk/Global.asax.cs
366
C#
// ======================================== // Project Name : WodiLib // File Name : TilePathSettingPartialDeny.cs // // MIT License Copyright(c) 2019 kameske // see LICENSE file // ======================================== using System; using System.ComponentModel; using System.Runtime.Serialization; using WodiLib.Sys; namespace WodiLib.Map { /// <summary> /// タイル通行許可設定・部分的に拒否 /// </summary> [Serializable] internal class TilePathSettingPartialDeny : TilePathSettingBase, IEquatable<TilePathSettingPartialDeny> { // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Public Property // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <summary> /// タイル通行許可 /// </summary> public override TilePathPermission PathPermission => TilePathPermission.PartialDeny; /// <summary> /// タイル通行不可フラグ /// </summary> /// <exception cref="PropertyNullException">nullをセットした場合</exception> /// <exception cref="PropertyAccessException">タイル通行許可が"通行不可"以外の場合</exception> public override TileImpassableFlags ImpassableFlags { get; } = new TileImpassableFlags(); // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Constructor // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <summary> /// コンストラクタ /// </summary> public TilePathSettingPartialDeny() { } /// <summary> /// コンストラクタ /// </summary> /// <param name="impassableFlags">通行設定フラグ</param> /// <exception cref="ArgumentNullException">cannotPattingFlagsがnullの場合</exception> public TilePathSettingPartialDeny(TileImpassableFlags impassableFlags) { if (impassableFlags is null) throw new ArgumentNullException( ErrorMessage.NotNull(nameof(impassableFlags))); ImpassableFlags = impassableFlags; } /// <summary> /// コンストラクタ /// </summary> /// <param name="code">コード値</param> public TilePathSettingPartialDeny(int code) : base(code) { ImpassableFlags = new TileImpassableFlags(code); } // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Public Method // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <summary> /// 値を比較する。 /// </summary> /// <param name="other">比較対象</param> /// <returns>一致する場合、true</returns> public bool Equals(TilePathSettingPartialDeny? other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ImpassableFlags.Equals(other.ImpassableFlags); } // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Protected Override Method // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <inheritdoc/> protected override bool ChildEquals(ITilePathSetting other) { if (other is null) return false; if (!(other is TilePathSettingPartialDeny casted)) return false; return Equals(casted); } // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Common // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <summary> /// バイナリ変換する。 /// </summary> /// <returns>バイナリデータ</returns> public override byte[] ToBinary() { var result = 0; result += PathPermission.Code; result += ImpassableFlags.ToCode(); result += PathOption.Code; result += IsCounter ? CounterOnCode : 0; return result.ToWoditorIntBytes(); } // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Serializable // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <summary> /// コンストラクタ /// </summary> /// <param name="info">デシリアライズ情報</param> /// <param name="context">コンテキスト</param> [EditorBrowsable(EditorBrowsableState.Never)] protected TilePathSettingPartialDeny(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
34.848485
117
0.519348
[ "MIT" ]
kameske/WodiLib
WodiLib/WodiLib/Map/Model/Internal/TilePathSettingPartialDeny.cs
4,900
C#
using System; using System.Collections.Generic; using Registration.Application.EventSourcedNormalizers; using Registration.Application.Interfaces; using AutoMapper; using AutoMapper.QueryableExtensions; using Registration.Domain.Repositories.Interfaces; using Registration.Domain.ReadModel; using CqrsFramework.Domain; using System.Linq; using Registration.Domain.ReadModel.Security; using Microsoft.EntityFrameworkCore; namespace Registration.Application.Services { public class LocationService : ILocationService { //private readonly ISession _session; private readonly ILocationRepository _locationRepository; private readonly IMapper _mapper; public LocationService( //ISession session, IMapper mapper, ILocationRepository locationRepository ) { //_session = session; _mapper = mapper; _locationRepository = locationRepository; } public void Dispose() { GC.SuppressFinalize(this); } public Location FindLocation(Guid locationId) { var location = _locationRepository.Find(locationId); return location; } public IEnumerable<Location> FindLocations() { var locations = _locationRepository.Find(_ => true).Include(_=>_.AdditionalLocationImages); return locations; } } }
27.87037
103
0.648505
[ "MIT" ]
Liang-Zhinian/CqrsFrameworkDotNet
Sample/Reservation/v1/Registration/Registration.Application/Services/LocationService.cs
1,507
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; using Reign; public class InputExDemo : MonoBehaviour { public Button BackButton; public Text InputText; void Update() { // bind button events BackButton.onClick.AddListener(backClicked); // ==================================== // You can log input here for debuging... // ==================================== // All button and key input //string keyLabel = InputEx.LogKeys(); //if (keyLabel != null) //{ // InputText.text = keyLabel; // return; //} // All GamePad input string buttonLabel = InputEx.LogButtons(); string analogLabel = InputEx.LogAnalogs(); if (buttonLabel != null) InputText.text = buttonLabel; else if (analogLabel != null) InputText.text = analogLabel; // Example Input use case examples //if (InputEx.GetButton(ButtonTypes.Start, ControllerPlayers.Any));// do soething... //if (InputEx.GetButtonDown(ButtonTypes.Start, ControllerPlayers.Any));// do soething... //if (InputEx.GetButtonUp(ButtonTypes.Start, ControllerPlayers.Any));// do soething... //if (InputEx.GetAxis(AnalogTypes.AxisLeftX, ControllerPlayers.Any) >= .1f);// do soething... } private void backClicked() { Application.LoadLevel("MainDemo"); } }
26.851064
95
0.663233
[ "MIT" ]
U3DC/Snaker
Assets/Plugins/Reign/DemoScenes/Scripts/InputExDemo.cs
1,264
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20220310 { using Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="MachineUpdateProperties" /> /// </summary> public partial class MachineUpdatePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType" /// /> parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType" /// /> parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <see cref="MachineUpdateProperties"/> /// type. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="MachineUpdateProperties" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="MachineUpdateProperties" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <paramref name="sourceValue" /> parameter can be converted to the <paramref name="destinationType" /> /// parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType" /// /> parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType" /> parameter using <paramref /// name="formatProvider" /> and <paramref name="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="MachineUpdateProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <paramref name="sourceValue" /> parameter into an instance of <see cref="MachineUpdateProperties" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="MachineUpdateProperties" />.</param> /// <returns> /// an instance of <see cref="MachineUpdateProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20220310.IMachineUpdateProperties ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20220310.IMachineUpdateProperties).IsAssignableFrom(type)) { return sourceValue; } try { return MachineUpdateProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return MachineUpdateProperties.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return MachineUpdateProperties.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.727891
263
0.599923
[ "MIT" ]
imadan1996/azure-powershell
src/ConnectedMachine/generated/api/Models/Api20220310/MachineUpdateProperties.TypeConverter.cs
7,605
C#
using System; using System.Collections.Generic; namespace API_QLHSBanTru.ViewModel { public class EmployeeVm { public int EmployeeID { get; set; } public string Username { get; set; } public string Password { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Nullable<System.DateTime> Birthday { get; set; } public Nullable<bool> Gender { get; set; } public int EthnicGroupID { get; set; } public int ReligionID { get; set; } public byte[] Image { get; set; } public int LocationID { get; set; } public string AddressDetail { get; set; } public Nullable<int> DegreeID { get; set; } public string Email { get; set; } public string Phone { get; set; } public string IdentityNumber { get; set; } public System.DateTime DateOfIssue { get; set; } public string PlaceOfIssue { get; set; } public string Note { get; set; } public bool Status { get; set; } public virtual ICollection<ContractVm> Contracts { get; set; } public virtual DegreeVm Degree { get; set; } public virtual ICollection<Employee_ClassVm> Employee_Class { get; set; } public virtual EthnicGroupVm EthnicGroup { get; set; } public virtual ICollection<Employee_FunctionVm> Employee_Function { get; set; } public virtual LocationVm Location { get; set; } public virtual ReligionVm Religion { get; set; } public virtual ICollection<HealthProblemVm> HealthProblems { get; set; } public virtual ICollection<HistoryVm> Histories { get; set; } } }
43.410256
87
0.636149
[ "MIT" ]
TuanDC3/API-QLHSBanTru
API-QLHSBanTru/API-QLHSBanTru/ViewModel/EmployeeVm.cs
1,695
C#
using System; using System.Collections.Generic; using System.Linq; namespace Orleans.Streaming.CosmosDB { /// <summary> /// Configure CosmosDB stream provider /// </summary> public class CosmosDBStreamConfigurator { internal Dictionary<string, (CosmosDBStreamOptions Options, Type MapperType)> Settings; internal CosmosDBStreamConfigurator() { this.Settings = new Dictionary<string, (CosmosDBStreamOptions Options, Type MapperType)>(); } /// <summary> /// Register CosmosDB Change Feed to the stream provider /// </summary> /// <param name="name">Provider Name</param> /// <param name="configure">Options configuration delegate</param> /// <param name="mapperType">(optional) A custom IStreamMapper implementation type.</param> public CosmosDBStreamConfigurator AddStream(string name, Action<CosmosDBStreamOptions> configure, Type mapperType = null) { if (configure == null) throw new ArgumentNullException(nameof(configure)); if (mapperType == null) { mapperType = typeof(IdBasedStreamMapper); } else if (!mapperType.GetInterfaces().Contains(typeof(IStreamMapper))) { throw new InvalidOperationException("Mapper must implement 'IStreamMapper' interface'"); } var options = new CosmosDBStreamOptions(); configure.Invoke(options); this.Settings[name] = (options, mapperType); return this; } } }
36.6
130
0.6102
[ "MIT" ]
KevinCathcart/Orleans.CosmosDB
src/Orleans.Streaming.CosmosDB/Options/CosmosDBStreamConfigurator.cs
1,647
C#
using Mimp.SeeSharper.DependencyInjection.Abstraction; using System; using System.Collections.Generic; namespace Mimp.SeeSharper.DependencyInjection.Tag.Abstraction { public class TagDependencyContext : DependencyContext, ITagDependencyContext { public object Tag { get; } public TagDependencyContext(object tag, IDependencyProvider provider, Type dependencyType) : base(provider, dependencyType) { Tag = tag ?? throw new ArgumentNullException(nameof(tag)); } public override bool Equals(object? obj) { return obj is TagDependencyContext context && base.Equals(obj) && EqualityComparer<Type>.Default.Equals(DependencyType, context.DependencyType) && EqualityComparer<IDependencyProvider>.Default.Equals(Provider, context.Provider) && EqualityComparer<object>.Default.Equals(Tag, context.Tag); } public override int GetHashCode() { int hashCode = -863085855; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<Type>.Default.GetHashCode(DependencyType); hashCode = hashCode * -1521134295 + EqualityComparer<IDependencyProvider>.Default.GetHashCode(Provider); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Tag); return hashCode; } public override string? ToString() { return $"{GetType().Name} {{ {nameof(DependencyType)} = {DependencyType}, {nameof(Tag)} = {Tag} }}"; } } }
33.82
116
0.639267
[ "MIT" ]
DavenaHack/SeeSharper.DependencyInjection
src/Mimp.SeeSharper.DependencyInjection.Tag.Abstraction/TagDependencyContext.cs
1,693
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RealParserTests { /// <summary> /// Test some specific floating-point literals that have been shown to be problematic /// in some implementation. /// </summary> [Fact] public static void TestTroublesomeDoubles() { //// https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx CheckOneDouble("0.6822871999174", 0x3FE5D54BF743FD1Bul); //// Common problem numbers CheckOneDouble("2.2250738585072011e-308", 0x000FFFFFFFFFFFFFul); CheckOneDouble("2.2250738585072012e-308", 0x0010000000000000ul); //// http://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/ CheckOneDouble("1.3694713649464322631e-11", 0x3DAE1D703BB5749Dul); CheckOneDouble("9.3170532238714134438e+16", 0x4374B021AFD9F651ul); //// https://connect.microsoft.com/VisualStudio/feedback/details/914964/double-round-trip-conversion-via-a-string-is-not-safe CheckOneDouble("0.84551240822557006", 0x3FEB0E7009B61CE0ul); // This value has a non-terminating binary fraction. It has a 0 at bit 54 // followed by 120 ones. //// http://www.exploringbinary.com/a-bug-in-the-bigcomp-function-of-david-gays-strtod/ CheckOneDouble("1.8254370818746402660437411213933955878019332885742187", 0x3FFD34FD8378EA83ul); //// http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision CheckOneDouble("7.8459735791271921e+65", 0x4D9DCD0089C1314Eul); CheckOneDouble("3.08984926168550152811e-32", 0x39640DE48676653Bul); //// other values from https://github.com/dotnet/roslyn/issues/4221 CheckOneDouble("0.6822871999174000000", 0x3FE5D54BF743FD1Bul); CheckOneDouble("0.6822871999174000001", 0x3FE5D54BF743FD1Bul); // A handful of selected values for which double.Parse has been observed to produce an incorrect result CheckOneDouble("88.7448699245e+188", 0x675fde6aee647ed2ul); CheckOneDouble("02.0500496671303857e-88", 0x2dba19a3cf32cd7ful); CheckOneDouble("1.15362842193e193", 0x68043a6fcda86331ul); CheckOneDouble("65.9925719e-190", 0x18dd672e04e96a79ul); CheckOneDouble("0.4619024460e-158", 0x1f103c1e5abd7c87ul); CheckOneDouble("61.8391820096448e147", 0x5ed35849885ad12bul); CheckOneDouble("0.2e+127", 0x5a27a2ecc414a03ful); CheckOneDouble("0.8e+127", 0x5a47a2ecc414a03ful); CheckOneDouble("35.27614496323756e-307", 0x0083d141335ce6c7ul); CheckOneDouble("3.400034617466e190", 0x677e863a216ab367ul); CheckOneDouble("0.78393577148319e-254", 0x0b2d6d5379bc932dul); CheckOneDouble("0.947231e+100", 0x54b152a10483a38ful); CheckOneDouble("4.e126", 0x5a37a2ecc414a03ful); CheckOneDouble("6.235271922748e-165", 0x1dd6faeba4fc9f91ul); CheckOneDouble("3.497444198362024e-82", 0x2f053b8036dd4203ul); CheckOneDouble("8.e+126", 0x5a47a2ecc414a03ful); CheckOneDouble("10.027247729e+91", 0x53089cc2d930ed3ful); CheckOneDouble("4.6544819e-192", 0x18353c5d35ceaaadul); CheckOneDouble("5.e+125", 0x5a07a2ecc414a03ful); CheckOneDouble("6.96768e68", 0x4e39d8352ee997f9ul); CheckOneDouble("0.73433e-145", 0x21cd57b723dc17bful); CheckOneDouble("31.076044256878e259", 0x76043627aa7248dful); CheckOneDouble("0.8089124675e-201", 0x162fb3bf98f037f7ul); CheckOneDouble("88.7453407049700914e-144", 0x227150a674c218e3ul); CheckOneDouble("32.401089401e-65", 0x32c10fa88084d643ul); CheckOneDouble("0.734277884753e-209", 0x14834fdfb6248755ul); CheckOneDouble("8.3435e+153", 0x5fe3e9c5b617dc39ul); CheckOneDouble("30.379e-129", 0x25750ec799af9efful); CheckOneDouble("78.638509299e141", 0x5d99cb8c0a72cd05ul); CheckOneDouble("30.096884930e-42", 0x3784f976b4d47d63ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 1 (less than half ULP - round down) CheckOneDouble("69e+267", 0x77C0B7CB60C994DAul); CheckOneDouble("999e-026", 0x3B282782AFE1869Eul); CheckOneDouble("7861e-034", 0x39AFE3544145E9D8ul); CheckOneDouble("75569e-254", 0x0C35A462D91C6AB3ul); CheckOneDouble("928609e-261", 0x0AFBE2DD66200BEFul); CheckOneDouble("9210917e+080", 0x51FDA232347E6032ul); CheckOneDouble("84863171e+114", 0x59406E98F5EC8F37ul); CheckOneDouble("653777767e+273", 0x7A720223F2B3A881ul); CheckOneDouble("5232604057e-298", 0x041465B896C24520ul); CheckOneDouble("27235667517e-109", 0x2B77D41824D64FB2ul); CheckOneDouble("653532977297e-123", 0x28D925A0AABCDC68ul); CheckOneDouble("3142213164987e-294", 0x057D3409DFBCA26Ful); CheckOneDouble("46202199371337e-072", 0x33D28F9EDFBD341Ful); CheckOneDouble("231010996856685e-073", 0x33C28F9EDFBD341Ful); CheckOneDouble("9324754620109615e+212", 0x6F43AE60753AF6CAul); CheckOneDouble("78459735791271921e+049", 0x4D9DCD0089C1314Eul); CheckOneDouble("272104041512242479e+200", 0x6D13BBB4BF05F087ul); CheckOneDouble("6802601037806061975e+198", 0x6CF3BBB4BF05F087ul); CheckOneDouble("20505426358836677347e-221", 0x161012954B6AABBAul); CheckOneDouble("836168422905420598437e-234", 0x13B20403A628A9CAul); CheckOneDouble("4891559871276714924261e+222", 0x7286ECAF7694A3C7ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 2 (greater than half ULP - round up) CheckOneDouble("85e-037", 0x38A698CCDC60015Aul); CheckOneDouble("623e+100", 0x554640A62F3A83DFul); CheckOneDouble("3571e+263", 0x77462644C61D41AAul); CheckOneDouble("81661e+153", 0x60B7CA8E3D68578Eul); CheckOneDouble("920657e-023", 0x3C653A9985DBDE6Cul); CheckOneDouble("4603285e-024", 0x3C553A9985DBDE6Cul); CheckOneDouble("87575437e-309", 0x016E07320602056Cul); CheckOneDouble("245540327e+122", 0x5B01B6231E18C5CBul); CheckOneDouble("6138508175e+120", 0x5AE1B6231E18C5CBul); CheckOneDouble("83356057653e+193", 0x6A4544E6DAEE2A18ul); CheckOneDouble("619534293513e+124", 0x5C210C20303FE0F1ul); CheckOneDouble("2335141086879e+218", 0x6FC340A1C932C1EEul); CheckOneDouble("36167929443327e-159", 0x21BCE77C2B3328FCul); CheckOneDouble("609610927149051e-255", 0x0E104273B18918B1ul); CheckOneDouble("3743626360493413e-165", 0x20E8823A57ADBEF9ul); CheckOneDouble("94080055902682397e-242", 0x11364981E39E66CAul); CheckOneDouble("899810892172646163e+283", 0x7E6ADF51FA055E03ul); CheckOneDouble("7120190517612959703e+120", 0x5CC3220DCD5899FDul); CheckOneDouble("25188282901709339043e-252", 0x0FA4059AF3DB2A84ul); CheckOneDouble("308984926168550152811e-052", 0x39640DE48676653Bul); CheckOneDouble("6372891218502368041059e+064", 0x51C067047DBB38FEul); // http://www.exploringbinary.com/incorrect-decimal-to-floating-point-conversion-in-sqlite/ CheckOneDouble("1e-23", 0x3B282DB34012B251ul); CheckOneDouble("8.533e+68", 0x4E3FA69165A8EEA2ul); CheckOneDouble("4.1006e-184", 0x19DBE0D1C7EA60C9ul); CheckOneDouble("9.998e+307", 0x7FE1CC0A350CA87Bul); CheckOneDouble("9.9538452227e-280", 0x0602117AE45CDE43ul); CheckOneDouble("6.47660115e-260", 0x0A1FDD9E333BADADul); CheckOneDouble("7.4e+47", 0x49E033D7ECA0ADEFul); CheckOneDouble("5.92e+48", 0x4A1033D7ECA0ADEFul); CheckOneDouble("7.35e+66", 0x4DD172B70EABABA9ul); CheckOneDouble("8.32116e+55", 0x4B8B2628393E02CDul); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Fact] public static void TestSpecificDoubles() { CheckOneDouble("0.0", 0x0000000000000000ul); // Verify the smallest denormals: for (ulong i = 0x0000000000000001ul; i != 0x0000000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest denormals and the smallest normals: for (ulong i = 0x000fffffffffff00ul; i != 0x0010000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest normals: for (ulong i = 0x7fefffffffffff00ul; i != 0x7ff0000000000000ul; ++i) { TestRoundTripDouble(i); } // Verify all representable powers of two and nearby values: for (int pow = -1022; pow <= 1023; pow++) { ulong twoToThePow = ((ulong)(pow + 1023)) << 52; TestRoundTripDouble(twoToThePow); TestRoundTripDouble(twoToThePow + 1); TestRoundTripDouble(twoToThePow - 1); } // Verify all representable powers of ten and nearby values: for (int pow = -323; pow <= 308; pow++) { var s = $"1.0e{pow}"; double value; RealParser.TryParseDouble(s, out value); var tenToThePow = (ulong)BitConverter.DoubleToInt64Bits(value); CheckOneDouble(s, value); TestRoundTripDouble(tenToThePow + 1); TestRoundTripDouble(tenToThePow - 1); } // Verify a few large integer values: TestRoundTripDouble((double)long.MaxValue); TestRoundTripDouble((double)ulong.MaxValue); // Verify small and large exactly representable integers: CheckOneDouble("1", 0x3ff0000000000000); CheckOneDouble("2", 0x4000000000000000); CheckOneDouble("3", 0x4008000000000000); CheckOneDouble("4", 0x4010000000000000); CheckOneDouble("5", 0x4014000000000000); CheckOneDouble("6", 0x4018000000000000); CheckOneDouble("7", 0x401C000000000000); CheckOneDouble("8", 0x4020000000000000); CheckOneDouble("9007199254740984", 0x433ffffffffffff8); CheckOneDouble("9007199254740985", 0x433ffffffffffff9); CheckOneDouble("9007199254740986", 0x433ffffffffffffa); CheckOneDouble("9007199254740987", 0x433ffffffffffffb); CheckOneDouble("9007199254740988", 0x433ffffffffffffc); CheckOneDouble("9007199254740989", 0x433ffffffffffffd); CheckOneDouble("9007199254740990", 0x433ffffffffffffe); CheckOneDouble("9007199254740991", 0x433fffffffffffff); // 2^53 - 1 // Verify the smallest and largest denormal values: CheckOneDouble("5.0e-324", 0x0000000000000001); CheckOneDouble("1.0e-323", 0x0000000000000002); CheckOneDouble("1.5e-323", 0x0000000000000003); CheckOneDouble("2.0e-323", 0x0000000000000004); CheckOneDouble("2.5e-323", 0x0000000000000005); CheckOneDouble("3.0e-323", 0x0000000000000006); CheckOneDouble("3.5e-323", 0x0000000000000007); CheckOneDouble("4.0e-323", 0x0000000000000008); CheckOneDouble("4.5e-323", 0x0000000000000009); CheckOneDouble("5.0e-323", 0x000000000000000a); CheckOneDouble("5.5e-323", 0x000000000000000b); CheckOneDouble("6.0e-323", 0x000000000000000c); CheckOneDouble("6.5e-323", 0x000000000000000d); CheckOneDouble("7.0e-323", 0x000000000000000e); CheckOneDouble("7.5e-323", 0x000000000000000f); CheckOneDouble("2.2250738585071935e-308", 0x000ffffffffffff0); CheckOneDouble("2.2250738585071940e-308", 0x000ffffffffffff1); CheckOneDouble("2.2250738585071945e-308", 0x000ffffffffffff2); CheckOneDouble("2.2250738585071950e-308", 0x000ffffffffffff3); CheckOneDouble("2.2250738585071955e-308", 0x000ffffffffffff4); CheckOneDouble("2.2250738585071960e-308", 0x000ffffffffffff5); CheckOneDouble("2.2250738585071964e-308", 0x000ffffffffffff6); CheckOneDouble("2.2250738585071970e-308", 0x000ffffffffffff7); CheckOneDouble("2.2250738585071974e-308", 0x000ffffffffffff8); CheckOneDouble("2.2250738585071980e-308", 0x000ffffffffffff9); CheckOneDouble("2.2250738585071984e-308", 0x000ffffffffffffa); CheckOneDouble("2.2250738585071990e-308", 0x000ffffffffffffb); CheckOneDouble("2.2250738585071994e-308", 0x000ffffffffffffc); CheckOneDouble("2.2250738585072000e-308", 0x000ffffffffffffd); CheckOneDouble("2.2250738585072004e-308", 0x000ffffffffffffe); CheckOneDouble("2.2250738585072010e-308", 0x000fffffffffffff); // Test cases from Rick Regan's article, "Incorrectly Rounded Conversions in Visual C++": // // http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ // // Example 1: CheckOneDouble( "9214843084008499", 0x43405e6cec57761a); // Example 2: CheckOneDouble( "0.500000000000000166533453693773481063544750213623046875", 0x3fe0000000000002); // Example 3 (2^-1 + 2^-53 + 2^-54): CheckOneDouble( "30078505129381147446200", 0x44997a3c7271b021); // Example 4: CheckOneDouble( "1777820000000000000001", 0x4458180d5bad2e3e); // Example 5 (2^-1 + 2^-53 + 2^-54 + 2^-66): CheckOneDouble( "0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002); // Example 6 (2^-1 + 2^-53 + 2^-54 + 2^-65): CheckOneDouble( "0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fe0000000000002); // Example 7: CheckOneDouble( "0.3932922657273", 0x3fd92bb352c4623a ); // The following test cases are taken from other articles on Rick Regan's // Exploring Binary blog. These are conversions that other implementations // were found to perform incorrectly. // http://www.exploringbinary.com/nondeterministic-floating-point-conversions-in-java/ // http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ // Example 1 (2^-1047 + 2^-1075, half-ulp above a power of two): CheckOneDouble( "6.6312368714697582767853966302759672433990999473553031442499717587" + "362866301392654396180682007880487441059604205526018528897150063763" + "256665955396033303618005191075917832333584923372080578494993608994" + "251286407188566165030934449228547591599881603044399098682919739314" + "266256986631577498362522745234853124423586512070512924530832781161" + "439325697279187097860044978723221938561502254152119972830784963194" + "121246401117772161481107528151017752957198119743384519360959074196" + "224175384736794951486324803914359317679811223967034438033355297560" + "033532098300718322306892013830155987921841729099279241763393155074" + "022348361207309147831684007154624400538175927027662135590421159867" + "638194826541287705957668068727833491469671712939495988506756821156" + "96218943412532098591327667236328125E-316", 0x0000000008000000); // Example 2 (2^-1058 - 2^-1075, half-ulp below a power of two): CheckOneDouble( "3.2378839133029012895883524125015321748630376694231080599012970495" + "523019706706765657868357425877995578606157765598382834355143910841" + "531692526891905643964595773946180389283653051434639551003566966656" + "292020173313440317300443693602052583458034314716600326995807313009" + "548483639755486900107515300188817581841745696521731104736960227499" + "346384253806233697747365600089974040609674980283891918789639685754" + "392222064169814626901133425240027243859416510512935526014211553334" + "302252372915238433223313261384314778235911424088000307751706259156" + "707286570031519536642607698224949379518458015308952384398197084033" + "899378732414634842056080000272705311068273879077914449185347715987" + "501628125488627684932015189916680282517302999531439241685457086639" + "13273994694463908672332763671875E-319", 0x0000000000010000); // Example 3 (2^-1027 + 2^-1066 + 2^-1075, half-ulp above a non-power of two): CheckOneDouble( "6.9533558078476771059728052155218916902221198171459507544162056079" + "800301315496366888061157263994418800653863998640286912755395394146" + "528315847956685600829998895513577849614468960421131982842131079351" + "102171626549398024160346762138294097205837595404767869364138165416" + "212878432484332023692099166122496760055730227032447997146221165421" + "888377703760223711720795591258533828013962195524188394697705149041" + "926576270603193728475623010741404426602378441141744972109554498963" + "891803958271916028866544881824524095839813894427833770015054620157" + "450178487545746683421617594966617660200287528887833870748507731929" + "971029979366198762266880963149896457660004790090837317365857503352" + "620998601508967187744019647968271662832256419920407478943826987518" + "09812609536720628966577351093292236328125E-310", 0x0000800000000100 ); // Example 4 (2^-1058 + 2^-1063 + 2^-1075, half-ulp below a non-power of two): CheckOneDouble( "3.3390685575711885818357137012809439119234019169985217716556569973" + "284403145596153181688491490746626090999981130094655664268081703784" + "340657229916596426194677060348844249897410807907667784563321682004" + "646515939958173717821250106683466529959122339932545844611258684816" + "333436749050742710644097630907080178565840197768788124253120088123" + "262603630354748115322368533599053346255754042160606228586332807443" + "018924703005556787346899784768703698535494132771566221702458461669" + "916553215355296238706468887866375289955928004361779017462862722733" + "744717014529914330472578638646014242520247915673681950560773208853" + "293843223323915646452641434007986196650406080775491621739636492640" + "497383622906068758834568265867109610417379088720358034812416003767" + "05491726170293986797332763671875E-319", 0x0000000000010800 ); // http://www.exploringbinary.com/gays-strtod-returns-zero-for-inputs-just-above-2-1075/ // A number between 2^-2074 and 2^-1075, just slightly larger than 2^-1075. // It has bit 1075 set (the denormal rounding bit), followed by 2506 zeroes, // followed by one bits. It should round up to 2^-1074. CheckOneDouble( "2.470328229206232720882843964341106861825299013071623822127928412503" + "37753635104375932649918180817996189898282347722858865463328355177969" + "89819938739800539093906315035659515570226392290858392449105184435931" + "80284993653615250031937045767824921936562366986365848075700158576926" + "99037063119282795585513329278343384093519780155312465972635795746227" + "66465272827220056374006485499977096599470454020828166226237857393450" + "73633900796776193057750674017632467360096895134053553745851666113422" + "37666786041621596804619144672918403005300575308490487653917113865916" + "46239524912623653881879636239373280423891018672348497668235089863388" + "58792562830275599565752445550725518931369083625477918694866799496832" + "40497058210285131854513962138377228261454376934125320985913276672363" + "28125001e-324", 0x0000000000000001); CheckOneDouble("1.0e-99999999999999999999", 0.0); CheckOneDouble("0e-99999999999999999999", 0.0); CheckOneDouble("0e99999999999999999999", 0.0); } private static void TestRoundTripDouble(ulong bits) { double d = BitConverter.Int64BitsToDouble((long)bits); if (double.IsInfinity(d) || double.IsNaN(d)) return; string s = InvariantToString(d); CheckOneDouble(s, bits); } private static string InvariantToString(object o) { return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:G17}", o); } private static void TestRoundTripDouble(double d) { string s = InvariantToString(d); CheckOneDouble(s, d); } private static void CheckOneDouble(string s, ulong expectedBits) { CheckOneDouble(s, BitConverter.Int64BitsToDouble((long)expectedBits)); } private static void CheckOneDouble(string s, double expected) { double actual; if (!RealParser.TryParseDouble(s, out actual)) actual = 1.0 / 0.0; if (!actual.Equals(expected)) { throw new Exception($@" Error for double input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } // ============ test some floats ============ [Fact] public static void TestSpecificFloats() { CheckOneFloat(" 0.0", 0x00000000); // Verify the smallest denormals: for (uint i = 0x00000001; i != 0x00000100; ++i) { TestRoundTripFloat(i); } // Verify the largest denormals and the smallest normals: for (uint i = 0x007fff00; i != 0x00800100; ++i) { TestRoundTripFloat(i); } // Verify the largest normals: for (uint i = 0x7f7fff00; i != 0x7f800000; ++i) { TestRoundTripFloat(i); } // Verify all representable powers of two and nearby values: for (int i = -1022; i != 1023; ++i) { float f; try { f = (float)Math.Pow(2.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } // Verify all representable powers of ten and nearby values: for (int i = -50; i <= 40; ++i) { float f; try { f = (float)Math.Pow(10.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } TestRoundTripFloat((float)int.MaxValue); TestRoundTripFloat((float)uint.MaxValue); // Verify small and large exactly representable integers: CheckOneFloat("1", 0x3f800000); CheckOneFloat("2", 0x40000000); CheckOneFloat("3", 0x40400000); CheckOneFloat("4", 0x40800000); CheckOneFloat("5", 0x40A00000); CheckOneFloat("6", 0x40C00000); CheckOneFloat("7", 0x40E00000); CheckOneFloat("8", 0x41000000); CheckOneFloat("16777208", 0x4b7ffff8); CheckOneFloat("16777209", 0x4b7ffff9); CheckOneFloat("16777210", 0x4b7ffffa); CheckOneFloat("16777211", 0x4b7ffffb); CheckOneFloat("16777212", 0x4b7ffffc); CheckOneFloat("16777213", 0x4b7ffffd); CheckOneFloat("16777214", 0x4b7ffffe); CheckOneFloat("16777215", 0x4b7fffff); // 2^24 - 1 // Verify the smallest and largest denormal values: CheckOneFloat("1.4012984643248170e-45", 0x00000001); CheckOneFloat("2.8025969286496340e-45", 0x00000002); CheckOneFloat("4.2038953929744510e-45", 0x00000003); CheckOneFloat("5.6051938572992680e-45", 0x00000004); CheckOneFloat("7.0064923216240850e-45", 0x00000005); CheckOneFloat("8.4077907859489020e-45", 0x00000006); CheckOneFloat("9.8090892502737200e-45", 0x00000007); CheckOneFloat("1.1210387714598537e-44", 0x00000008); CheckOneFloat("1.2611686178923354e-44", 0x00000009); CheckOneFloat("1.4012984643248170e-44", 0x0000000a); CheckOneFloat("1.5414283107572988e-44", 0x0000000b); CheckOneFloat("1.6815581571897805e-44", 0x0000000c); CheckOneFloat("1.8216880036222622e-44", 0x0000000d); CheckOneFloat("1.9618178500547440e-44", 0x0000000e); CheckOneFloat("2.1019476964872256e-44", 0x0000000f); CheckOneFloat("1.1754921087447446e-38", 0x007ffff0); CheckOneFloat("1.1754922488745910e-38", 0x007ffff1); CheckOneFloat("1.1754923890044375e-38", 0x007ffff2); CheckOneFloat("1.1754925291342839e-38", 0x007ffff3); CheckOneFloat("1.1754926692641303e-38", 0x007ffff4); CheckOneFloat("1.1754928093939768e-38", 0x007ffff5); CheckOneFloat("1.1754929495238232e-38", 0x007ffff6); CheckOneFloat("1.1754930896536696e-38", 0x007ffff7); CheckOneFloat("1.1754932297835160e-38", 0x007ffff8); CheckOneFloat("1.1754933699133625e-38", 0x007ffff9); CheckOneFloat("1.1754935100432089e-38", 0x007ffffa); CheckOneFloat("1.1754936501730553e-38", 0x007ffffb); CheckOneFloat("1.1754937903029018e-38", 0x007ffffc); CheckOneFloat("1.1754939304327482e-38", 0x007ffffd); CheckOneFloat("1.1754940705625946e-38", 0x007ffffe); CheckOneFloat("1.1754942106924411e-38", 0x007fffff); // This number is exactly representable and should not be rounded in any // mode: // 0.1111111111111111111111100 // ^ CheckOneFloat("0.99999988079071044921875", 0x3f7ffffe); // This number is below the halfway point between two representable values // so it should round down in nearest mode: // 0.11111111111111111111111001 // ^ CheckOneFloat("0.99999989569187164306640625", 0x3f7ffffe); // This number is exactly halfway between two representable values, so it // should round to even in nearest mode: // 0.1111111111111111111111101 // ^ CheckOneFloat("0.9999999105930328369140625", 0x3f7ffffe); // This number is above the halfway point between two representable values // so it should round up in nearest mode: // 0.11111111111111111111111011 // ^ CheckOneFloat("0.99999992549419403076171875", 0x3f7fffff); } private static void TestRoundTripFloat(uint bits) { float d = Int32BitsToFloat(bits); if (float.IsInfinity(d) || float.IsNaN(d)) return; string s = InvariantToString(d); CheckOneFloat(s, bits); } private static void TestRoundTripFloat(float d) { string s = InvariantToString(d); if (s != "NaN" && s != "Infinity") CheckOneFloat(s, d); } private static void CheckOneFloat(string s, uint expectedBits) { CheckOneFloat(s, Int32BitsToFloat(expectedBits)); } private static void CheckOneFloat(string s, float expected) { float actual; if (!RealParser.TryParseFloat(s, out actual)) actual = 1.0f / 0.0f; if (!actual.Equals(expected)) { throw new Exception($@"Error for float input ""{s}"" expected {InvariantToString(expected)} actual {InvariantToString(actual)}"); } } private static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } private static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } [StructLayout(LayoutKind.Explicit)] private struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
50.146819
137
0.632596
[ "MIT" ]
06needhamt/roslyn
src/Compilers/Core/CodeAnalysisTest/RealParserTests.cs
30,742
C#
using MessagingClientMVVM.MicroMVVM; using MessagingClientMVVM.Models; using MessagingServer; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MessagingClientMVVM.ViewModels { public class MessageCollectionViewModel : ObservableObject { #region Members ConcurrentDictionary<int, MTObservableCollection<Message>> _messageCollections = new ConcurrentDictionary<int, MTObservableCollection<Message>>(); int? _selectedUserID; #endregion #region Properties public int? SelectedUserID { get { return _selectedUserID; } set { _selectedUserID = value; RaisePropertyChanged("SelectedUserID"); RaisePropertyChanged("Collection"); } } public MTObservableCollection<Message> Collection { get { if (_selectedUserID == null) return new MTObservableCollection<Message>(); MTObservableCollection<Message> messageCollectionTemp; if (!_messageCollections.TryGetValue((int)_selectedUserID, out messageCollectionTemp)) { if (!_messageCollections.TryAdd((int)_selectedUserID, new MTObservableCollection<Message>())) throw new Exception("Failed Adding New Queue"); if (!_messageCollections.TryGetValue((int)_selectedUserID, out messageCollectionTemp)) throw new Exception("FAILED ADDING NEW MESSAGE-COLLECTION"); RaisePropertyChanged("Collection"); } return messageCollectionTemp; } } #endregion #region Methods public MTObservableCollection<Message> GetCollection(int clientID) { MTObservableCollection<Message> messageCollectionTemp; if (!_messageCollections.TryGetValue(clientID, out messageCollectionTemp)) { if (!_messageCollections.TryAdd(clientID, new MTObservableCollection<Message>())) throw new Exception("Failed Adding New Queue"); if (!_messageCollections.TryGetValue(clientID, out messageCollectionTemp)) throw new Exception("FAILED ADDING NEW MESSAGE-COLLECTION"); } return messageCollectionTemp; } public void Add(Message message, int CurrentLoginID) { if (CurrentLoginID != message.senderID) { GetCollection(message.senderID).Add(message); if (message.senderID == _selectedUserID) RaisePropertyChanged("Collection"); } else { GetCollection(message.receiverID).Add(message); if (message.receiverID == _selectedUserID) RaisePropertyChanged("Collection"); } } public void RemoveByTimeStamp(Message message) { Message foundMessage = GetCollection(message.senderID).Where(Message => Message.createdTimeStamp.ToString() == message.MessageString).First(); GetCollection(message.senderID).Remove(foundMessage); if (message.senderID == _selectedUserID) RaisePropertyChanged("Collection"); } #endregion } }
36.77551
154
0.602109
[ "Apache-2.0" ]
topham101/MultiUserMessagingApplication
MessagingClientMVVM/ViewModels/MessageCollectionViewModel.cs
3,606
C#
using System; class Program { string x0; public Program() { x0 = ""; var x1 = ""; for (var i = 0; i < 1000; i++) { x0 += "" + i; // BAD x1 = x1 + i; // BAD var x2 = ""; x2 += x1; // GOOD } } }
14.95
38
0.307692
[ "MIT" ]
00mjk/codeql
csharp/ql/test/query-tests/Performance/StringConcatenationInLoop/StringConcatenationInLoop.cs
299
C#
using Joy.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Joy.Common.Implement { public class PcLogger : JLogger { public PcLogger() { base.LogMethods += WriteFile; if (File.Exists(LogFile)) { DateTime n = DateTime.Now; string desFile = string.Concat(LogFile.PathWithoutName(), string.Format("Log_{0}_{1}_{2}_{3}_{4}_{5}_{6}.txt", n.Year, n.Month, n.Day, n.Hour, n.Minute, n.Second, n.Millisecond)); File.Move(LogFile, desFile); } } public void WriteFile(string msg) { File.AppendAllText(LogFile, msg); } } }
21.62069
185
0.679426
[ "MIT" ]
mind0n/hive
History/Website/Store/Joy.Common/Implement/PcLogger.cs
629
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IAccessPackageSearchRequestBuilder. /// </summary> public partial interface IAccessPackageSearchRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IAccessPackageSearchRequest Request(IEnumerable<Option> options = null); } }
36.896552
153
0.582243
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IAccessPackageSearchRequestBuilder.cs
1,070
C#
using NLua; namespace Schuster { public class TaskExtension : ILuaExtension { public void LoadExtension(Lua lua) { lua.LoadCLRPackage(); lua.DoString(@" import ('Pipeline', 'Schuster.Tasks')"); } } }
16.538462
59
0.683721
[ "MIT" ]
MarshallEvergreen/schuster
src/Pipeline/TaskExtension.cs
215
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Funly.SkyStudio { // Subclass to remove templating, so we can serialize this class. [Serializable] public class BoolGroupDictionary : SerializableDictionary<string, BoolKeyframeGroup> { } }
21.785714
86
0.783607
[ "MIT" ]
Dedicatus/PhaseShifter
Assets/FunlySkyStudio/Scripts/Sky Profile/Serializable Collections/BoolGroupDictionary.cs
307
C#
using System; using System.Collections.Generic; using LudicrousElectron.GUI; using LudicrousElectron.GUI.Elements; using LudicrousElectron.GUI.Geometry; using static LunarLambda.API.Events; using LunarLambda.GUI.Menus.Controls; namespace LunarLambda.API { public static class MenuAPI { public static readonly string MainMenuName = "LL.Main.Menu"; public static readonly string OptionsMenuName = "LL.Options.Menu"; public static readonly string StartGameMenuName = "LL.StartGame.Menu"; public static readonly string JoinGameMenuName = "LL.JoinGame.Menu"; public static readonly string GameStatusMenu = "LL.GameStatus.Menu"; public static event EventHandler SetupMenus = null; internal static void CallSetupMenus() { SetupMenus?.Invoke(null, EventArgs.Empty); } public static event EventHandler<StringDataEventArgs> MenuChanged = null; internal static void CallMenuChanged(string newName) { MenuChanged?.Invoke(null, new StringDataEventArgs(newName)); } public static UIButton AddButton(string _menuName, string displayName, int column, int row = -1) { var menuName = _menuName.ToLowerInvariant(); if (!RegisteredAPIButtons.ContainsKey(menuName)) RegisteredAPIButtons.Add(menuName, new List<MenuAPIEventArgs>()); string dn = displayName.ToLowerInvariant(); MenuAPIEventArgs info = RegisteredAPIButtons[menuName].Find((x) => x.Element.Name.ToLowerInvariant() == dn); if (info != null) return info.Element as UIButton; info = new MenuAPIEventArgs(new MenuButton(new RelativeRect()), menuName); info.Element.Name = displayName; (info.Element as UIButton)?.SetText(displayName); info.Row = row; info.Col = column; RegisteredAPIButtons[menuName].Add(info); ControllAdded?.Invoke(info.Element, info); return (info.Element as UIButton); } public static GUIElement AddGUIItem(string _menuName, GUIElement element, int column, int row = -1) { var menuName = _menuName.ToLowerInvariant(); if (!RegisteredAPIButtons.ContainsKey(menuName)) RegisteredAPIButtons.Add(menuName, new List<MenuAPIEventArgs>()); string dn = element.Name.ToLowerInvariant(); MenuAPIEventArgs info = RegisteredAPIButtons[menuName].Find((x) => x.Element.Name.ToLowerInvariant() == dn); if (info != null) return info.Element; info = new MenuAPIEventArgs(new MenuButton(new RelativeRect()), menuName); info.Element = element; info.Row = row; info.Col = column; RegisteredAPIButtons[menuName].Add(info); ControllAdded?.Invoke(info.Element, info); return info.Element; } public class MenuAPIEventArgs { public GUIElement Element = null; public string MenuName = string.Empty; public int Row = -1; public int Col = -1; internal MenuAPIEventArgs(GUIElement button, string menuName) { Element = button; MenuName = menuName; } } internal static event EventHandler<MenuAPIEventArgs> ControllAdded = null; internal static Dictionary<string, List<MenuAPIEventArgs>> RegisteredAPIButtons = new Dictionary<string, List<MenuAPIEventArgs>>(); internal static List<MenuAPIEventArgs> GetAPICtls(string _menuName) { var menuName = _menuName.ToLowerInvariant(); if (!RegisteredAPIButtons.ContainsKey(menuName)) return new List<MenuAPIEventArgs>(); return RegisteredAPIButtons[menuName]; } } }
30.36036
133
0.740356
[ "MIT" ]
JeffM2501/LunarLambda
Application/API/MenuAPI.cs
3,372
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using TMPro; using System; namespace VRestionnaire { public interface IQuestionPanelUI { //void SetQuestion(Question q); //bool CheckMandatory(); //void OnPanelBecameVisible(); //void OnPanelBecameInVissible(); } public abstract class QuestionPanelUI:MonoBehaviour{ public UISkinData skinData; public Button submitButton; public UnityAction<Question> OnQuestionAnswered; public LayoutElement headerLayout; public LayoutElement bodyLayout; public TMP_Text instructionsText; public TMP_Text idText; [HideInInspector]public Question question; public void SetQuestionIDVisibility(bool visible) { idText.gameObject.SetActive(visible); } public virtual void SetQuestion(Question q, UnityAction<Question> answeredEvent, UISkinData skinData) { OnQuestionAnswered += answeredEvent; question = q; if(question.required) { string strAterixColor = "#"+ColorUtility.ToHtmlStringRGB(skinData.requiredAsterixColor); question.instructions += " " + "<" + strAterixColor +"><b>*</b></color>"; } gameObject.name = "QurstionPanel" + question.questiontype + "_" + question.id; if(q.instructions == null || q.instructions.Length == 0) { headerLayout.gameObject.SetActive(false); } this.skinData = skinData; } public abstract void InitWithAnswer(); public virtual bool CheckMandatory() { if(question != null && question.required) { return question.isAnswered; }else { return true; } } public virtual void ShowPanel() { gameObject.SetActive(true); question.showUtcTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); InitWithAnswer(); } public virtual void HidePanel() { gameObject.SetActive(false); question.hideUtcTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } } }
21.640449
103
0.729491
[ "MIT" ]
alexandrovsky/VRestionnaires
VRestionnairesUnity/Assets/VRestionnaires/Scripts/UI/QuestionPanels/QuestionPanelUI.cs
1,928
C#
using System; namespace VersioningSummary { public class VersionDll { public string Name { get; set; } public Version Version { get; set; } public string ReleaseNotes { get; set; } public DateTime? DateRelease { get; set; } } }
21.076923
50
0.609489
[ "MIT" ]
ignatandrei/IsThisTaxiLegal
applications/VersioningSummary/VersionDll.cs
276
C#
using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace blazorui { public class GraphQLAPIClient { private readonly HttpClient _httpClient; public GraphQLAPIClient(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetHelloworld() { GraphQLRequest request = new GraphQLRequest(_httpClient) { OperationName = "welcome", Query = @"{ welcome{} }" }; string response = (await request.PostAsync()).RootElement.GetProperty("welcome").GetString(); return response; } } }
24.942857
105
0.576174
[ "MIT" ]
microsoft/blazor-graphql-starter-kit
blazorui/GraphQLAPIClient.cs
875
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Votorantim.Application.Base { public interface IRequest { } }
15.538462
37
0.752475
[ "MIT" ]
EduGomesTI/ChalengeVotorantim
src/Votorantim.Application/Base/IRequest.cs
204
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SmartCloud.Mvc.Services { public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } }
19.846154
74
0.744186
[ "MIT" ]
zhen08/SmartHomeV1
SmartCloud/SmartCloud.Mvc/Services/IEmailSender.cs
260
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace vlko.core.Tools { public static class HtmlManipulation { /// <summary> /// Removes the tags. /// </summary> /// <param name="htmlInput">The HTML input.</param> /// <returns>Html input with removed tags.</returns> public static string RemoveTags(this string htmlInput) { string result = HtmlSanitizer.Sanitize(htmlInput).Trim(); return Regex.Replace(result, @"<(.|\n)*?>", string.Empty); } /// <summary> /// Shortens the specified input. /// </summary> /// <param name="input">The input.</param> /// <param name="shortenLength">Length of the shorten.</param> /// <param name="additionalShortenText">The additional shorten text.</param> /// <returns>Shorten text</returns> public static string Shorten(this string input, int shortenLength, string additionalShortenText = null) { if (!string.IsNullOrEmpty(additionalShortenText)) { shortenLength -= additionalShortenText.Length; } if (input.Length > shortenLength) { return input.Substring(0, shortenLength) + (string.IsNullOrEmpty(additionalShortenText) ? string.Empty : additionalShortenText); } return input; } } }
27.531915
105
0.691654
[ "MIT" ]
vlko/vlko
vlko.core/Tools/HtmlManipulation.cs
1,296
C#
using TraceabilityEngine.Util; using System; using System.Collections.Generic; using System.Text; namespace TraceabilityEngine.StaticData { public class ProductClaim : ITEStaticData { public string Key { get; set; } public string Name { get; set; } public static ProductClaim GetFromKey(string key) { return GetList().Find(c => c.Key == key); } public static List<ProductClaim> GetList() { EmbeddedResourceLoader loader = new EmbeddedResourceLoader(); TEXML xml = loader.ReadXML("TEStaticData.Data.ProductClaims.xml"); List<ProductClaim> productClaims = new List<ProductClaim>(); foreach (TEXML xProductClaim in xml.ChildElements) { ProductClaim productClaim = new ProductClaim(); productClaim.Key = xProductClaim.Attribute("Key"); productClaim.Name = xProductClaim.Attribute("Name"); productClaims.Add(productClaim); } return productClaims; } } }
32.029412
78
0.61157
[ "MIT" ]
TraceabilityInternet/TraceabilityDriver
TEStaticData/ProductClaim.cs
1,091
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; using XamarinCDWeb.Data; namespace XamarinCDWeb.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20171025064823_AddedEntity_MobileApp")] partial class AddedEntity_MobileApp { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.0-rtm-26452"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("XamarinCDWeb.Data.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("XamarinCDWeb.Data.MobileApp", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ApkFilePath"); b.Property<string>("ApkVersion"); b.Property<string>("IpaFilePath"); b.Property<string>("IpaVersion"); b.Property<string>("Name"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("MobileApps"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("XamarinCDWeb.Data.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("XamarinCDWeb.Data.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("XamarinCDWeb.Data.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("XamarinCDWeb.Data.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
32.633466
95
0.471127
[ "MIT" ]
heavenwing/XamarinDevOpsWeb
CDWeb/XamarinCDWeb/Data/Migrations/20171025064823_AddedEntity_MobileApp.Designer.cs
8,193
C#
using AsyncIO.ProducerConsumer.Models; using AsyncIO.ProducerConsumer.Roles; using AsyncIO.DemoConsole.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace AsyncIO.DemoConsole.Roles { class HidrogenConsumer : Consumer<Hidrogen> { public override void Consume(Hidrogen item, CancellationToken token) { } public override void Finish() { throw new NotImplementedException(); } } }
22.130435
76
0.695481
[ "MIT" ]
Ritor42/AsyncIO.ProducerConsumer
AsyncIO.DemoConsole/Roles/HidrogenConsumer.cs
511
C#
using System; using System.Collections.Generic; using System.Text; namespace EdaSample.Common.Events { public abstract class DomainEvent : IDomainEvent { protected DomainEvent() { this.Id = Guid.NewGuid(); this.Timestamp = DateTime.UtcNow; } public long Sequence { get; set; } public string AggregateRootType { get; set; } public Guid AggregateRootId { get; set; } public Guid Id { get; } public DateTime Timestamp { get; } } }
20.576923
53
0.601869
[ "MIT" ]
daxnet/edasample
src/services/EdaSample.Common/Events/DomainEvent.cs
537
C#
using DATA.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SERVICES { public class EntityService // : Service<Product>, IEntityService { private static IDatabaseFactory dbf = new DatabaseFactory(); private static IUnitOfWork ut = new UnitOfWork(dbf); public EntityService() // : base(ut) { } /* public IEnumerable<Product> GetProductsByCategory(string categoryName) { return ut.getRepository<Product>().GetMany(x => x.Hiscategory.Name == categoryName); } */ } }
21.766667
96
0.660031
[ "MIT" ]
marwenbhz/MULTITENANT
SERVICES/EntityService.cs
655
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NadekoBot.Core.Services.Database; namespace NadekoBot.Migrations { [DbContext(typeof(NadekoContext))] [Migration("20210607221225_PokemonSprite")] partial class PokemonSprite { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.5"); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiRaidSetting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("Action") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("PunishDuration") .HasColumnType("INTEGER"); b.Property<int>("Seconds") .HasColumnType("INTEGER"); b.Property<int>("UserThreshold") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId") .IsUnique(); b.ToTable("AntiRaidSetting"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiSpamIgnore", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("AntiSpamSettingId") .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("AntiSpamSettingId"); b.ToTable("AntiSpamIgnore"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiSpamSetting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("Action") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("MessageThreshold") .HasColumnType("INTEGER"); b.Property<int>("MuteTime") .HasColumnType("INTEGER"); b.Property<ulong?>("RoleId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId") .IsUnique(); b.ToTable("AntiSpamSetting"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AutoCommand", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<string>("ChannelName") .HasColumnType("TEXT"); b.Property<string>("CommandText") .HasColumnType("TEXT"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong?>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("GuildName") .HasColumnType("TEXT"); b.Property<int>("Interval") .HasColumnType("INTEGER"); b.Property<ulong?>("VoiceChannelId") .HasColumnType("INTEGER"); b.Property<string>("VoiceChannelName") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("AutoCommands"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.BanTemplate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Text") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildId") .IsUnique(); b.ToTable("BanTemplates"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.BlacklistEntry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("ItemId") .HasColumnType("INTEGER"); b.Property<int>("Type") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("Blacklist"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubApplicants", b => { b.Property<int>("ClubId") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("ClubId", "UserId"); b.HasIndex("UserId"); b.ToTable("ClubApplicants"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubBans", b => { b.Property<int>("ClubId") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("ClubId", "UserId"); b.HasIndex("UserId"); b.ToTable("ClubBans"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<int>("Discrim") .HasColumnType("INTEGER"); b.Property<string>("ImageUrl") .HasColumnType("TEXT"); b.Property<int>("MinimumLevelReq") .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasColumnType("TEXT") .HasMaxLength(20); b.Property<int>("OwnerId") .HasColumnType("INTEGER"); b.Property<int>("Xp") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasAlternateKey("Name", "Discrim"); b.HasIndex("OwnerId") .IsUnique(); b.ToTable("Clubs"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CommandAlias", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Mapping") .HasColumnType("TEXT"); b.Property<string>("Trigger") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("CommandAlias"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CommandCooldown", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("CommandName") .HasColumnType("TEXT"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("Seconds") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("CommandCooldown"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CurrencyTransaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<long>("Amount") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Reason") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("CurrencyTransactions"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CustomReaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<bool>("AllowTarget") .HasColumnType("INTEGER"); b.Property<bool>("AutoDeleteTrigger") .HasColumnType("INTEGER"); b.Property<bool>("ContainsAnywhere") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("DmResponse") .HasColumnType("INTEGER"); b.Property<ulong?>("GuildId") .HasColumnType("INTEGER"); b.Property<bool>("IsRegex") .HasColumnType("INTEGER"); b.Property<bool>("OwnerOnly") .HasColumnType("INTEGER"); b.Property<string>("Reactions") .HasColumnType("TEXT"); b.Property<string>("Response") .HasColumnType("TEXT"); b.Property<string>("Trigger") .HasColumnType("TEXT"); b.Property<ulong>("UseCount") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("CustomReactions"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.DelMsgOnCmdChannel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<bool>("State") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("DelMsgOnCmdChannel"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.DiscordPermOverride", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Command") .HasColumnType("TEXT"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong?>("GuildId") .HasColumnType("INTEGER"); b.Property<ulong>("Perm") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildId", "Command") .IsUnique(); b.ToTable("DiscordPermOverrides"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.DiscordUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("AvatarId") .HasColumnType("TEXT"); b.Property<int?>("ClubId") .HasColumnType("INTEGER"); b.Property<long>("CurrencyAmount") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Discriminator") .HasColumnType("TEXT"); b.Property<bool>("IsClubAdmin") .HasColumnType("INTEGER"); b.Property<DateTime>("LastLevelUp") .ValueGeneratedOnAdd() .HasColumnType("TEXT") .HasDefaultValue(new DateTime(2017, 9, 21, 20, 53, 13, 305, DateTimeKind.Local)); b.Property<DateTime>("LastXpGain") .HasColumnType("TEXT"); b.Property<int>("NotifyOnLevelUp") .HasColumnType("INTEGER"); b.Property<int>("TotalXp") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<string>("Username") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasAlternateKey("UserId"); b.HasIndex("ClubId"); b.HasIndex("CurrencyAmount"); b.HasIndex("TotalXp"); b.HasIndex("UserId"); b.ToTable("DiscordUser"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ExcludedItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("ItemId") .HasColumnType("INTEGER"); b.Property<int>("ItemType") .HasColumnType("INTEGER"); b.Property<int?>("XpSettingsId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("XpSettingsId"); b.ToTable("ExcludedItem"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FeedSub", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Url") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasAlternateKey("GuildConfigId", "Url"); b.ToTable("FeedSub"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilterChannelId", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int?>("GuildConfigId1") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.HasIndex("GuildConfigId1"); b.ToTable("FilterChannelId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilterLinksChannelId", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("FilterLinksChannelId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilteredWord", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Word") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("FilteredWord"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FollowedStream", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Message") .HasColumnType("TEXT"); b.Property<int>("Type") .HasColumnType("INTEGER"); b.Property<string>("Username") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("FollowedStream"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GCChannelId", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("GCChannelId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GroupName", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<int>("Number") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId", "Number") .IsUnique(); b.ToTable("GroupName"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GuildConfig", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("AutoAssignRoleId") .HasColumnType("INTEGER"); b.Property<bool>("AutoDcFromVc") .HasColumnType("INTEGER"); b.Property<bool>("AutoDeleteByeMessages") .HasColumnType("INTEGER"); b.Property<int>("AutoDeleteByeMessagesTimer") .HasColumnType("INTEGER"); b.Property<bool>("AutoDeleteGreetMessages") .HasColumnType("INTEGER"); b.Property<int>("AutoDeleteGreetMessagesTimer") .HasColumnType("INTEGER"); b.Property<bool>("AutoDeleteSelfAssignedRoleMessages") .HasColumnType("INTEGER"); b.Property<ulong>("ByeMessageChannelId") .HasColumnType("INTEGER"); b.Property<string>("ChannelByeMessageText") .HasColumnType("TEXT"); b.Property<string>("ChannelGreetMessageText") .HasColumnType("TEXT"); b.Property<bool>("CleverbotEnabled") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<float>("DefaultMusicVolume") .HasColumnType("REAL"); b.Property<bool>("DeleteMessageOnCommand") .HasColumnType("INTEGER"); b.Property<string>("DmGreetMessageText") .HasColumnType("TEXT"); b.Property<bool>("ExclusiveSelfAssignedRoles") .HasColumnType("INTEGER"); b.Property<bool>("FilterInvites") .HasColumnType("INTEGER"); b.Property<bool>("FilterLinks") .HasColumnType("INTEGER"); b.Property<bool>("FilterWords") .HasColumnType("INTEGER"); b.Property<ulong?>("GameVoiceChannel") .HasColumnType("INTEGER"); b.Property<ulong>("GreetMessageChannelId") .HasColumnType("INTEGER"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Locale") .HasColumnType("TEXT"); b.Property<int?>("LogSettingId") .HasColumnType("INTEGER"); b.Property<string>("MuteRoleName") .HasColumnType("TEXT"); b.Property<bool>("NotifyStreamOffline") .HasColumnType("INTEGER"); b.Property<string>("PermissionRole") .HasColumnType("TEXT"); b.Property<string>("Prefix") .HasColumnType("TEXT"); b.Property<int?>("RootPermissionId") .HasColumnType("INTEGER"); b.Property<bool>("SendChannelByeMessage") .HasColumnType("INTEGER"); b.Property<bool>("SendChannelGreetMessage") .HasColumnType("INTEGER"); b.Property<bool>("SendDmGreetMessage") .HasColumnType("INTEGER"); b.Property<string>("TimeZoneId") .HasColumnType("TEXT"); b.Property<bool>("VerboseErrors") .HasColumnType("INTEGER"); b.Property<bool>("VerbosePermissions") .HasColumnType("INTEGER"); b.Property<bool>("VoicePlusTextEnabled") .HasColumnType("INTEGER"); b.Property<int>("WarnExpireAction") .HasColumnType("INTEGER"); b.Property<int>("WarnExpireHours") .HasColumnType("INTEGER"); b.Property<bool>("WarningsInitialized") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildId") .IsUnique(); b.HasIndex("LogSettingId"); b.HasIndex("RootPermissionId"); b.HasIndex("WarnExpireHours"); b.ToTable("GuildConfigs"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.IgnoredLogChannel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("LogSettingId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("LogSettingId"); b.ToTable("IgnoredLogChannels"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.IgnoredVoicePresenceChannel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("LogSettingId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("LogSettingId"); b.ToTable("IgnoredVoicePresenceCHannels"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.LogSetting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<bool>("ChannelCreated") .HasColumnType("INTEGER"); b.Property<ulong?>("ChannelCreatedId") .HasColumnType("INTEGER"); b.Property<bool>("ChannelDestroyed") .HasColumnType("INTEGER"); b.Property<ulong?>("ChannelDestroyedId") .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<bool>("ChannelUpdated") .HasColumnType("INTEGER"); b.Property<ulong?>("ChannelUpdatedId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("IsLogging") .HasColumnType("INTEGER"); b.Property<ulong?>("LogOtherId") .HasColumnType("INTEGER"); b.Property<bool>("LogUserPresence") .HasColumnType("INTEGER"); b.Property<ulong?>("LogUserPresenceId") .HasColumnType("INTEGER"); b.Property<bool>("LogVoicePresence") .HasColumnType("INTEGER"); b.Property<ulong?>("LogVoicePresenceId") .HasColumnType("INTEGER"); b.Property<ulong?>("LogVoicePresenceTTSId") .HasColumnType("INTEGER"); b.Property<bool>("MessageDeleted") .HasColumnType("INTEGER"); b.Property<ulong?>("MessageDeletedId") .HasColumnType("INTEGER"); b.Property<bool>("MessageUpdated") .HasColumnType("INTEGER"); b.Property<ulong?>("MessageUpdatedId") .HasColumnType("INTEGER"); b.Property<bool>("UserBanned") .HasColumnType("INTEGER"); b.Property<ulong?>("UserBannedId") .HasColumnType("INTEGER"); b.Property<bool>("UserJoined") .HasColumnType("INTEGER"); b.Property<ulong?>("UserJoinedId") .HasColumnType("INTEGER"); b.Property<bool>("UserLeft") .HasColumnType("INTEGER"); b.Property<ulong?>("UserLeftId") .HasColumnType("INTEGER"); b.Property<ulong?>("UserMutedId") .HasColumnType("INTEGER"); b.Property<ulong>("UserPresenceChannelId") .HasColumnType("INTEGER"); b.Property<bool>("UserUnbanned") .HasColumnType("INTEGER"); b.Property<ulong?>("UserUnbannedId") .HasColumnType("INTEGER"); b.Property<bool>("UserUpdated") .HasColumnType("INTEGER"); b.Property<ulong?>("UserUpdatedId") .HasColumnType("INTEGER"); b.Property<ulong>("VoicePresenceChannelId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("LogSettings"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.MusicPlayerSettings", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<bool>("AutoDisconnect") .HasColumnType("INTEGER"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<ulong?>("MusicChannelId") .HasColumnType("INTEGER"); b.Property<int>("PlayerRepeat") .HasColumnType("INTEGER"); b.Property<int>("QualityPreset") .HasColumnType("INTEGER"); b.Property<int>("Volume") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") .HasDefaultValue(100); b.HasKey("Id"); b.HasIndex("GuildId") .IsUnique(); b.ToTable("MusicPlayerSettings"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.MusicPlaylist", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Author") .HasColumnType("TEXT"); b.Property<ulong>("AuthorId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("MusicPlaylists"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.MutedUserId", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("MutedUserId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.NsfwBlacklitedTag", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Tag") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("NsfwBlacklitedTag"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Permission", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("NextId") .HasColumnType("INTEGER"); b.Property<int>("PrimaryTarget") .HasColumnType("INTEGER"); b.Property<ulong>("PrimaryTargetId") .HasColumnType("INTEGER"); b.Property<int>("SecondaryTarget") .HasColumnType("INTEGER"); b.Property<string>("SecondaryTargetName") .HasColumnType("TEXT"); b.Property<bool>("State") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("NextId") .IsUnique(); b.ToTable("Permission"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Permissionv2", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("Index") .HasColumnType("INTEGER"); b.Property<bool>("IsCustomCommand") .HasColumnType("INTEGER"); b.Property<int>("PrimaryTarget") .HasColumnType("INTEGER"); b.Property<ulong>("PrimaryTargetId") .HasColumnType("INTEGER"); b.Property<int>("SecondaryTarget") .HasColumnType("INTEGER"); b.Property<string>("SecondaryTargetName") .HasColumnType("TEXT"); b.Property<bool>("State") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("Permissionv2"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PlantedCurrency", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<long>("Amount") .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<ulong>("MessageId") .HasColumnType("INTEGER"); b.Property<string>("Password") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("ChannelId"); b.HasIndex("MessageId") .IsUnique(); b.ToTable("PlantedCurrency"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PlaylistSong", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("MusicPlaylistId") .HasColumnType("INTEGER"); b.Property<string>("Provider") .HasColumnType("TEXT"); b.Property<int>("ProviderType") .HasColumnType("INTEGER"); b.Property<string>("Query") .HasColumnType("TEXT"); b.Property<string>("Title") .HasColumnType("TEXT"); b.Property<string>("Uri") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("MusicPlaylistId"); b.ToTable("PlaylistSong"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PokemonSprite", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("Attack") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Defense") .HasColumnType("INTEGER"); b.Property<int>("HP") .HasColumnType("INTEGER"); b.Property<bool>("IsActive") .HasColumnType("INTEGER"); b.Property<bool>("IsShiny") .HasColumnType("INTEGER"); b.Property<int>("Level") .HasColumnType("INTEGER"); b.Property<int>("MaxHP") .HasColumnType("INTEGER"); b.Property<string>("Move1") .HasColumnType("TEXT"); b.Property<string>("Move2") .HasColumnType("TEXT"); b.Property<string>("Move3") .HasColumnType("TEXT"); b.Property<string>("Move4") .HasColumnType("TEXT"); b.Property<string>("NickName") .HasColumnType("TEXT"); b.Property<long>("OwnerId") .HasColumnType("INTEGER"); b.Property<int>("SpecialAttack") .HasColumnType("INTEGER"); b.Property<int>("SpecialDefense") .HasColumnType("INTEGER"); b.Property<int>("SpeciesId") .HasColumnType("INTEGER"); b.Property<int>("Speed") .HasColumnType("INTEGER"); b.Property<string>("StatusEffect") .HasColumnType("TEXT"); b.Property<int>("StatusTurns") .HasColumnType("INTEGER"); b.Property<long>("XP") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("PokemonSprite"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Poll", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Question") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildId") .IsUnique(); b.ToTable("Poll"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PollAnswer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Index") .HasColumnType("INTEGER"); b.Property<int?>("PollId") .HasColumnType("INTEGER"); b.Property<string>("Text") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("PollId"); b.ToTable("PollAnswer"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PollVote", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("PollId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<int>("VoteIndex") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("PollId"); b.ToTable("PollVote"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Quote", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("AuthorId") .HasColumnType("INTEGER"); b.Property<string>("AuthorName") .IsRequired() .HasColumnType("TEXT"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Keyword") .IsRequired() .HasColumnType("TEXT"); b.Property<string>("Text") .IsRequired() .HasColumnType("TEXT"); b.Property<ulong>("UseCount") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildId"); b.HasIndex("Keyword"); b.ToTable("Quotes"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ReactionRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("EmoteName") .HasColumnType("TEXT"); b.Property<int?>("ReactionRoleMessageId") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("ReactionRoleMessageId"); b.ToTable("ReactionRole"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ReactionRoleMessage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("Exclusive") .HasColumnType("INTEGER"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("Index") .HasColumnType("INTEGER"); b.Property<ulong>("MessageId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("ReactionRoleMessage"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Reminder", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("IsPrivate") .HasColumnType("INTEGER"); b.Property<string>("Message") .HasColumnType("TEXT"); b.Property<ulong>("ServerId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<DateTime>("When") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("When"); b.ToTable("Reminders"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Repeater", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("ChannelId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<TimeSpan>("Interval") .HasColumnType("TEXT"); b.Property<ulong?>("LastMessageId") .HasColumnType("INTEGER"); b.Property<string>("Message") .HasColumnType("TEXT"); b.Property<bool>("NoRedundant") .HasColumnType("INTEGER"); b.Property<TimeSpan?>("StartTimeOfDay") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("GuildRepeater"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.RewardedUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("AmountRewardedThisMonth") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<DateTime>("LastReward") .HasColumnType("TEXT"); b.Property<string>("PatreonUserId") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("PatreonUserId") .IsUnique(); b.ToTable("RewardedUsers"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.RotatingPlayingStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Status") .HasColumnType("TEXT"); b.Property<int>("Type") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("RotatingStatus"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.SelfAssignedRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Group") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") .HasDefaultValue(0); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<int>("LevelRequirement") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildId", "RoleId") .IsUnique(); b.ToTable("SelfAssignableRoles"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ShopEntry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("AuthorId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("Index") .HasColumnType("INTEGER"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<int>("Price") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.Property<string>("RoleName") .HasColumnType("TEXT"); b.Property<int>("Type") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("ShopEntry"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ShopEntryItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("ShopEntryId") .HasColumnType("INTEGER"); b.Property<string>("Text") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ShopEntryId"); b.ToTable("ShopEntryItem"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.SlowmodeIgnoredRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("SlowmodeIgnoredRole"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.SlowmodeIgnoredUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("SlowmodeIgnoredUser"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Stake", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<long>("Amount") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<string>("Source") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("Stakes"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleBlacklistedUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("StreamRoleSettingsId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<string>("Username") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("StreamRoleSettingsId"); b.ToTable("StreamRoleBlacklistedUser"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleSettings", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<ulong>("AddRoleId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<ulong>("FromRoleId") .HasColumnType("INTEGER"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("Keyword") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("GuildConfigId") .IsUnique(); b.ToTable("StreamRoleSettings"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleWhitelistedUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("StreamRoleSettingsId") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<string>("Username") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("StreamRoleSettingsId"); b.ToTable("StreamRoleWhitelistedUser"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnbanTimer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<DateTime>("UnbanAt") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("UnbanTimer"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnmuteTimer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<DateTime>("UnmuteAt") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("UnmuteTimer"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnroleTimer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.Property<DateTime>("UnbanAt") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("UnroleTimer"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UserXpStats", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("AwardedXp") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<DateTime>("LastLevelUp") .ValueGeneratedOnAdd() .HasColumnType("TEXT") .HasDefaultValue(new DateTime(2017, 9, 21, 20, 53, 13, 307, DateTimeKind.Local)); b.Property<int>("NotifyOnLevelUp") .HasColumnType("INTEGER"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.Property<int>("Xp") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("AwardedXp"); b.HasIndex("GuildId"); b.HasIndex("UserId"); b.HasIndex("Xp"); b.HasIndex("UserId", "GuildId") .IsUnique(); b.ToTable("UserXpStats"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.VcRoleInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.Property<ulong>("VoiceChannelId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("VcRoleInfo"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("AffinityId") .HasColumnType("INTEGER"); b.Property<int?>("ClaimerId") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Price") .HasColumnType("INTEGER"); b.Property<int>("WaifuId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("AffinityId"); b.HasIndex("ClaimerId"); b.HasIndex("Price"); b.HasIndex("WaifuId") .IsUnique(); b.ToTable("WaifuInfo"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Item") .HasColumnType("INTEGER"); b.Property<string>("ItemEmoji") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<int>("Price") .HasColumnType("INTEGER"); b.Property<int?>("WaifuInfoId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("WaifuInfoId"); b.ToTable("WaifuItem"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuUpdate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("NewId") .HasColumnType("INTEGER"); b.Property<int?>("OldId") .HasColumnType("INTEGER"); b.Property<int>("UpdateType") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("NewId"); b.HasIndex("OldId"); b.HasIndex("UserId"); b.ToTable("WaifuUpdates"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Warning", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<bool>("Forgiven") .HasColumnType("INTEGER"); b.Property<string>("ForgivenBy") .HasColumnType("TEXT"); b.Property<ulong>("GuildId") .HasColumnType("INTEGER"); b.Property<string>("Moderator") .HasColumnType("TEXT"); b.Property<string>("Reason") .HasColumnType("TEXT"); b.Property<ulong>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("DateAdded"); b.HasIndex("GuildId"); b.HasIndex("UserId"); b.ToTable("Warnings"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WarningPunishment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("Count") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int?>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<int>("Punishment") .HasColumnType("INTEGER"); b.Property<ulong?>("RoleId") .HasColumnType("INTEGER"); b.Property<int>("Time") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId"); b.ToTable("WarningPunishment"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpCurrencyReward", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("Amount") .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Level") .HasColumnType("INTEGER"); b.Property<int>("XpSettingsId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("XpSettingsId"); b.ToTable("XpCurrencyReward"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpRoleReward", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("Level") .HasColumnType("INTEGER"); b.Property<ulong>("RoleId") .HasColumnType("INTEGER"); b.Property<int>("XpSettingsId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("XpSettingsId", "Level") .IsUnique(); b.ToTable("XpRoleReward"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpSettings", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime?>("DateAdded") .HasColumnType("TEXT"); b.Property<int>("GuildConfigId") .HasColumnType("INTEGER"); b.Property<string>("NotifyMessage") .HasColumnType("TEXT"); b.Property<bool>("ServerExcluded") .HasColumnType("INTEGER"); b.Property<bool>("XpRoleRewardExclusive") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("GuildConfigId") .IsUnique(); b.ToTable("XpSettings"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiRaidSetting", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithOne("AntiRaidSetting") .HasForeignKey("NadekoBot.Core.Services.Database.Models.AntiRaidSetting", "GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiSpamIgnore", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.AntiSpamSetting", null) .WithMany("IgnoredChannels") .HasForeignKey("AntiSpamSettingId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.AntiSpamSetting", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithOne("AntiSpamSetting") .HasForeignKey("NadekoBot.Core.Services.Database.Models.AntiSpamSetting", "GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubApplicants", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.ClubInfo", "Club") .WithMany("Applicants") .HasForeignKey("ClubId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubBans", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.ClubInfo", "Club") .WithMany("Bans") .HasForeignKey("ClubId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ClubInfo", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "Owner") .WithOne() .HasForeignKey("NadekoBot.Core.Services.Database.Models.ClubInfo", "OwnerId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CommandAlias", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("CommandAliases") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.CommandCooldown", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("CommandCooldowns") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.DelMsgOnCmdChannel", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("DelMsgOnCmdChannels") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.DiscordUser", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.ClubInfo", "Club") .WithMany("Users") .HasForeignKey("ClubId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ExcludedItem", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.XpSettings", null) .WithMany("ExclusionList") .HasForeignKey("XpSettingsId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FeedSub", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithMany("FeedSubs") .HasForeignKey("GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilterChannelId", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("FilterInvitesChannelIds") .HasForeignKey("GuildConfigId"); b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("FilterWordsChannelIds") .HasForeignKey("GuildConfigId1"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilterLinksChannelId", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("FilterLinksChannelIds") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FilteredWord", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("FilteredWords") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.FollowedStream", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("FollowedStreams") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GCChannelId", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithMany("GenerateCurrencyChannelIds") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GroupName", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithMany("SelfAssignableRoleGroupNames") .HasForeignKey("GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.GuildConfig", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.LogSetting", "LogSetting") .WithMany() .HasForeignKey("LogSettingId"); b.HasOne("NadekoBot.Core.Services.Database.Models.Permission", "RootPermission") .WithMany() .HasForeignKey("RootPermissionId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.IgnoredLogChannel", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.LogSetting", "LogSetting") .WithMany("IgnoredChannels") .HasForeignKey("LogSettingId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.IgnoredVoicePresenceChannel", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.LogSetting", "LogSetting") .WithMany("IgnoredVoicePresenceChannelIds") .HasForeignKey("LogSettingId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.MutedUserId", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("MutedUsers") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.NsfwBlacklitedTag", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("NsfwBlacklistedTags") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Permission", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.Permission", "Next") .WithOne("Previous") .HasForeignKey("NadekoBot.Core.Services.Database.Models.Permission", "NextId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Permissionv2", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("Permissions") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PlaylistSong", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.MusicPlaylist", null) .WithMany("Songs") .HasForeignKey("MusicPlaylistId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PollAnswer", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.Poll", null) .WithMany("Answers") .HasForeignKey("PollId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.PollVote", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.Poll", null) .WithMany("Votes") .HasForeignKey("PollId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ReactionRole", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.ReactionRoleMessage", null) .WithMany("ReactionRoles") .HasForeignKey("ReactionRoleMessageId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ReactionRoleMessage", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithMany("ReactionRoleMessages") .HasForeignKey("GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.Repeater", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("GuildRepeaters") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ShopEntry", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("ShopEntries") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.ShopEntryItem", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.ShopEntry", null) .WithMany("Items") .HasForeignKey("ShopEntryId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.SlowmodeIgnoredRole", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("SlowmodeIgnoredRoles") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.SlowmodeIgnoredUser", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("SlowmodeIgnoredUsers") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleBlacklistedUser", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.StreamRoleSettings", null) .WithMany("Blacklist") .HasForeignKey("StreamRoleSettingsId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleSettings", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithOne("StreamRole") .HasForeignKey("NadekoBot.Core.Services.Database.Models.StreamRoleSettings", "GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.StreamRoleWhitelistedUser", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.StreamRoleSettings", null) .WithMany("Whitelist") .HasForeignKey("StreamRoleSettingsId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnbanTimer", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("UnbanTimer") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnmuteTimer", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("UnmuteTimers") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.UnroleTimer", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("UnroleTimer") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.VcRoleInfo", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("VcRoleInfos") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuInfo", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "Affinity") .WithMany() .HasForeignKey("AffinityId"); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "Claimer") .WithMany() .HasForeignKey("ClaimerId"); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "Waifu") .WithOne() .HasForeignKey("NadekoBot.Core.Services.Database.Models.WaifuInfo", "WaifuId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuItem", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.WaifuInfo", null) .WithMany("Items") .HasForeignKey("WaifuInfoId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WaifuUpdate", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "New") .WithMany() .HasForeignKey("NewId"); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "Old") .WithMany() .HasForeignKey("OldId"); b.HasOne("NadekoBot.Core.Services.Database.Models.DiscordUser", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.WarningPunishment", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", null) .WithMany("WarnPunishments") .HasForeignKey("GuildConfigId"); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpCurrencyReward", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.XpSettings", "XpSettings") .WithMany("CurrencyRewards") .HasForeignKey("XpSettingsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpRoleReward", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.XpSettings", "XpSettings") .WithMany("RoleRewards") .HasForeignKey("XpSettingsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("NadekoBot.Core.Services.Database.Models.XpSettings", b => { b.HasOne("NadekoBot.Core.Services.Database.Models.GuildConfig", "GuildConfig") .WithOne("XpSettings") .HasForeignKey("NadekoBot.Core.Services.Database.Models.XpSettings", "GuildConfigId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.488478
117
0.437885
[ "MIT" ]
PetNoire/NadekoBot
NadekoBot.Core/Migrations/20210607221225_PokemonSprite.Designer.cs
93,940
C#
/** * The MIT License * Copyright (c) 2016 Population Register Centre (VRK) * * 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.Collections.Generic; using System.Linq; using Moq; using PTV.Database.DataAccess.Interfaces.DbContext; using PTV.Database.DataAccess.Interfaces.Translators; using PTV.Database.DataAccess.Translators.Types; using PTV.Database.Model.Models; using PTV.Domain.Model.Enums; using PTV.Domain.Model.Models; using Xunit; using PTV.Database.DataAccess.Translators.Organizations; using PTV.Database.DataAccess.Tests.Translators.Common; namespace PTV.Database.DataAccess.Tests.Translators.Organizations { public class OrganizationNameTextTranslatorTest : TranslatorTestBase { private List<object> translators; private IUnitOfWork unitOfWorkMock; public OrganizationNameTextTranslatorTest() { unitOfWorkMock = unitOfWorkMockSetup.Object; translators = new List<object>() { new OrganizationNameTextTranslator(ResolveManager, TranslationPrimitives), RegisterTranslatorMock(new Mock<ITranslator<Language, string>>(), unitOfWorkMock), new NameTypeCodeTranslator(ResolveManager, TranslationPrimitives) }; RegisterDbSet(CreateCodeData<NameType>(typeof(NameTypeEnum)), unitOfWorkMockSetup); RegisterDbSet(new List<OrganizationName>(), unitOfWorkMockSetup); } /// <summary> /// test for OrganizationNameTextTranslator vm - > entity /// </summary> [Fact] public void TranslateOrganizationNameTextToEntity() { var vmName = "testName"; var toTranslate = new List<string>() { vmName }; var translations = RunTranslationModelToEntityTest<string, OrganizationName>(translators, toTranslate, unitOfWorkMock); var translation = translations.First(); Assert.Equal(toTranslate.Count, translations.Count); Assert.Equal(vmName, translation.Name); Assert.Equal(NameTypeEnum.Name.ToString(), translation.Type.Code); } } }
41.855263
131
0.717699
[ "MIT" ]
MikkoVirenius/ptv-1.7
test/PTV.Database.DataAccess.Tests/Translators/Organizations/OrganizationNameTextTranslatorTest.cs
3,183
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.NineOldAndroids.Views; namespace CarouselViewProjectmaster { public class MyFragment : Android.Support.V4.App.Fragment { public MyFragment(){ } public static Android.Support.V4.App.Fragment newInstance(MainActivity context, int pos, float scale,bool IsBlured) { Bundle b = new Bundle(); b.PutInt("pos", pos); b.PutFloat("scale", scale); b.PutBoolean("IsBlured", IsBlured); MyFragment myf = new MyFragment (); return Android.Support.V4.App.Fragment.Instantiate (context,myf.Class.Name, b); } public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } LinearLayout l = (LinearLayout)inflater.Inflate(Resource.Layout.mf, container, false); int pos = this.Arguments.GetInt("pos"); TextView tv = (TextView) l.FindViewById(Resource.Id.viewID); tv.Text = "Position = " + pos; LinearLayout root = (LinearLayout) l.FindViewById(Resource.Id.root); float scale = this.Arguments.GetFloat("scale"); bool isBlured=this.Arguments.GetBoolean("IsBlured"); if(isBlured) { ViewHelper.SetAlpha(root,MyPagerAdapter.getMinAlpha()); ViewHelper.SetRotationY(root, MyPagerAdapter.getMinDegree()); } return l; } } }
25.2
117
0.724206
[ "Apache-2.0" ]
JoinauThomas/cover-flow---base
CarouselViewProject-master/MyFragment.cs
1,514
C#
#region "copyright" /* Copyright © 2016 - 2021 Stefan Berg <isbeorn86+NINA@googlemail.com> and the N.I.N.A. contributors This file is part of N.I.N.A. - Nighttime Imaging 'N' Astronomy. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #endregion "copyright" using System; using System.Runtime.InteropServices; namespace NINA.Equipment.Interfaces { public delegate void ToupTekAlikeCallback(ToupTekAlikeEvent tEvent); public interface IToupTekAlikeCameraSDK { string Category { get; } uint MaxSpeed { get; } bool MonoMode { get; } void get_Temperature(out short temp); void get_Option(ToupTekAlikeOption option, out int target); bool put_Option(ToupTekAlikeOption option, int v); void get_ExpTimeRange(out uint min, out uint max, out uint def); void get_Speed(out ushort speed); bool put_Speed(ushort value); bool get_ExpoAGain(out ushort gain); bool put_AutoExpoEnable(bool v); void get_Size(out int width, out int height); void get_ExpoAGainRange(out ushort min, out ushort max, out ushort def); bool put_ExpoAGain(ushort value); bool StartPullModeWithCallback(ToupTekAlikeCallback toupTekAlikeCallback); bool get_RawFormat(out uint fourCC, out uint bitDepth); bool PullImageV2(ushort[] data, int bitDepth, out ToupTekAlikeFrameInfo info); void Close(); bool put_ExpoTime(uint µsTime); bool Trigger(ushort v); IToupTekAlikeCameraSDK Open(string id); string Version(); } [StructLayout(LayoutKind.Sequential)] public struct ToupTekAlikeFrameInfo { public uint width; public uint height; public uint flag; /* FRAMEINFO_FLAG_xxxx */ public uint seq; /* sequence number */ public ulong timestamp; /* microsecond */ }; public struct ToupTekAlikeResolution { public uint width; public uint height; }; public struct ToupTekAlikeModel { public string name; /* model name */ public ulong flag; /* sdk_FLAG_xxx, 64 bits */ public uint maxspeed; /* number of speed level, same as get_MaxSpeed(), the speed range = [0, maxspeed], closed interval */ public uint preview; /* number of preview resolution, same as get_ResolutionNumber() */ public uint still; /* number of still resolution, same as get_StillResolutionNumber() */ public uint maxfanspeed; /* maximum fan speed */ public uint ioctrol; /* number of input/output control */ public float xpixsz; /* physical pixel size */ public float ypixsz; /* physical pixel size */ public ToupTekAlikeResolution[] res; }; public struct ToupTekAlikeDeviceInfo { public string displayname; /* display name */ public string id; /* unique and opaque id of a connected camera */ public ToupTekAlikeModel model; }; [Flags] public enum ToupTekAlikeFlag : ulong { FLAG_CMOS = 0x00000001, /* cmos sensor */ FLAG_CCD_PROGRESSIVE = 0x00000002, /* progressive ccd sensor */ FLAG_CCD_INTERLACED = 0x00000004, /* interlaced ccd sensor */ FLAG_ROI_HARDWARE = 0x00000008, /* support hardware ROI */ FLAG_MONO = 0x00000010, /* monochromatic */ FLAG_BINSKIP_SUPPORTED = 0x00000020, /* support bin/skip mode */ FLAG_USB30 = 0x00000040, /* usb3.0 */ FLAG_TEC = 0x00000080, /* Thermoelectric Cooler */ FLAG_USB30_OVER_USB20 = 0x00000100, /* usb3.0 camera connected to usb2.0 port */ FLAG_ST4 = 0x00000200, /* ST4 */ FLAG_GETTEMPERATURE = 0x00000400, /* support to get the temperature of the sensor */ FLAG_RAW10 = 0x00001000, /* pixel format, RAW 10bits */ FLAG_RAW12 = 0x00002000, /* pixel format, RAW 12bits */ FLAG_RAW14 = 0x00004000, /* pixel format, RAW 14bits */ FLAG_RAW16 = 0x00008000, /* pixel format, RAW 16bits */ FLAG_FAN = 0x00010000, /* cooling fan */ FLAG_TEC_ONOFF = 0x00020000, /* Thermoelectric Cooler can be turn on or off, support to set the target temperature of TEC */ FLAG_ISP = 0x00040000, /* ISP (Image Signal Processing) chip */ FLAG_TRIGGER_SOFTWARE = 0x00080000, /* support software trigger */ FLAG_TRIGGER_EXTERNAL = 0x00100000, /* support external trigger */ FLAG_TRIGGER_SINGLE = 0x00200000, /* only support trigger single: one trigger, one image */ FLAG_BLACKLEVEL = 0x00400000, /* support set and get the black level */ FLAG_AUTO_FOCUS = 0x00800000, /* support auto focus */ FLAG_BUFFER = 0x01000000, /* frame buffer */ FLAG_DDR = 0x02000000, /* use very large capacity DDR (Double Data Rate SDRAM) for frame buffer */ FLAG_CG = 0x04000000, /* support Conversion Gain mode: HCG, LCG */ FLAG_YUV411 = 0x08000000, /* pixel format, yuv411 */ FLAG_VUYY = 0x10000000, /* pixel format, yuv422, VUYY */ FLAG_YUV444 = 0x20000000, /* pixel format, yuv444 */ FLAG_RGB888 = 0x40000000, /* pixel format, RGB888 */ [Obsolete("Use FLAG_RAW10")] FLAG_BITDEPTH10 = FLAG_RAW10, /* obsolete, same as FLAG_RAW10 */ [Obsolete("Use FLAG_RAW12")] FLAG_BITDEPTH12 = FLAG_RAW12, /* obsolete, same as FLAG_RAW12 */ [Obsolete("Use FLAG_RAW14")] FLAG_BITDEPTH14 = FLAG_RAW14, /* obsolete, same as FLAG_RAW14 */ [Obsolete("Use FLAG_RAW16")] FLAG_BITDEPTH16 = FLAG_RAW16, /* obsolete, same as FLAG_RAW16 */ FLAG_RAW8 = 0x80000000, /* pixel format, RAW 8 bits */ FLAG_GMCY8 = 0x0000000100000000, /* pixel format, GMCY, 8 bits */ FLAG_GMCY12 = 0x0000000200000000, /* pixel format, GMCY, 12 bits */ FLAG_UYVY = 0x0000000400000000, /* pixel format, yuv422, UYVY */ FLAG_CGHDR = 0x0000000800000000, /* Conversion Gain: HCG, LCG, HDR */ FLAG_GLOBALSHUTTER = 0x0000001000000000, /* global shutter */ FLAG_FOCUSMOTOR = 0x0000002000000000, /* support focus motor */ FLAG_PRECISE_FRAMERATE = 0x0000004000000000, /* support precise framerate & bandwidth, see OPTION_PRECISE_FRAMERATE & OPTION_BANDWIDTH */ FLAG_HEAT = 0x0000008000000000, /* heat to prevent fogging up */ FLAG_LOW_NOISE = 0x0000010000000000, /* low noise mode */ FLAG_LEVELRANGE_HARDWARE = 0x0000020000000000, /* hardware level range, put(get)_LevelRangeV2 */ FLAG_EVENT_HARDWARE = 0x0000040000000000 /* hardware event, such as exposure start & stop */ }; public enum ToupTekAlikeEvent : uint { EVENT_EXPOSURE = 0x0001, /* exposure time or gain changed */ EVENT_TEMPTINT = 0x0002, /* white balance changed, Temp/Tint mode */ EVENT_CHROME = 0x0003, /* reversed, do not use it */ EVENT_IMAGE = 0x0004, /* live image arrived, use sdk_PullImage to get this image */ EVENT_STILLIMAGE = 0x0005, /* snap (still) frame arrived, use sdk_PullStillImage to get this frame */ EVENT_WBGAIN = 0x0006, /* white balance changed, RGB Gain mode */ EVENT_TRIGGERFAIL = 0x0007, /* trigger failed */ EVENT_BLACK = 0x0008, /* black balance changed */ EVENT_FFC = 0x0009, /* flat field correction status changed */ EVENT_DFC = 0x000a, /* dark field correction status changed */ EVENT_ROI = 0x000b, /* roi changed */ EVENT_LEVELRANGE = 0x000c, /* level range changed */ EVENT_ERROR = 0x0080, /* generic error */ EVENT_DISCONNECTED = 0x0081, /* camera disconnected */ EVENT_NOFRAMETIMEOUT = 0x0082, /* no frame timeout error */ EVENT_AFFEEDBACK = 0x0083, /* auto focus feedback information */ EVENT_AFPOSITION = 0x0084, /* auto focus sensor board positon */ EVENT_NOPACKETTIMEOUT = 0x0085, /* no packet timeout */ EVENT_EXPO_START = 0x4000, /* exposure start */ EVENT_EXPO_STOP = 0x4001, /* exposure stop */ EVENT_TRIGGER_ALLOW = 0x4002, /* next trigger allow */ EVENT_FACTORY = 0x8001 /* restore factory settings */ }; public enum ToupTekAlikeOption : uint { OPTION_NOFRAME_TIMEOUT = 0x01, /* no frame timeout: 1 = enable; 0 = disable. default: disable */ OPTION_THREAD_PRIORITY = 0x02, /* set the priority of the internal thread which grab data from the usb device. iValue: 0 = THREAD_PRIORITY_NORMAL; 1 = THREAD_PRIORITY_ABOVE_NORMAL; 2 = THREAD_PRIORITY_HIGHEST; default: 0; see: msdn SetThreadPriority */ OPTION_RAW = 0x04, /* raw data mode, read the sensor "raw" data. This can be set only BEFORE sdk_StartXXX(). 0 = rgb, 1 = raw, default value: 0 */ OPTION_HISTOGRAM = 0x05, /* 0 = only one, 1 = continue mode */ OPTION_BITDEPTH = 0x06, /* 0 = 8 bits mode, 1 = 16 bits mode */ OPTION_FAN = 0x07, /* 0 = turn off the cooling fan, [1, max] = fan speed */ OPTION_TEC = 0x08, /* 0 = turn off the thermoelectric cooler, 1 = turn on the thermoelectric cooler */ OPTION_LINEAR = 0x09, /* 0 = turn off the builtin linear tone mapping, 1 = turn on the builtin linear tone mapping, default value: 1 */ OPTION_CURVE = 0x0a, /* 0 = turn off the builtin curve tone mapping, 1 = turn on the builtin polynomial curve tone mapping, 2 = logarithmic curve tone mapping, default value: 2 */ OPTION_TRIGGER = 0x0b, /* 0 = video mode, 1 = software or simulated trigger mode, 2 = external trigger mode, 3 = external + software trigger, default value = 0 */ OPTION_RGB = 0x0c, /* 0 => RGB24; 1 => enable RGB48 format when bitdepth > 8; 2 => RGB32; 3 => 8 Bits Gray (only for mono camera); 4 => 16 Bits Gray (only for mono camera when bitdepth > 8) */ OPTION_COLORMATIX = 0x0d, /* enable or disable the builtin color matrix, default value: 1 */ OPTION_WBGAIN = 0x0e, /* enable or disable the builtin white balance gain, default value: 1 */ OPTION_TECTARGET = 0x0f, /* get or set the target temperature of the thermoelectric cooler, in 0.1 degree Celsius. For example, 125 means 12.5 degree Celsius, -35 means -3.5 degree Celsius */ OPTION_AUTOEXP_POLICY = 0x10, /* auto exposure policy: 0: Exposure Only 1: Exposure Preferred 2: Gain Only 3: Gain Preferred default value: 1 */ OPTION_FRAMERATE = 0x11, /* limit the frame rate, range=[0, 63], the default value 0 means no limit */ OPTION_DEMOSAIC = 0x12, /* demosaic method for both video and still image: BILINEAR = 0, VNG(Variable Number of Gradients interpolation) = 1, PPG(Patterned Pixel Grouping interpolation) = 2, AHD(Adaptive Homogeneity-Directed interpolation) = 3, see https://en.wikipedia.org/wiki/Demosaicing, default value: 0 */ OPTION_DEMOSAIC_VIDEO = 0x13, /* demosaic method for video */ OPTION_DEMOSAIC_STILL = 0x14, /* demosaic method for still image */ OPTION_BLACKLEVEL = 0x15, /* black level */ OPTION_MULTITHREAD = 0x16, /* multithread image processing */ OPTION_BINNING = 0x17, /* binning, 0x01 (no binning), 0x02 (add, 2*2), 0x03 (add, 3*3), 0x04 (add, 4*4), 0x05 (add, 5*5), 0x06 (add, 6*6), 0x07 (add, 7*7), 0x08 (add, 8*8), 0x82 (average, 2*2), 0x83 (average, 3*3), 0x84 (average, 4*4), 0x85 (average, 5*5), 0x86 (average, 6*6), 0x87 (average, 7*7), 0x88 (average, 8*8). The final image size is rounded down to an even number, such as 640/3 to get 212 */ OPTION_ROTATE = 0x18, /* rotate clockwise: 0, 90, 180, 270 */ OPTION_CG = 0x19, /* Conversion Gain mode: 0 = LCG, 1 = HCG, 2 = HDR */ OPTION_PIXEL_FORMAT = 0x1a, /* pixel format */ OPTION_FFC = 0x1b, /* flat field correction set: 0: disable 1: enable -1: reset (0xff000000 | n): set the average number to n, [1~255] get: (val & 0xff): 0 -> disable, 1 -> enable, 2 -> inited ((val & 0xff00) >> 8): sequence ((val & 0xff0000) >> 8): average number */ OPTION_DDR_DEPTH = 0x1c, /* the number of the frames that DDR can cache 1: DDR cache only one frame 0: Auto: ->one for video mode when auto exposure is enabled ->full capacity for others 1: DDR can cache frames to full capacity */ OPTION_DFC = 0x1d, /* dark field correction set: 0: disable 1: enable -1: reset (0xff000000 | n): set the average number to n, [1~255] get: (val & 0xff): 0 -> disable, 1 -> enable, 2 -> inited ((val & 0xff00) >> 8): sequence ((val & 0xff0000) >> 8): average number */ OPTION_SHARPENING = 0x1e, /* Sharpening: (threshold << 24) | (radius << 16) | strength) strength: [0, 500], default: 0 (disable) radius: [1, 10] threshold: [0, 255] */ OPTION_FACTORY = 0x1f, /* restore the factory settings */ OPTION_TEC_VOLTAGE = 0x20, /* get the current TEC voltage in 0.1V, 59 mean 5.9V; readonly */ OPTION_TEC_VOLTAGE_MAX = 0x21, /* get the TEC maximum voltage in 0.1V; readonly */ OPTION_DEVICE_RESET = 0x22, /* reset usb device, simulate a replug */ OPTION_UPSIDE_DOWN = 0x23, /* upsize down: 1: yes 0: no default: 1 (win), 0 (linux/macos) */ OPTION_AFPOSITION = 0x24, /* auto focus sensor board positon */ OPTION_AFMODE = 0x25, /* auto focus mode (0:manul focus; 1:auto focus; 2:once focus; 3:conjugate calibration) */ OPTION_AFZONE = 0x26, /* auto focus zone */ OPTION_AFFEEDBACK = 0x27, /* auto focus information feedback; 0:unknown; 1:focused; 2:focusing; 3:defocus; 4:up; 5:down */ OPTION_TESTPATTERN = 0x28, /* test pattern: 0: TestPattern Off 3: monochrome diagonal stripes 5: monochrome vertical stripes 7: monochrome horizontal stripes 9: chromatic diagonal stripes */ OPTION_AUTOEXP_THRESHOLD = 0x29, /* threshold of auto exposure, default value: 5, range = [2, 15] */ OPTION_BYTEORDER = 0x2a, /* Byte order, BGR or RGB: 0->RGB, 1->BGR, default value: 1(Win), 0(macOS, Linux, Android) */ OPTION_NOPACKET_TIMEOUT = 0x2b, /* no packet timeout: 0 = disable, positive value = timeout milliseconds. default: disable */ OPTION_MAX_PRECISE_FRAMERATE = 0x2c, /* precise frame rate maximum value in 0.1 fps, such as 115 means 11.5 fps. E_NOTIMPL means not supported */ OPTION_PRECISE_FRAMERATE = 0x2d, /* precise frame rate current value in 0.1 fps, range:[1~maximum] */ OPTION_BANDWIDTH = 0x2e, /* bandwidth, [1-100]% */ OPTION_RELOAD = 0x2f, /* reload the last frame in trigger mode */ OPTION_CALLBACK_THREAD = 0x30, /* dedicated thread for callback */ OPTION_FRAME_DEQUE_LENGTH = 0x31, /* frame buffer deque length, range: [2, 1024], default: 3 */ OPTION_MIN_PRECISE_FRAMERATE = 0x32, /* precise frame rate minimum value in 0.1 fps, such as 15 means 1.5 fps */ OPTION_SEQUENCER_ONOFF = 0x33, /* sequencer trigger: on/off */ OPTION_SEQUENCER_NUMBER = 0x34, /* sequencer trigger: number, range = [1, 255] */ OPTION_SEQUENCER_EXPOTIME = 0x01000000, /* sequencer trigger: exposure time, iOption = OPTION_SEQUENCER_EXPOTIME | index, iValue = exposure time For example, to set the exposure time of the third group to 50ms, call: sdk_put_Option(sdk_OPTION_SEQUENCER_EXPOTIME | 3, 50000) */ OPTION_SEQUENCER_EXPOGAIN = 0x02000000, /* sequencer trigger: exposure gain, iOption = OPTION_SEQUENCER_EXPOGAIN | index, iValue = gain */ OPTION_DENOISE = 0x35, /* denoise, strength range: [0, 100], 0 means disable */ OPTION_HEAT_MAX = 0x36, /* maximum level: heat to prevent fogging up */ OPTION_HEAT = 0x37, /* heat to prevent fogging up */ OPTION_LOW_NOISE = 0x38, /* low noise mode: 1 => enable */ OPTION_POWER = 0x39, /* get power consumption, unit: milliwatt */ OPTION_GLOBAL_RESET_MODE = 0x3a, /* global reset mode */ OPTION_OPEN_USB_ERRORCODE = 0x3b, /* open usb error code */ OPTION_LINUX_USB_ZEROCOPY = 0x3c, /* global option for linux platform: enable or disable usb zerocopy (helps to reduce memory copy and improve efficiency. Requires kernel version >= 4.6 and hardware platform support) if the image is wrong, this indicates that the hardware platform does not support this feature, please disable it when the program starts: sdk_put_Option((this is a global option, the camera handle parameter is not required, use nullptr), sdk_OPTION_LINUX_USB_ZEROCOPY, 0) default value: disable(0): android or arm32 enable(1): others */ OPTION_FLUSH = 0x3d /* 1 = hard flush, discard frames cached by camera DDR (if any) 2 = soft flush, discard frames cached by sdk.dll (if any) 3 = both flush sdk_Flush means 'both flush' */ }; }
66.889251
417
0.544193
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
daleghent/NINA
NINA.Equipment/Interfaces/IToupTekAlikeCameraSDK.cs
20,539
C#
using System.Text.Json.Serialization; namespace Forms.Infrastructure.CloudFoundry.Models { public class Credentials { [JsonPropertyName("host")] public string Host { get; set; } [JsonPropertyName("password")] public string Password { get; set; } [JsonPropertyName("port")] public int Port { get; set; } [JsonPropertyName("tls_enabled")] public bool TlsEnabled { get; set; } } }
28.875
50
0.614719
[ "Apache-2.0" ]
mod-veterans/digital-service-web-app
Forms.Infrastructure/CloudFoundry/Models/Credentials.cs
462
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Shriek.ServiceProxy.Http.Server.Internal { internal class ServiceControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature> { private const string ControllerTypeNameSuffix = "Controller"; private readonly IEnumerable<Type> ServiceTypes; public ServiceControllerFeatureProvider(IEnumerable<Type> ServiceTypes) { this.ServiceTypes = ServiceTypes; } public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature) { foreach (var type in AppDomain.CurrentDomain.GetAllTypes()) { if (IsController(type) || ServiceTypes.Any(o => type.IsClass && o.IsAssignableFrom(type)/* && o.Assembly == type.Assembly*/) && !feature.Controllers.Contains(type)) { feature.Controllers.Add(type.GetTypeInfo()); } } } protected bool IsController(Type typeInfo) { if (!typeInfo.IsClass) { return false; } if (typeInfo.IsAbstract) { return false; } // We only consider public top-level classes as controllers. IsPublic returns false for nested // classes, regardless of visibility modifiers if (!typeInfo.IsPublic) { return false; } if (typeInfo.ContainsGenericParameters) { return false; } if (typeInfo.IsDefined(typeof(NonControllerAttribute))) { return false; } if (!typeInfo.Name.EndsWith(ControllerTypeNameSuffix, StringComparison.OrdinalIgnoreCase) && !typeInfo.IsDefined(typeof(ControllerAttribute))) { return false; } return true; } } }
31.114286
180
0.584481
[ "MIT" ]
alexinea/shriek-fx
src/Shriek.ServiceProxy.Http.Server/Internal/ServiceControllerFeatureProvider.cs
2,180
C#
using System.ComponentModel.DataAnnotations; namespace Amazon.Kinesis.Firehose; public sealed class ListDeliveryStreamsRequest { [StringLength(64)] public string? DeliveryStreamType { get; init; } public string? ExclusiveStartDeliveryStreamName { get; init; } public int? Limit { get; init; } } public class ListDeliveryStreamsResult { }
20.944444
67
0.721485
[ "MIT" ]
TheJVaughan/Amazon
src/Amazon.Kinesis.Firehose/Actions/ListDeliveryStreamsRequest.cs
379
C#
using Newtonsoft.Json; using System; namespace AdelaideFuel.Shared { public class SiteDto : ISite { [JsonProperty("S")] public int SiteId { get; set; } [JsonProperty("A")] public string Address { get; set; } [JsonProperty("N")] public string Name { get; set; } [JsonProperty("B")] public int BrandId { get; set; } [JsonProperty("P")] public string Postcode { get; set; } [JsonProperty("G1")] public int GeographicRegionLevel1 { get; set; } [JsonProperty("G2")] public int GeographicRegionLevel2 { get; set; } [JsonProperty("G3")] public int GeographicRegionLevel3 { get; set; } [JsonProperty("G4")] public int GeographicRegionLevel4 { get; set; } [JsonProperty("G5")] public int GeographicRegionLevel5 { get; set; } [JsonProperty("Lat")] public double Latitude { get; set; } [JsonProperty("Lng")] public double Longitude { get; set; } [JsonProperty("M")] public DateTime LastModifiedUtc { get; set; } [JsonProperty("GPI")] public string GooglePlaceId { get; set; } [JsonProperty("MO")] public string MondayOpen { get; set; } [JsonProperty("MC")] public string MondayClose { get; set; } [JsonProperty("TO")] public string TuesdayOpen { get; set; } [JsonProperty("TC")] public string TuesdayClose { get; set; } [JsonProperty("WO")] public string WednesdayOpen { get; set; } [JsonProperty("WC")] public string WednesdayClose { get; set; } [JsonProperty("THO")] public string ThursdayOpen { get; set; } [JsonProperty("THC")] public string ThursdayClose { get; set; } [JsonProperty("FO")] public string FridayOpen { get; set; } [JsonProperty("FC")] public string FridayClose { get; set; } [JsonProperty("SO")] public string SaturdayOpen { get; set; } [JsonProperty("SC")] public string SaturdayClose { get; set; } [JsonProperty("SUO")] public string SundayOpen { get; set; } [JsonProperty("SUC")] public string SundayClose { get; set; } } }
25.26087
55
0.562823
[ "MIT" ]
dmariogatto/adelaidefuel
src/AdelaideFuel.Shared/Models/Api/SiteDto.cs
2,326
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Api.ViewModel { public class UserInfo { public string Id { get; set; } public string Nom { get; set; } } }
18.357143
40
0.626459
[ "Apache-2.0" ]
Schlagadiguenflu/confluences-teletravail
src/Api/ViewModel/UserInfo.cs
259
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; using HugsLib.Utils; namespace RimWorldOnlineCity.UI { public class Dialog_SelectThingDef : Window { public Action PostCloseAction; public ThingDef SelectThingDef = null; public FloatRange SelectHitPointsPercents = FloatRange.ZeroToOne; public QualityRange SelectQualities = QualityRange.All; private ThingFilter thingFilter = new ThingFilter(); private Vector2 scrollPosition; public void ClearFilter() { thingFilter = new ThingFilter(); thingFilter.AllowedQualityLevels = new QualityRange(QualityCategory.Normal, QualityCategory.Legendary); thingFilter.AllowedHitPointsPercents = new FloatRange(0.8f, 1); thingFilter.SetDisallowAll(null, null); } public override Vector2 InitialSize { get { return new Vector2(350f, 700f); } } public override void PreOpen() { base.PreOpen(); } public override void PostClose() { base.PostClose(); if (PostCloseAction != null) PostCloseAction(); } public override void DoWindowContents(Rect inRect) { if (thingFilter.AllowedThingDefs.Count() > 1) { thingFilter = new ThingFilter(); thingFilter.AllowedQualityLevels = SelectQualities; thingFilter.AllowedHitPointsPercents = SelectHitPointsPercents; thingFilter.SetDisallowAll(null, null); } SelectThingDef = thingFilter.AllowedThingDefs.FirstOrDefault(); SelectQualities = thingFilter.AllowedQualityLevels; SelectHitPointsPercents = thingFilter.AllowedHitPointsPercents; const float mainListingSpacing = 6f; var btnSize = new Vector2(140f, 40f); var buttonYStart = inRect.height - btnSize.y; /* var ev = Event.current; if (Widgets.ButtonText(new Rect(0, buttonYStart, btnSize.x, btnSize.y), "OCity_DialogInput_Ok".Translate()) || ev.isKey && ev.type == EventType.keyDown && ev.keyCode == KeyCode.Return) */ if (SelectThingDef != null) { Close(); } if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x, buttonYStart, btnSize.x, btnSize.y), "OCity_DialogInput_Cancele".Translate())) { Close(); } //выше кнопок Rect workRect = new Rect(inRect.x, inRect.y, inRect.width, buttonYStart - mainListingSpacing); ThingFilterUI.DoThingFilterConfigWindow(workRect, ref this.scrollPosition, thingFilter, null, 8, null, null, null); } } }
32.373626
148
0.609301
[ "Apache-2.0" ]
PsyPatron/OnlineCity
Source/RimWorldOnlineCity/UI/Dialog_SelectThingDef.cs
2,958
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TPP.Core.Data.Entities { [Table("Note")] public class Note : EntityBase { [Required] public string Text { get; set; } public DateTime Created { get; set; } } }
23.277778
60
0.689737
[ "MIT" ]
Bhaskers-Blu-Org2/SPP_Public
src/api/Data/TPP.Core.Data/Entities/Note.cs
419
C#
/* Copyright 2010 MCLawl Team - Written by Valek (Modified for use with MCForge) Dual-licensed under the Educational Community License, Version 2.0 and the GNU General Public License, Version 3 (the "Licenses"); you may not use this file except in compliance with the Licenses. You may obtain a copy of the Licenses at http://www.osedu.org/licenses/ECL-2.0 http://www.gnu.org/licenses/gpl-3.0.html Unless required by applicable law or agreed to in writing, software distributed under the Licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the specific language governing permissions and limitations under the Licenses. */ namespace MCForge.Commands { public class CmdAlive : Command { public override string name { get { return "alive"; } } public override string shortcut { get { return "alive"; } } public override string type { get { return "mod"; } } public override bool museumUsable { get { return true; } } public override LevelPermission defaultRank { get { return LevelPermission.Banned; } } public CmdAlive() { } public override void Use(Player p, string message) { // Player who = null; if (ZombieGame.alive.Count == 0) { Player.SendMessage(p, "No one is alive."); } else { Player.SendMessage(p, "Players who are " + c.green + "alive " + Server.DefaultColor + "are:"); string playerstring = ""; ZombieGame.alive.ForEach(delegate(Player player) { playerstring = playerstring + player.group.color + player.name + Server.DefaultColor + ", "; }); Player.SendMessage(p, playerstring); } } public override void Help(Player p) { Player.SendMessage(p, "/alive - shows who is alive"); } } }
39.901961
112
0.61769
[ "Unlicense" ]
MCForge/MCForge-Vanilla-Redux
Commands/CmdAlive.cs
2,035
C#
// ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Nova.Expressions; using Nova.Parser; using BlockExpression = Nova.Expressions.BlockExpression; // <copyright file="NovaPartialFunction.cs" Company="Michael Tindal"> // Copyright 2011-2013 Michael Tindal // // 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. // </copyright> // ----------------------------------------------------------------------- namespace Nova.Runtime { /// <summary> /// TODO: Update summary. /// </summary> public partial class NovaNativeFunction : NovaFunction { private static readonly Dictionary<MethodBase, List<FunctionArgument>> ArgumentCache = new Dictionary<MethodBase, List<FunctionArgument>>(); public NovaNativeFunction(Type target, MethodBase method) : base( GetExportName(method) ?? (method.IsConstructor ? "new" : method.Name), GenerateArguments(method), GenerateBody(target, method), new NovaScope()) { Func<MethodBase, bool> chkDoNotExportMethod = t => { var a = t.GetCustomAttributes(typeof (NovaDoNotExportAttribute), false).FirstOrDefault(); return a != null; }; if (chkDoNotExportMethod(method)) { Name = "<__doNotExport>"; return; } Target = target; Method = method; NumberOfArguments = method.GetParameters().Count(); } public Type Target { get; private set; } public MethodBase Method { get; private set; } public int NumberOfArguments { get; private set; } public static List<FunctionArgument> GenerateArguments(MethodBase method) { if (ArgumentCache.ContainsKey(method)) { return ArgumentCache[method]; } var args = new List<FunctionArgument>(); method.GetParameters().ToList().ForEach(p => { var arg = new FunctionArgument(p.Name); if (p.GetCustomAttributes(typeof (ParamArrayAttribute), false).Any()) { arg.IsVarArg = true; } if (p.DefaultValue != null && p.DefaultValue.GetType() != typeof (DBNull)) { arg.HasDefault = true; arg.DefaultValue = Expression.Constant(p.DefaultValue); } args.Add(arg); }); ArgumentCache[method] = args; return args; } public static BlockExpression GenerateBody(Type type, MethodBase method) { var body = new List<Expression>(); body.Add( NovaExpression.Invoke( Expression.Constant(method.IsConstructor ? typeof (NovaInstance) : type, typeof (Type)), Expression.Constant(method, typeof (MethodBase)), ArgumentCache[method])); body.Add(Expression.Label(NovaParser.ReturnTarget, Expression.Constant(null, typeof (object)))); return NovaExpression.NovaBlock(body.ToArray()); } public static string GetExportName(MethodBase t) { var a = t.GetCustomAttributes(typeof (NovaExportAttribute), false).FirstOrDefault(); return a != null ? ((NovaExportAttribute) a).Name : null; } public override string ToString() { return string.Format("[NovaNativeFunction: TargetType={0}, Scope={1}]", Target, Scope); } } }
42.717172
114
0.581934
[ "Apache-2.0" ]
chaoticvoid/Nova
Nova/Runtime/NovaNativeFunction.cs
4,229
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 servicecatalog-2015-12-10.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.ServiceCatalog.Model { /// <summary> /// Container for the parameters to the DescribeProduct operation. /// Retrieves information about a specified product. /// /// /// <para> /// This operation is functionally identical to <a>DescribeProductView</a> except that /// it takes as input <code>ProductId</code> instead of <code>ProductViewId</code>. /// </para> /// </summary> public partial class DescribeProductRequest : AmazonServiceCatalogRequest { private string _acceptLanguage; private string _id; /// <summary> /// Gets and sets the property AcceptLanguage. /// <para> /// Optional language code. Supported language codes are as follows: /// </para> /// /// <para> /// "en" (English) /// </para> /// /// <para> /// "jp" (Japanese) /// </para> /// /// <para> /// "zh" (Chinese) /// </para> /// /// <para> /// If no code is specified, "en" is used as the default. /// </para> /// </summary> public string AcceptLanguage { get { return this._acceptLanguage; } set { this._acceptLanguage = value; } } // Check to see if AcceptLanguage property is set internal bool IsSetAcceptLanguage() { return this._acceptLanguage != null; } /// <summary> /// Gets and sets the property Id. /// <para> /// The <code>ProductId</code> of the product to describe. /// </para> /// </summary> public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } } }
28.897959
112
0.578037
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/ServiceCatalog/Generated/Model/DescribeProductRequest.cs
2,832
C#
using FluentValidation; using FluentValidation.Results; using iRLeagueApiCore.Communication.Models; using iRLeagueApiCore.Server.Handlers.Scorings; using iRLeagueApiCore.UnitTests.Fixtures; using iRLeagueDatabaseCore.Models; using Microsoft.AspNetCore.Identity.Test; using Microsoft.Extensions.Logging; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Transactions; using Xunit; namespace iRLeagueApiCore.UnitTests.Server.Handlers.Scorings { [Collection("HandlerTests")] public class PostScoringHandlerTests : HandlersTestsBase<PostScoringHandler, PostScoringRequest, ScoringModel>, IClassFixture<DbTestFixture> { public PostScoringHandlerTests(DbTestFixture fixture) : base(fixture) { } protected override PostScoringRequest DefaultRequest() { return DefaultRequest(testLeagueId, testScoringId); } protected PostScoringRequest DefaultRequest(long leagueId, long seasonId) { var model = new PostScoringModel() { BasePoints = new double[0], BonusPoints = new string[0] }; return new PostScoringRequest(leagueId, seasonId, model); } protected override PostScoringHandler CreateTestHandler(LeagueDbContext dbContext, IValidator<PostScoringRequest> validator) { return new PostScoringHandler(logger, dbContext, new IValidator<PostScoringRequest>[] { validator }); } protected override void DefaultAssertions(PostScoringRequest request, ScoringModel result, LeagueDbContext dbContext) { base.DefaultAssertions(request, result, dbContext); Assert.NotEqual(0, result.Id); Assert.Contains(dbContext.Scorings, x => x.ScoringId == result.Id); Assert.Empty(result.BasePoints); Assert.Empty(result.BonusPoints); } [Fact] public override async Task<ScoringModel> HandleDefaultAsync() { return await base.HandleDefaultAsync(); } [Theory] [InlineData(0,testSeasonId)] [InlineData(testLeagueId,0)] [InlineData(42,testSeasonId)] [InlineData(testLeagueId,42)] public async Task HandleNotFoundAsync(long leagueId, long seasonId) { var request = DefaultRequest(leagueId, seasonId); await base.HandleNotFoundRequestAsync(request); } [Fact] public override async Task HandleValidationFailedAsync() { await base.HandleValidationFailedAsync(); } } }
34.113924
144
0.678664
[ "MIT" ]
SSchulze1989/iRLeagueApiCore
iRLeagueApiCore.UnitTests/Server/Handlers/Scorings/PostScoringHandlerTests.cs
2,697
C#
using System.Collections.Generic; namespace Sledge.BspEditor.Tools.Draggable { public interface IDraggableState : IDraggable { IEnumerable<IDraggable> GetDraggables(); } }
21.333333
49
0.734375
[ "BSD-3-Clause" ]
LogicAndTrick/sledge
Sledge.BspEditor.Tools/Draggable/IDraggableState.cs
192
C#
using Amazon.CodeCommit; using Amazon.CodeCommit.Model; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; using Amazon.Lambda.Core; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; using Amazon; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace PBnCLambda { public class Function { private static string ConfigPathEnvVar = "CC2AF_CONFIG_PATH"; private static string ConfigPathDefault = "cc2af.yml"; private static string SrcBranchDefault = "master"; private static Deserializer YamlDeserializer = new DeserializerBuilder().Build(); private static HttpClient Http = new HttpClient(); /// <summary> /// A function to handle a CodeCommit Event. /// </summary> /// <param name="commitEvent"></param> /// <param name="context"></param> /// <returns></returns> public void FunctionHandler(CodeCommitEvent commitEvent, ILambdaContext context) { string repositoryName = commitEvent.Records[0].RepositoryName; string branch = commitEvent.Records[0].codecommit.references[0].Branch; string commit = commitEvent.Records[0].codecommit.references[0].commit; string region = commitEvent.Records[0].awsRegion; string configPath = Environment.GetEnvironmentVariable(ConfigPathEnvVar); configPath = String.IsNullOrWhiteSpace(configPath) ? ConfigPathDefault : configPath; var codeCommit = new AmazonCodeCommitClient(RegionEndpoint.GetBySystemName(region)); var repository = codeCommit.GetRepositoryAsync( new GetRepositoryRequest() {RepositoryName = repositoryName} ).GetAwaiter().GetResult(); var config = GetCc2AfConfig(codeCommit, repositoryName, commit, configPath); var srcBranch = String.IsNullOrWhiteSpace(config.CodeCommitBranch) ? SrcBranchDefault : config.CodeCommitBranch; HttpResponseMessage response = null; if (branch == srcBranch) { var deploymentPassword = ConvertFromEncryptedBase64(config.DeploymentPassword); var codeCommitPassword = ConvertFromEncryptedBase64(config.CodeCommitPassword); response = InvokeDeployment(http: Http, deploymentAppUrl: config.DeploymentTriggerUrl, deploymentAppName: config.DeploymentAppName, deploymentUser: config.DeploymentUser, deploymentPassword: deploymentPassword, codeCommitHttpsUrl: repository.RepositoryMetadata.CloneUrlHttp, codeCommitUser: config.CodeCommitUser, codeCommitPassword: codeCommitPassword); } WriteResults(response, configPath, config, repository, region, repositoryName, branch, commit, srcBranch); } public static void WriteResults(HttpResponseMessage response, string configPath, Cc2AfConfig config, GetRepositoryResponse repository, string region, string repositoryName, string branch, string commit, string srcBranch) { var dictionary = new Dictionary<string,object>(){ // Display only fields that do not contain secrets {"Response", new Dictionary<string,object>(){ {"Headers", response.Headers}, {"Status", response.StatusCode}, {"ReasonPhrase", response.ReasonPhrase}, {"Content", response.Content}, {"IsSuccessStatusCode", response.IsSuccessStatusCode}}}, {"Resquest", new Dictionary<string,object>(){ {"Uri", response.RequestMessage.RequestUri}, {"Method", response.RequestMessage.Method}, {"ContentHeaders", response.Content.Headers}}}, {"ConfigPath", configPath}, {"Config", config}, {"Region", region}, {"Repository", repository}, {"RepositoryName", repositoryName}, {"Branch", branch}, {"Commit", commit}, {"SrcBranch", srcBranch} }; Console.WriteLine(JsonConvert.SerializeObject(dictionary)); } public static string ConvertFromEncryptedBase64 (string encryptedBase64) { string result; using (var kms = new AmazonKeyManagementServiceClient()) { var response = kms.DecryptAsync(new DecryptRequest(){ CiphertextBlob = new MemoryStream(Convert.FromBase64String(encryptedBase64)) }).GetAwaiter().GetResult(); using (TextReader reader = new StreamReader(response.Plaintext)) { result = reader.ReadToEnd(); } } return result; } public static Cc2AfConfig GetCc2AfConfig(AmazonCodeCommitClient codeCommit, string repositoryName, string afterCommitSpecifier, string configPath) { Cc2AfConfig result; var differences = GetDifferences(codeCommit, repositoryName, afterCommitSpecifier); var configDiff = GetConfigurationDifference(differences, configPath); if (configDiff == null) { var ex = new FileNotFoundException($"Unable to find Cc2Fa Configuration YAML file '{configPath}'.", configPath); throw ex; } var configBlob = codeCommit.GetBlobAsync(new GetBlobRequest(){ BlobId = configDiff.AfterBlob.BlobId, RepositoryName = repositoryName }).GetAwaiter().GetResult(); using (var reader = new StreamReader(configBlob.Content)) { result = YamlDeserializer.Deserialize<Cc2AfConfig>(reader); } return result; } public static List<Difference> GetDifferences (AmazonCodeCommitClient codeCommit, string repositoryName, string afterCommitSpecifier) { var result = new List<Difference>(); GetDifferencesRequest request; GetDifferencesResponse response; string nextToken = String.Empty; int count = 0; do { count++; Console.WriteLine($"Count: {count}; RepositoryName: {repositoryName}; AfterCommitSpecifier: {afterCommitSpecifier}; Next: {nextToken}"); request = new GetDifferencesRequest(){ RepositoryName = repositoryName, AfterCommitSpecifier = afterCommitSpecifier}; if (!String.IsNullOrWhiteSpace(nextToken)) { request.NextToken = nextToken; } response = codeCommit.GetDifferencesAsync(request).GetAwaiter().GetResult(); result.AddRange(response.Differences); nextToken = response.NextToken; } while (!String.IsNullOrEmpty(nextToken)); return result; } public static Difference GetConfigurationDifference(IList<Difference> differences, string configPath) { Difference result; result = differences.Where( d => d.AfterBlob.Path == configPath).FirstOrDefault(); return result; } public static HttpResponseMessage InvokeDeployment(HttpClient http, string deploymentAppUrl, string deploymentUser, string deploymentPassword, string deploymentAppName, string codeCommitUser, string codeCommitPassword, string codeCommitHttpsUrl) { var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{deploymentUser}:{deploymentPassword}")); var request = new HttpRequestMessage(); request.Headers.Add("Authorization", $"Basic {auth}"); request.Headers.Add("X-SITE-DEPLOYMENT-ID",deploymentAppName); request.RequestUri = new Uri(deploymentAppUrl); request.Method = HttpMethod.Post; var builder = new UriBuilder(codeCommitHttpsUrl); builder.UserName = Uri.EscapeDataString(codeCommitUser); builder.Password = Uri.EscapeDataString(codeCommitPassword); var bodyString = JsonConvert.SerializeObject(new Dictionary<string,string>(){ {"format", "basic"}, {"url", builder.ToString()} }); var bodyBytes = Encoding.UTF8.GetBytes(bodyString); request.Content = new ByteArrayContent(bodyBytes); return http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead).GetAwaiter().GetResult(); } } }
46.257426
253
0.61098
[ "MIT" ]
markekraus/PeanutButterChocolate
CSLambda/PBnCLambda/Function.cs
9,344
C#
using UnityEngine; public class HumanDrag : MonoBehaviour { public OutlinePostEffect OutlinePostEffect; public bool canDrag = true; private void OnMouseEnter() => OutlinePostEffect.samplerScale = 0.8f; private void OnMouseExit() => OutlinePostEffect.samplerScale = 0; private float mouseX; private bool isUp = false; private void OnMouseDrag() { if (canDrag) { isUp = false; mouseX = Input.GetAxis("Mouse X"); transform.localEulerAngles -= new Vector3(0, mouseX * 5, 0); } } private void OnMouseUp() { if(canDrag) isUp = true; } private void Update() { if (canDrag) if (isUp) transform.localEulerAngles = new Vector3(0, Mathf.Lerp(transform.localEulerAngles.y, 150, Time.deltaTime * 4), 0); } }
24.969697
145
0.632282
[ "MIT" ]
Anarchy-Massacre-Studio/TheFPSGame
Assets/Script/UIScript/HumanDrag.cs
826
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCampaignExtensionSettingServiceClientTest { [Category("Smoke")][Test] public void GetCampaignExtensionSettingRequestObject() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetCampaignExtensionSettingRequestObjectAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetCampaignExtensionSetting() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetCampaignExtensionSettingAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetCampaignExtensionSettingResourceNames() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request.ResourceNameAsCampaignExtensionSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetCampaignExtensionSettingResourceNamesAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request.ResourceNameAsCampaignExtensionSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request.ResourceNameAsCampaignExtensionSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void MutateCampaignExtensionSettingsRequestObject() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse response = client.MutateCampaignExtensionSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task MutateCampaignExtensionSettingsRequestObjectAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse responseCallSettings = await client.MutateCampaignExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignExtensionSettingsResponse responseCancellationToken = await client.MutateCampaignExtensionSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void MutateCampaignExtensionSettings() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse response = client.MutateCampaignExtensionSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task MutateCampaignExtensionSettingsAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse responseCallSettings = await client.MutateCampaignExtensionSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignExtensionSettingsResponse responseCancellationToken = await client.MutateCampaignExtensionSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
69.105096
270
0.709664
[ "Apache-2.0" ]
googleads/google-ads-dotnet
tests/V9/Services/CampaignExtensionSettingServiceClientTest.g.cs
21,699
C#