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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndByte() { var test = new SimpleBinaryOpTest__AndByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / sizeof(Byte); private const int RetElementCount = VectorSize / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static SimpleBinaryOpTest__AndByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AndByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.And( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.And( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.And( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndByte(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { if ((byte)(left[0] & right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] & right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
41.172205
144
0.565233
[ "MIT" ]
ruben-ayrapetyan/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Avx2/And.Byte.cs
13,628
C#
using EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccessLayer.Abstract { public interface ICommentDal:IGenericDal<Comment> { } }
17.357143
51
0.802469
[ "MIT" ]
batuhansariikaya/MVC_CoreBlogProject
CoreProject_MVC/DataAccessLayer/Abstract/ICommentDal.cs
245
C#
using System; using System.Linq; using System.Xml.Linq; using AutoFixture; using NUnit.Framework; namespace Dfe.Spi.UkrlpAdapter.Infrastructure.UkrlpSoapApi.UnitTests { public class WhenBuildingMessageToGetUpdatesSince { private static readonly XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; private static readonly XNamespace ukrlpNs = "http://ukrlp.co.uk.server.ws.v3"; private string _stakeholderId; private DateTime _updatedSince; private UkrlpSoapMessageBuilder _builder; [SetUp] public void Arrange() { var fixture = new Fixture(); _stakeholderId = fixture.Create<string>(); _updatedSince = fixture.Create<DateTime>(); _builder = new UkrlpSoapMessageBuilder(_stakeholderId); } [Test] public void ThenItShouldReturnSoapMesage() { var actual = _builder.BuildMessageToGetUpdatesSince(_updatedSince); var envelope = XElement.Parse(actual); Assert.AreEqual("Envelope", envelope.Name.LocalName); Assert.AreEqual(soapNs.NamespaceName, envelope.Name.NamespaceName); Assert.IsNotNull(envelope.Elements().SingleOrDefault(e => e.Name.LocalName == "Header" && e.Name.NamespaceName == soapNs.NamespaceName)); Assert.IsNotNull(envelope.Elements().SingleOrDefault(e => e.Name.LocalName == "Body" && e.Name.NamespaceName == soapNs.NamespaceName)); } [Test] public void ThenItShouldHaveAProviderQueryRequestInTheSoapBody() { var actual = _builder.BuildMessageToGetUpdatesSince(_updatedSince); var body = XElement.Parse(actual).GetElementByLocalName("Body"); Assert.IsNotNull(body.Elements().SingleOrDefault(e => e.Name.LocalName == "ProviderQueryRequest" && e.Name.NamespaceName == ukrlpNs.NamespaceName)); } [Test] public void ThenItShouldHaveAQueryIdInRequest() { var actual = _builder.BuildMessageToGetUpdatesSince(_updatedSince); var request = XElement.Parse(actual).GetElementByLocalName("Body").GetElementByLocalName("ProviderQueryRequest"); var queryId = request.GetElementByLocalName("QueryId"); Assert.IsNotNull(queryId); } [Test] public void ThenItShouldHaveAStakeholderIdInSelectionCriteria() { var actual = _builder.BuildMessageToGetUpdatesSince(_updatedSince); var selectionCriteria = XElement.Parse(actual) .GetElementByLocalName("Body") .GetElementByLocalName("ProviderQueryRequest") .GetElementByLocalName("SelectionCriteria"); var stakeholderId = selectionCriteria.GetElementByLocalName("StakeholderId"); Assert.IsNotNull(stakeholderId); Assert.AreEqual(_stakeholderId, stakeholderId.Value); } [Test] public void ThenItShouldHaveASelectionCriteriaForProviderUpdatedSince() { var actual = _builder.BuildMessageToGetUpdatesSince(_updatedSince); var selectionCriteria = XElement.Parse(actual) .GetElementByLocalName("Body") .GetElementByLocalName("ProviderQueryRequest") .GetElementByLocalName("SelectionCriteria"); var expectedUpdatedSinceFormatted = _updatedSince.ToUniversalTime().ToString("O"); var providerUpdatedSince = selectionCriteria.GetElementByLocalName("ProviderUpdatedSince"); Assert.IsNotNull(providerUpdatedSince); Assert.AreEqual(expectedUpdatedSinceFormatted, providerUpdatedSince.Value); } } }
39.489583
125
0.658401
[ "MIT" ]
DFE-Digital/spi-ukrlp-adapter
src/Dfe.Spi.UkrlpAdapter.Infrastructure.UkrlpSoapApi.UnitTests/WhenBuildingMessageToGetUpdatesSince.cs
3,791
C#
/******************************************************** * ADO.NET 2.0 Data Provider for SQLite Version 3.X * Written by Robert Simpson (robert@blackcastlesoft.com) * * Released to the public domain, use at your own risk! ********************************************************/ namespace Mono.Data.Sqlite { using System; using System.Data; using System.Data.Common; /// <summary> /// SQLite implementation of DbTransaction. /// </summary> public sealed class SqliteTransaction : DbTransaction { /// <summary> /// The connection to which this transaction is bound /// </summary> internal SqliteConnection _cnn; internal long _version; // Matches the version of the connection private IsolationLevel _level; /// <summary> /// Constructs the transaction object, binding it to the supplied connection /// </summary> /// <param name="connection">The connection to open a transaction on</param> /// <param name="deferredLock">TRUE to defer the writelock, or FALSE to lock immediately</param> internal SqliteTransaction(SqliteConnection connection, bool deferredLock) { _cnn = connection; _version = _cnn._version; _level = (deferredLock == true) ? IsolationLevel.ReadCommitted : IsolationLevel.Serializable; if (_cnn._transactionLevel++ == 0) { try { using (SqliteCommand cmd = _cnn.CreateCommand()) { if (!deferredLock) cmd.CommandText = "BEGIN IMMEDIATE"; else cmd.CommandText = "BEGIN"; cmd.ExecuteNonQuery(); } } catch (SqliteException) { _cnn._transactionLevel--; _cnn = null; throw; } } } /// <summary> /// Commits the current transaction. /// </summary> public override void Commit() { IsValid(true); if (_cnn._transactionLevel - 1 == 0) { using (SqliteCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = "COMMIT"; cmd.ExecuteNonQuery(); } } _cnn._transactionLevel--; _cnn = null; } /// <summary> /// Returns the underlying connection to which this transaction applies. /// </summary> public new SqliteConnection Connection { get { return _cnn; } } /// <summary> /// Forwards to the local Connection property /// </summary> protected override DbConnection DbConnection { get { return Connection; } } /// <summary> /// Disposes the transaction. If it is currently active, any changes are rolled back. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { lock (this) { if (IsValid(false)) Rollback(); _cnn = null; } } base.Dispose(disposing); } /// <summary> /// Gets the isolation level of the transaction. SQLite only supports Serializable transactions. /// </summary> public override IsolationLevel IsolationLevel { get { return _level; } } /// <summary> /// Rolls back the active transaction. /// </summary> public override void Rollback() { IsValid(true); IssueRollback(_cnn); _cnn._transactionLevel = 0; _cnn = null; } internal static void IssueRollback(SqliteConnection cnn) { using (SqliteCommand cmd = cnn.CreateCommand()) { cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); } } internal bool IsValid(bool throwError) { if (_cnn == null) { if (throwError == true) throw new ArgumentNullException("No connection associated with this transaction"); else return false; } if (_cnn._transactionLevel == 0) { if (throwError == true) throw new SqliteException((int)SQLiteErrorCode.Misuse, "No transaction is active on this connection"); else return false; } if (_cnn._version != _version) { if (throwError == true) throw new SqliteException((int)SQLiteErrorCode.Misuse, "The connection was closed and re-opened, changes were rolled back"); else return false; } if (_cnn.State != ConnectionState.Open) { if (throwError == true) throw new SqliteException((int)SQLiteErrorCode.Misuse, "Connection was closed"); else return false; } return true; } } }
27.418605
157
0.560645
[ "Apache-2.0" ]
121468615/mono
mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0/SQLiteTransaction.cs
4,718
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UrlSettings" company=""> // // </copyright> // <summary> // The class UrlSettings. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace SingleSignOn.AdminApi { #region Usings using System; #endregion /// <summary> /// The Config. /// </summary> public class UrlSettings { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Config"/> class. /// </summary> public UrlSettings() { } #endregion #region Public Properties public string Authority { get; set; } public string CorsUrl { get; set; } #endregion #region Public Methods And Operators #endregion #region Other Methods #endregion } }
21
119
0.425714
[ "MIT" ]
laredoza/SingleSignOnApi
src/AdminApi/V1/UrlSettings.cs
1,050
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.ServiceModel.Channels; using System.Text; using System.Threading.Tasks; namespace AMQPBizTalkAdapter { class AmqpNetLitePollingReceiver : AmqpNetLiteReceiver, IReceiver { readonly Object ObjectLocker; readonly Encoding messageEncoding; readonly Uri connectionUri; readonly int msgPollingLot; private DateTime nextTimeToExecute = DateTime.UtcNow; private int executeIntervalInSeconds; private bool closed = false; public AmqpNetLitePollingReceiver(AMQPBizTalkAdapterConnection connection, QueueTypeEnum queueType, string queue, string keyRouting, string subscriptionId, MethodTracer methodTracer, Encoding encoding, int lot, int intervalInSeconds) : base(connection, queueType, queue, subscriptionId) { this.executeIntervalInSeconds = intervalInSeconds; this.ObjectLocker = new object(); this.messageEncoding = encoding; this.connectionUri = connection.ConnectionUri.Uri; this.msgPollingLot = lot; } public void StartListener(TimeSpan timeout, MethodTracer methodTracer) { lock (ObjectLocker) { try { methodTracer.TraceData(System.Diagnostics.TraceEventType.Verbose, string.Format("Start listening uri= {0}", this.connectionUri)); this.Start(timeout,methodTracer); } catch (Exception exception) { methodTracer.TraceData(TraceEventType.Error, "Error in RabbitMQConsumerBase.StartListener"); methodTracer.TraceException(exception); throw; } } } public void StopListener(TimeSpan timeout, MethodTracer methodTracer) { methodTracer.TraceData(System.Diagnostics.TraceEventType.Verbose, string.Format("Stop listening uri= {0}", this.connectionUri)); this.Stop(timeout, methodTracer); } public bool TryReceive(TimeSpan timeout, MethodTracer methodTracer, out System.ServiceModel.Channels.Message wcfMessage) { bool result = false; TimeOutHelper timeHelper = new TimeOutHelper(timeout); while (true) { lock (ObjectLocker) { if (timeHelper.IsExpired || this.closed) { methodTracer.TraceReturn(false); result = false; methodTracer.TraceData(System.Diagnostics.TraceEventType.Verbose, "timeHelper.IsExpired "); wcfMessage = null; break; } if (DateTime.UtcNow >= this.nextTimeToExecute) { try { if (this.IsAvailablesMessages) { List<Amqp.Message> eMsgs = this.DequeueMessages(msgPollingLot); List<ReceiveMessage> messages = new List<ReceiveMessage>(); foreach (var e in eMsgs) { ReceiveMessage wso2Message = Helpers.Helper.GetReceiveMessage(e, methodTracer, this.messageEncoding, "GenNewGUID"); if (wso2Message != null) { messages.Add(wso2Message); } } wcfMessage = Helpers.Helper.CreateWcfMessage(messages, this.connectionUri); result = true; this.nextTimeToExecute = this.nextTimeToExecute.AddSeconds((double)this.executeIntervalInSeconds); //Send Ack to amqp MB this.AckDelivery(eMsgs); methodTracer.TraceReturn(true); break; } else { methodTracer.TraceData(System.Diagnostics.TraceEventType.Verbose, string.Format("No message available nextTimeToExecute={0}", this.nextTimeToExecute.ToLongTimeString())); while (DateTime.UtcNow >= this.nextTimeToExecute) { this.nextTimeToExecute = this.nextTimeToExecute.AddSeconds((double)this.executeIntervalInSeconds); } result = false; wcfMessage = null; } } catch (Exception ex) { methodTracer.TraceException(ex); while (this.nextTimeToExecute <= DateTime.UtcNow) { this.nextTimeToExecute = this.nextTimeToExecute.AddSeconds((double)this.executeIntervalInSeconds); } throw; } } } System.Threading.Thread.Sleep(1000); } return result; } public bool WaitForMessage(TimeSpan timeout, MethodTracer methodTracer) { return this.IsAvailablesMessages; } } }
41.104895
202
0.495407
[ "MIT" ]
AbdelazizElbaz/AMQPBizTalkAdapter
src/AMQPBizTalkAdapter/Messaging/AmqpNetLite/AmqpNetLitepollingReceiver.cs
5,880
C#
using System.IO; using Calamari.Common.Plumbing.FileSystem; using Calamari.Common.Plumbing.Variables; using Calamari.Deployment; using Calamari.Tests.Fixtures.Deployment.Packages; using Calamari.Tests.Helpers; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Deployment { [TestFixture] [Category(TestCategory.CompatibleOS.OnlyWindows)] public class DeployVhdFixture : DeployPackageFixture { private const string ServiceName = "Acme.Vhd"; private const string Environment = "Production"; [SetUp] public override void SetUp() { base.SetUp(); } [TearDown] public override void CleanUp() { base.CleanUp(); } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldDeployAVhd() { Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles}, {KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\ApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\ApplicationPath\\web\.config' using '[A-Z]:\\ApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\ApplicationPath\\\\appsettings.json with format Json"); } } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldDeployAVhdWithTwoPartitions() { Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles}, {KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; Variables["OctopusVhdPartitions[1].ApplicationPath"] = "PathThatDoesNotExist"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName, twoPartitions: true))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); result.AssertOutput($"VHD partition 1 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // handles additionalpaths setting not being valid for all partitions result.AssertOutputMatches(@"[A-Z]:\\PathThatDoesNotExist not found so not added to Calamari processing paths"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 0 is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 1 is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\ApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\ApplicationPath\\web\.config' using '[A-Z]:\\ApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\ApplicationPath\\\\appsettings.json with format Json"); } } [Test] [RequiresAdmin] [RequiresWindowsServer2012OrAbove] public void ShouldBlockMountAndOverrideAppPath() { Variables[KnownVariables.Package.EnabledFeatures] = "Octopus.Features.Vhd,Octopus.Features.ConfigurationTransforms"; Variables[SpecialVariables.Vhd.ApplicationPath] = "ApplicationPath"; Variables["foo"] = "bar"; Variables[PackageVariables.SubstituteInFilesTargets] = "web.config"; Variables[KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles] = "True"; Variables[DeploymentEnvironment.Name] = Environment; Variables[ActionVariables.StructuredConfigurationVariablesTargets] = "appsettings.json"; Variables[KnownVariables.Package.EnabledFeatures] = $"{KnownVariables.Features.StructuredConfigurationVariables},{KnownVariables.Features.SubstituteInFiles},{KnownVariables.Features.ConfigurationTransforms},Octopus.Features.Vhd"; Variables["OctopusVhdPartitions[0].Mount"] = "false"; Variables["OctopusVhdPartitions[1].ApplicationPath"] = "AlternateApplicationPath"; using (var vhd = new TemporaryFile(VhdBuilder.BuildSampleVhd(ServiceName, twoPartitions: true))) using (var file = new TemporaryFile(PackageBuilder.BuildSimpleZip(ServiceName, "1.0.0", Path.GetDirectoryName(vhd.FilePath)))) { var result = DeployPackage(file.FilePath); result.AssertSuccess(); result.AssertOutput("Extracting package to: " + Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0")); result.AssertOutput("Extracted 2 files"); // mounts VHD result.AssertNoOutput($"VHD partition 0 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); result.AssertOutput($"VHD partition 1 from {Path.Combine(StagingDirectory, Environment, ServiceName, "1.0.0", ServiceName + ".vhdx")} mounted to"); // runs predeploy etc result.AssertOutput("Bonjour from PreDeploy.ps1"); // can access mountpoint from predeploy result.AssertOutputMatches(@"VHD is mounted at [A-Z]:\\"); result.AssertNoOutputMatches(@"VHD partition 0 is mounted at [A-Z]:\\"); result.AssertOutputMatches(@"VHD partition 1 is mounted at [A-Z]:\\"); // variable substitution in files result.AssertOutputMatches(@"Performing variable substitution on '[A-Z]:\\AlternateApplicationPath\\web\.config'"); // config transforms result.AssertOutputMatches(@"Transforming '[A-Z]:\\AlternateApplicationPath\\web\.config' using '[A-Z]:\\AlternateApplicationPath\\web\.Production\.config'"); // json substitutions result.AssertOutputMatches("Structured variable replacement succeeded on file [A-Z]:\\\\AlternateApplicationPath\\\\appsettings.json with format Json"); } } } }
54.319767
242
0.656962
[ "Apache-2.0" ]
OctopusDeploy/Calamari
source/Calamari.Tests/Fixtures/Deployment/DeployVhdFixture.cs
9,343
C#
using System.Runtime.Serialization; namespace EncompassRest.Loans.Enums { public enum ATRQMStatus { [EnumMember(Value = "Meets Standard")] MeetsStandard = 0, [EnumMember(Value = "Not Meet")] NotMeet = 1, [EnumMember(Value = "Review Needed")] ReviewNeeded = 2 } }
23.071429
46
0.606811
[ "MIT" ]
gashach/EncompassRest
src/EncompassRest/Loans/Enums/ATRQMStatus.cs
323
C#
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Aurora.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace Aurora.Framework { public interface IGroupsServicesConnector { UUID CreateGroup(UUID RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID); void UpdateGroup(UUID RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish); GroupRecord GetGroupRecord(UUID RequestingAgentID, UUID GroupID, string GroupName); GroupProfileData GetGroupProfile(UUID RequestingAgentID, UUID GroupID); List<DirGroupsReplyData> FindGroups(UUID RequestingAgentID, string search, uint? start, uint? count, uint queryFlags); List<GroupMembersData> GetGroupMembers(UUID RequestingAgentID, UUID GroupID); void AddGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers); void UpdateGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers); void RemoveGroupRole(UUID RequestingAgentID, UUID groupID, UUID roleID); List<GroupRolesData> GetGroupRoles(UUID RequestingAgentID, UUID GroupID); List<GroupRoleMembersData> GetGroupRoleMembers(UUID RequestingAgentID, UUID GroupID); void AddAgentToGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID); bool RemoveAgentFromGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID); void AddAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentIDFromAgentName, string FromAgentName); GroupInviteInfo GetAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID); void RemoveAgentToGroupInvite(UUID RequestingAgentID, UUID inviteID); void AddAgentToGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID); void RemoveAgentFromGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID); List<GroupRolesData> GetAgentGroupRoles(UUID RequestingAgentID, UUID AgentID, UUID GroupID); string SetAgentActiveGroup(UUID RequestingAgentID, UUID AgentID, UUID GroupID); GroupMembershipData GetAgentActiveMembership(UUID RequestingAgentID, UUID AgentID); string SetAgentActiveGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID); void SetAgentGroupInfo(UUID RequestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile); GroupMembershipData GetAgentGroupMembership(UUID RequestingAgentID, UUID AgentID, UUID GroupID); List<GroupMembershipData> GetAgentGroupMemberships(UUID RequestingAgentID, UUID AgentID); void AddGroupNotice(UUID RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, UUID ItemID, int AssetType, string ItemName); GroupNoticeInfo GetGroupNotice(UUID RequestingAgentID, UUID noticeID); List<GroupNoticeData> GetGroupNotices(UUID RequestingAgentID, UUID GroupID); List<GroupInviteInfo> GetGroupInvites(UUID requestingAgentID); void AddGroupProposal(UUID agentID, GroupProposalInfo info); bool CreateSession(ChatSession chatSession); void AddMemberToGroup(ChatSessionMember chatSessionMember, UUID GroupID); ChatSession GetSession(UUID sessionid); ChatSessionMember FindMember(UUID sessionid, UUID Agent); void RemoveSession(UUID sessionid); List<GroupTitlesData> GetGroupTitles(UUID agentID, UUID groupID); List<GroupProposalInfo> GetActiveProposals(UUID agentID, UUID groupID); List<GroupProposalInfo> GetInactiveProposals(UUID agentID, UUID groupID); void VoteOnActiveProposals(UUID agentID, UUID groupID, UUID proposalID, string vote); } /// <summary> /// Internal class for chat sessions /// </summary> public class ChatSession { public List<ChatSessionMember> Members; public string Name; public UUID SessionID; } //Pulled from OpenMetaverse // Summary: // Struct representing a member of a group chat session and their settings public class ChatSessionMember { // Summary: // The OpenMetaverse.UUID of the Avatar public UUID AvatarKey; // // Summary: // True if user has voice chat enabled public bool CanVoiceChat; public bool HasBeenAdded; // // Summary: // True of Avatar has moderator abilities public bool IsModerator; // // Summary: // True if a moderator has muted this avatars chat public bool MuteText; // // Summary: // True if a moderator has muted this avatars voice public bool MuteVoice; // // Summary: // True if they have been requested to join the session } public class GroupInviteInfo : IDataTransferable { public UUID AgentID = UUID.Zero; public string FromAgentName = ""; public UUID GroupID = UUID.Zero; public UUID InviteID = UUID.Zero; public UUID RoleID = UUID.Zero; public GroupInviteInfo() { } public GroupInviteInfo(Dictionary<string, object> values) { FromKVP(values); } public override Dictionary<string, object> ToKVP() { Dictionary<string, object> values = new Dictionary<string, object>(); values["GroupID"] = GroupID; values["RoleID"] = RoleID; values["AgentID"] = AgentID; values["InviteID"] = InviteID; values["FromAgentName"] = FromAgentName; return values; } public override void FromKVP(Dictionary<string, object> values) { GroupID = UUID.Parse(values["GroupID"].ToString()); RoleID = UUID.Parse(values["RoleID"].ToString()); AgentID = UUID.Parse(values["AgentID"].ToString()); InviteID = UUID.Parse(values["InviteID"].ToString()); FromAgentName = values["FromAgentName"].ToString(); } public override OSDMap ToOSD() { OSDMap values = new OSDMap(); values["GroupID"] = GroupID; values["RoleID"] = RoleID; values["AgentID"] = AgentID; values["InviteID"] = InviteID; values["FromAgentName"] = FromAgentName; return values; } public override void FromOSD(OSDMap values) { GroupID = values["GroupID"]; RoleID = values["RoleID"]; AgentID = values["AgentID"]; InviteID = values["InviteID"]; FromAgentName = values["FromAgentName"]; } } public class GroupNoticeInfo : IDataTransferable { public byte[] BinaryBucket = new byte[0]; public UUID GroupID = UUID.Zero; public string Message = string.Empty; public GroupNoticeData noticeData = new GroupNoticeData(); public GroupNoticeInfo() { } public GroupNoticeInfo(Dictionary<string, object> values) { FromKVP(values); } public override void FromKVP(Dictionary<string, object> values) { noticeData = new GroupNoticeData(values["noticeData"] as Dictionary<string, object>); GroupID = UUID.Parse(values["GroupID"].ToString()); Message = values["Message"].ToString(); BinaryBucket = Utils.HexStringToBytes(values["BinaryBucket"].ToString(), true); } public override Dictionary<string, object> ToKVP() { Dictionary<string, object> values = new Dictionary<string, object>(); values["noticeData"] = noticeData.ToKVP(); values["GroupID"] = GroupID; values["Message"] = Message; values["BinaryBucket"] = Utils.BytesToHexString(BinaryBucket, "BinaryBucket"); return values; } public override OSDMap ToOSD() { OSDMap values = new OSDMap(); values["noticeData"] = noticeData.ToOSD(); values["GroupID"] = GroupID; values["Message"] = Message; values["BinaryBucket"] = BinaryBucket; return values; } public override void FromOSD(OSDMap values) { noticeData = new GroupNoticeData(); noticeData.FromOSD((OSDMap)values["noticeData"]); GroupID = values["GroupID"]; Message = values["Message"]; BinaryBucket = values["BinaryBucket"]; } } public class GroupProposalInfo : IDataTransferable { public int Duration; public UUID GroupID = UUID.Zero; public float Majority; public int Quorum; public UUID Session = UUID.Zero; public string Text = string.Empty; public UUID BallotInitiator = UUID.Zero; public DateTime Created = DateTime.Now; public DateTime Ending = DateTime.Now; public UUID VoteID = UUID.Random(); /// <summary> /// Only set when a user is calling to find out proposal info, it is what said user voted /// </summary> public string VoteCast = ""; /// <summary> /// The result of the proposal (success or failure) /// </summary> public bool Result = false; /// <summary> /// The number of votes cast (so far if the proposal is still open) /// </summary> public int NumVotes = 0; /// <summary> /// If this is false, the result of the proposal has not been calculated and should be when it is retrieved next /// </summary> public bool HasCalculatedResult = false; public override void FromOSD(OSDMap map) { GroupID = map["GroupID"].AsUUID(); Duration = map["Duration"].AsInteger(); Majority = (float) map["Majority"].AsReal(); Text = map["Text"].AsString(); Quorum = map["Quorum"].AsInteger(); Session = map["Session"].AsUUID(); BallotInitiator = map["BallotInitiator"]; Created = map["Created"]; Ending = map["Ending"]; VoteID = map["VoteID"]; VoteCast = map["VoteCast"]; Result = map["Result"]; NumVotes = map["NumVotes"]; HasCalculatedResult = map["HasCalculatedResult"]; } public override OSDMap ToOSD() { OSDMap map = new OSDMap(); map["GroupID"] = GroupID; map["Duration"] = Duration; map["Majority"] = Majority; map["Text"] = Text; map["Quorum"] = Quorum; map["Session"] = Session; map["BallotInitiator"] = BallotInitiator; map["Created"] = Created; map["Ending"] = Ending; map["VoteID"] = VoteID; map["VoteCast"] = VoteCast; map["Result"] = Result; map["NumVotes"] = NumVotes; map["HasCalculatedResult"] = HasCalculatedResult; return map; } public override void FromKVP(Dictionary<string, object> KVP) { FromOSD(Util.DictionaryToOSD(KVP)); } public override Dictionary<string, object> ToKVP() { return Util.OSDToDictionary(ToOSD()); } } }
41.513353
127
0.618585
[ "BSD-3-Clause" ]
BillyWarrhol/Aurora-Sim
Aurora/Framework/Services/IGroupsServicesConnector.cs
13,990
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.InteractiveWindow.Commands { /// <summary> /// Creates an <see cref="IInteractiveWindowCommands"/> which handles updating the context type for the command type, /// classification of commands, and execution of commands. /// </summary> /// <remarks> /// Engines need to use this interface to respond to checks if code can be executed and to /// execute text when in a command mode. /// /// The commands that are available for this interactive window are provided at creation time /// along with the prefix which commands should be prefaced with. /// </remarks> public interface IInteractiveWindowCommandsFactory { /// <summary> /// Creates the IInteractiveCommands instance. /// </summary> IInteractiveWindowCommands CreateInteractiveCommands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands); } }
41.333333
161
0.724194
[ "Apache-2.0" ]
0x53A/roslyn
src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommandsFactory.cs
1,242
C#
using RelhaxModpack.Database; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RelhaxModpack.Automation.Tasks { public class CreateDirectoryTask : DirectoryTask, IXmlSerializable { public const string TaskCommandName = "create_directory"; public override string Command { get { return TaskCommandName; } } #region Task execution public override void ValidateCommands() { //don't run the base because it will check to make sure the directory exists, which we know it doesn't if (ValidateCommandStringNullEmptyTrue(nameof(DirectoryPath), DirectoryPath)) return; } public async override Task RunTask() { Logging.Debug("Creating directory {0}", DirectoryPath); if (Directory.Exists(DirectoryPath)) Logging.Debug("Directory path already exists"); else Directory.CreateDirectory(DirectoryPath); } public override void ProcessTaskResults() { if (ProcessTaskResultFalse(Directory.Exists(DirectoryPath), "The directory path does not exist")) return; } #endregion } }
30.488372
114
0.646834
[ "Apache-2.0" ]
SigmaTel71/RelhaxModpack
RelhaxModpack/RelhaxModpack/Automation/Tasks/CreateDirectoryTask.cs
1,313
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; namespace Microsoft.AspNetCore.Rewrite; internal static class RedirectToWwwHelper { private const string Localhost = "localhost"; public static bool IsHostInDomains(HttpRequest request, string[]? domains) { if (request.Host.Host.Equals(Localhost, StringComparison.OrdinalIgnoreCase)) { return false; } if (domains != null) { var isHostInDomains = false; foreach (var domain in domains) { if (domain.Equals(request.Host.Host, StringComparison.OrdinalIgnoreCase)) { isHostInDomains = true; break; } } if (!isHostInDomains) { return false; } } return true; } public static void SetRedirect(RewriteContext context, HostString newHost, int statusCode) { var request = context.HttpContext.Request; var response = context.HttpContext.Response; var newUrl = UriHelper.BuildAbsolute( request.Scheme, newHost, request.PathBase, request.Path, request.QueryString); response.StatusCode = statusCode; response.Headers.Location = newUrl; context.Result = RuleResult.EndResponse; } }
26.881356
94
0.592055
[ "MIT" ]
3ejki/aspnetcore
src/Middleware/Rewrite/src/RedirectToWwwHelper.cs
1,586
C#
using System.Collections.Generic; using System.Web; using Newtonsoft.Json; namespace AirtableApiClient { public enum SortDirection { Asc, Desc } public class Sort { [JsonProperty("fields")] public string Field { get; set; } [JsonProperty("direction")] public SortDirection Direction { get; set; } } public class Fields { [JsonProperty("fields")] public Dictionary<string, object> FieldsCollection { get; set; } = new Dictionary<string, object>(); public void AddField(string fieldName, object fieldValue) { FieldsCollection.Add(fieldName, fieldValue); } } public class IdFields : Fields { public IdFields(string id) { this.id = id; } [JsonProperty("id")] public string id; } internal class QueryParamHelper { static internal string FlattenSortParam( IEnumerable<Sort> sort) { int i = 0; string flattenSortParam = string.Empty; string toInsert = string.Empty; foreach (var sortItem in sort) { if (string.IsNullOrEmpty(toInsert) && i > 0) { toInsert = "&"; } // Name of fields to be sorted string param = $"sort[{i}][field]"; flattenSortParam += $"{toInsert}{HttpUtility.UrlEncode(param)}={HttpUtility.UrlEncode(sortItem.Field)}"; // Direction for sorting param = $"sort[{i}][direction]"; flattenSortParam += $"&{HttpUtility.UrlEncode(param)}={HttpUtility.UrlEncode(sortItem.Direction.ToString().ToLower())}"; i++; } return flattenSortParam; } static internal string FlattenFieldsParam( IEnumerable<string> fields) { int i = 0; string flattenFieldsParam = string.Empty; string toInsert = string.Empty; foreach (var fieldName in fields) { if (string.IsNullOrEmpty(toInsert) && i > 0) { toInsert = "&"; } string param = "fields[]"; flattenFieldsParam += $"{toInsert}{HttpUtility.UrlEncode(param)}={HttpUtility.UrlEncode(fieldName)}"; i++; } return flattenFieldsParam; } } // end class } // end namespace
26.141414
136
0.514683
[ "MIT" ]
DJCodeMonkey/airtable.net
AirtableApiClient/QueryParamHelper.cs
2,590
C#
namespace SimpleShop.Data { public class DataSettings { public const string ConnectionString = @"Server=.\SQLEXPRESS;Database=SimpleShop;Trusted_Connection=True"; } }
22.222222
81
0.675
[ "MIT" ]
kalintsenkov/SimpleShopConsoleApp
Data/SimpleShop.Data/DataSettings.cs
202
C#
using System; using System.Linq; using System.Management.Automation; using PnP.PowerShell.Commands.Attributes; using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using PnP.PowerShell.Commands.Model; namespace PnP.PowerShell.Commands.Apps { [Cmdlet(VerbsSecurity.Grant, "PnPAzureADAppSitePermission")] [RequiredMinimalApiPermissions("Sites.FullControl.All")] public class GrantPnPAzureADAppSitePermission : PnPGraphCmdlet { [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public Guid AppId; [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public string DisplayName; [Parameter(Mandatory = false)] public SitePipeBind Site; [Parameter(Mandatory = true)] [ValidateSet("Write", "Read")] public string[] Permissions; protected override void ExecuteCmdlet() { Guid siteId = Guid.Empty; if (ParameterSpecified(nameof(Site))) { siteId = Site.GetSiteIdThroughGraph(HttpClient, AccessToken); } else { siteId = PnPContext.Site.Id; } if (siteId != Guid.Empty) { var payload = new { roles = Permissions.Select(p => p.ToLower()).ToArray(), grantedToIdentities = new[] { new { application = new { id = AppId.ToString(), displayName = DisplayName } } } }; var results = PnP.PowerShell.Commands.Utilities.REST.RestHelper.PostAsync<AzureADAppPermissionInternal>(HttpClient, $"https://graph.microsoft.com/v1.0/sites/{siteId}/permissions", AccessToken, payload).GetAwaiter().GetResult(); WriteObject(results.Convert()); } } } }
32.515625
243
0.54493
[ "MIT" ]
ToddKlindt/powershell-1
src/Commands/Apps/GrantAzureADAppSitePermission.cs
2,081
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20180601 { /// <summary> /// Express Route Circuit Connection in an ExpressRouteCircuitPeering resource. /// </summary> public partial class ExpressRouteCircuitConnection : Pulumi.CustomResource { /// <summary> /// /29 IP address space to carve out Customer addresses for tunnels. /// </summary> [Output("addressPrefix")] public Output<string?> AddressPrefix { get; private set; } = null!; /// <summary> /// The authorization key. /// </summary> [Output("authorizationKey")] public Output<string?> AuthorizationKey { get; private set; } = null!; /// <summary> /// Express Route Circuit Connection State. Possible values are: 'Connected' and 'Disconnected'. /// </summary> [Output("circuitConnectionStatus")] public Output<string> CircuitConnectionStatus { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. /// </summary> [Output("expressRouteCircuitPeering")] public Output<Outputs.SubResourceResponse?> ExpressRouteCircuitPeering { get; private set; } = null!; /// <summary> /// Gets name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Output("name")] public Output<string?> Name { get; private set; } = null!; /// <summary> /// Reference to Express Route Circuit Private Peering Resource of the peered circuit. /// </summary> [Output("peerExpressRouteCircuitPeering")] public Output<Outputs.SubResourceResponse?> PeerExpressRouteCircuitPeering { get; private set; } = null!; /// <summary> /// Provisioning state of the circuit connection resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Create a ExpressRouteCircuitConnection resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ExpressRouteCircuitConnection(string name, ExpressRouteCircuitConnectionArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20180601:ExpressRouteCircuitConnection", name, args ?? new ExpressRouteCircuitConnectionArgs(), MakeResourceOptions(options, "")) { } private ExpressRouteCircuitConnection(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20180601:ExpressRouteCircuitConnection", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/latest:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteCircuitConnection"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteCircuitConnection"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ExpressRouteCircuitConnection resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ExpressRouteCircuitConnection Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ExpressRouteCircuitConnection(name, id, options); } } public sealed class ExpressRouteCircuitConnectionArgs : Pulumi.ResourceArgs { /// <summary> /// /29 IP address space to carve out Customer addresses for tunnels. /// </summary> [Input("addressPrefix")] public Input<string>? AddressPrefix { get; set; } /// <summary> /// The authorization key. /// </summary> [Input("authorizationKey")] public Input<string>? AuthorizationKey { get; set; } /// <summary> /// The name of the express route circuit. /// </summary> [Input("circuitName", required: true)] public Input<string> CircuitName { get; set; } = null!; /// <summary> /// The name of the express route circuit connection. /// </summary> [Input("connectionName", required: true)] public Input<string> ConnectionName { get; set; } = null!; /// <summary> /// Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. /// </summary> [Input("expressRouteCircuitPeering")] public Input<Inputs.SubResourceArgs>? ExpressRouteCircuitPeering { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Gets name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Reference to Express Route Circuit Private Peering Resource of the peered circuit. /// </summary> [Input("peerExpressRouteCircuitPeering")] public Input<Inputs.SubResourceArgs>? PeerExpressRouteCircuitPeering { get; set; } /// <summary> /// The name of the peering. /// </summary> [Input("peeringName", required: true)] public Input<string> PeeringName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public ExpressRouteCircuitConnectionArgs() { } } }
48.728643
172
0.630917
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20180601/ExpressRouteCircuitConnection.cs
9,697
C#
namespace DigitalLearningSolutions.Data.Services { using System; using System.Collections.Generic; using System.IO; using System.Linq; using ClosedXML.Excel; using DigitalLearningSolutions.Data.DataServices; using DigitalLearningSolutions.Data.Enums; using DigitalLearningSolutions.Data.Helpers; using DigitalLearningSolutions.Data.Models.TrackingSystem; public interface IActivityService { IEnumerable<PeriodOfActivity> GetFilteredActivity(int centreId, ActivityFilterData filterData); (string jobGroupName, string courseCategoryName, string courseName) GetFilterNames( ActivityFilterData filterData ); ReportsFilterOptions GetFilterOptions(int centreId, int? courseCategoryId); DateTime GetStartOfActivityForCentre(int centreId); byte[] GetActivityDataFileForCentre(int centreId, ActivityFilterData filterData); (DateTime startDate, DateTime? endDate)? GetValidatedUsageStatsDateRange( string startDateString, string endDateString, int centreId ); } public class ActivityService : IActivityService { private const string SheetName = "Usage Statistics"; private static readonly XLTableTheme TableTheme = XLTableTheme.TableStyleLight9; private readonly IActivityDataService activityDataService; private readonly ICourseCategoriesDataService courseCategoriesDataService; private readonly ICourseDataService courseDataService; private readonly IJobGroupsDataService jobGroupsDataService; public ActivityService( IActivityDataService activityDataService, IJobGroupsDataService jobGroupsDataService, ICourseCategoriesDataService courseCategoriesDataService, ICourseDataService courseDataService ) { this.activityDataService = activityDataService; this.jobGroupsDataService = jobGroupsDataService; this.courseCategoriesDataService = courseCategoriesDataService; this.courseDataService = courseDataService; } public IEnumerable<PeriodOfActivity> GetFilteredActivity(int centreId, ActivityFilterData filterData) { var activityData = activityDataService .GetFilteredActivity( centreId, filterData.StartDate, filterData.EndDate, filterData.JobGroupId, filterData.CourseCategoryId, filterData.CustomisationId ) .OrderBy(x => x.LogDate); var dataByPeriod = GroupActivityData(activityData, filterData.ReportInterval); var dateSlots = DateHelper.GetPeriodsBetweenDates( filterData.StartDate, filterData.EndDate ?? DateTime.UtcNow, filterData.ReportInterval ); return dateSlots.Select( slot => { var dateInformation = new DateInformation(slot, filterData.ReportInterval); var periodData = dataByPeriod.SingleOrDefault( data => data.DateInformation.Date == slot.Date ); return new PeriodOfActivity(dateInformation, periodData); } ); } public (string jobGroupName, string courseCategoryName, string courseName) GetFilterNames( ActivityFilterData filterData ) { return (GetJobGroupNameForActivityFilter(filterData.JobGroupId), GetCourseCategoryNameForActivityFilter(filterData.CourseCategoryId), GetCourseNameForActivityFilter(filterData.CustomisationId)); } public ReportsFilterOptions GetFilterOptions(int centreId, int? courseCategoryId) { var jobGroups = jobGroupsDataService.GetJobGroupsAlphabetical(); var courseCategories = courseCategoriesDataService .GetCategoriesForCentreAndCentrallyManagedCourses(centreId) .Select(cc => (cc.CourseCategoryID, cc.CategoryName)); var courses = courseDataService .GetCentrallyManagedAndCentreCourses(centreId, courseCategoryId) .OrderBy(c => c.CourseName) .Select(c => (c.CustomisationId, c.CourseName)); return new ReportsFilterOptions(jobGroups, courseCategories, courses); } public DateTime GetStartOfActivityForCentre(int centreId) { return activityDataService.GetStartOfActivityForCentre(centreId); } public byte[] GetActivityDataFileForCentre(int centreId, ActivityFilterData filterData) { using var workbook = new XLWorkbook(); var activityData = GetFilteredActivity(centreId, filterData).Select( p => new { Period = p.DateInformation.Date, p.Registrations, p.Completions, p.Evaluations } ); var sheet = workbook.Worksheets.Add(SheetName); var table = sheet.Cell(1, 1).InsertTable(activityData); table.Theme = TableTheme; sheet.Columns().AdjustToContents(); using var stream = new MemoryStream(); workbook.SaveAs(stream); return stream.ToArray(); } public (DateTime startDate, DateTime? endDate)? GetValidatedUsageStatsDateRange( string startDateString, string endDateString, int centreId ) { var startDateInvalid = !DateTime.TryParse(startDateString, out var startDate); if (startDateInvalid || startDate < GetStartOfActivityForCentre(centreId)) { return null; } var endDateIsSet = DateTime.TryParse(endDateString, out var endDate); if (endDateIsSet && (endDate < startDate || endDate > DateTime.Now)) { return null; } return (startDate, endDateIsSet ? endDate : (DateTime?)null); } private string GetJobGroupNameForActivityFilter(int? jobGroupId) { var jobGroupName = jobGroupId.HasValue ? jobGroupsDataService.GetJobGroupName(jobGroupId.Value) : "All"; return jobGroupName ?? "All"; } private string GetCourseCategoryNameForActivityFilter(int? courseCategoryId) { var courseCategoryName = courseCategoryId.HasValue ? courseCategoriesDataService.GetCourseCategoryName(courseCategoryId.Value) : "All"; return courseCategoryName ?? "All"; } private string GetCourseNameForActivityFilter(int? courseId) { var courseNames = courseId.HasValue ? courseDataService.GetCourseNameAndApplication(courseId.Value) : null; return courseNames?.CourseName ?? "All"; } private IEnumerable<PeriodOfActivity> GroupActivityData( IEnumerable<ActivityLog> activityData, ReportInterval interval ) { var referenceDate = DateHelper.ReferenceDate; var groupedActivityLogs = interval switch { ReportInterval.Days => activityData.GroupBy( x => new DateTime(x.LogYear, x.LogMonth, x.LogDate.Day).Ticks ), ReportInterval.Weeks => activityData.GroupBy( activityLog => referenceDate.AddDays((activityLog.LogDate - referenceDate).Days / 7 * 7).Ticks ), ReportInterval.Months => activityData.GroupBy(x => new DateTime(x.LogYear, x.LogMonth, 1).Ticks), ReportInterval.Quarters => activityData.GroupBy( x => new DateTime(x.LogYear, GetFirstMonthOfQuarter(x.LogQuarter), 1).Ticks ), _ => activityData.GroupBy(x => new DateTime(x.LogYear, 1, 1).Ticks) }; return groupedActivityLogs.Select( groupingOfLogs => new PeriodOfActivity( new DateInformation( new DateTime(groupingOfLogs.Key), interval ), groupingOfLogs.Count(activityLog => activityLog.Registered), groupingOfLogs.Count(activityLog => activityLog.Completed), groupingOfLogs.Count(activityLog => activityLog.Evaluated) ) ); } private static int GetFirstMonthOfQuarter(int quarter) { return quarter * 3 - 2; } } }
40.765766
115
0.601878
[ "MIT" ]
TechnologyEnhancedLearning/DLSV2
DigitalLearningSolutions.Data/Services/ActivityService.cs
9,052
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //------------------------------------------------------------------------------ // <auto-generated> // Types declaration for SharpDX.RawInput namespace. // This code was generated by a tool. // Date : 28/03/2015 21:51:18 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; using System.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Collections.Generic; namespace SharpDX.DirectInput { #pragma warning disable 649 #pragma warning disable 419 #pragma warning disable 1587 #pragma warning disable 1574 internal partial class LocalInterop { public static unsafe int Calliint(void* thisObject,void* arg0,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,int arg2,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,int arg0,void* arg1,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,int arg0,void* arg1,void* arg2,int arg3,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,int arg1,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,int arg1,int arg2,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,int arg1,void* arg2,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,void* arg2,void* arg3,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,int arg0,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,void* arg2,int arg3,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,int arg1,void* arg2,int arg3,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,int arg0,int arg1,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,void* arg2,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int Calliint(void* thisObject,void* arg0,void* arg1,void* arg2,void* arg3,int arg4,void* methodPtr) { throw new NotImplementedException(); } public static unsafe int CalliFuncint(void* arg0,int arg1,void* arg2,void* arg3,void* arg4,void* funcPtr) { throw new NotImplementedException(); } } }
68.061538
169
0.721293
[ "MIT" ]
Altair7610/SharpDX
Source/SharpDX.DirectInput/Generated/LocalInterop.cs
4,424
C#
#if !NETSTANDARD1_3 using System; namespace Kzrnm.Competitive.IO { /// <summary> /// <see cref="RepeatReader"/> /// </summary> public static class RepeatReaderSelectArray { /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[]) SelectArray<T1, T2>(this RepeatReader r, Func<ConsoleReader, (T1, T2)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i]) = factory(r.cr); return (arr1, arr2); } /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[]) SelectArray<T1, T2>(this RepeatReader r, Func<ConsoleReader, int, (T1, T2)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i]) = factory(r.cr, i); return (arr1, arr2); } /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[], T3[]) SelectArray<T1, T2, T3>(this RepeatReader r, Func<ConsoleReader, (T1, T2, T3)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; var arr3 = new T3[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i], arr3[i]) = factory(r.cr); return (arr1, arr2, arr3); } /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[], T3[]) SelectArray<T1, T2, T3>(this RepeatReader r, Func<ConsoleReader, int, (T1, T2, T3)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; var arr3 = new T3[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i], arr3[i]) = factory(r.cr, i); return (arr1, arr2, arr3); } /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[], T3[], T4[]) SelectArray<T1, T2, T3, T4>(this RepeatReader r, Func<ConsoleReader, (T1, T2, T3, T4)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; var arr3 = new T3[r.count]; var arr4 = new T4[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i], arr3[i], arr4[i]) = factory(r.cr); return (arr1, arr2, arr3, arr4); } /// <summary> /// Repeat <paramref name="factory"/>() /// </summary> public static (T1[], T2[], T3[], T4[]) SelectArray<T1, T2, T3, T4>(this RepeatReader r, Func<ConsoleReader, int, (T1, T2, T3, T4)> factory) { var arr1 = new T1[r.count]; var arr2 = new T2[r.count]; var arr3 = new T3[r.count]; var arr4 = new T4[r.count]; for (var i = 0; i < r.count; i++) (arr1[i], arr2[i], arr3[i], arr4[i]) = factory(r.cr, i); return (arr1, arr2, arr3, arr4); } } } #endif
35.702128
95
0.461263
[ "MIT" ]
naminodarie/Competitive.IO
Competitive.IO/ConsoleReader.RepeatReader.SelectArray.cs
3,358
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 #region Usings using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Web.UI; using Microsoft.Extensions.DependencyInjection; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Services.ModuleCache; using DotNetNuke.UI.Modules; using DotNetNuke.UI.Skins; using DotNetNuke.UI.Skins.Controls; using Globals = DotNetNuke.Common.Globals; using DotNetNuke.Instrumentation; using DotNetNuke.Abstractions; #endregion // ReSharper disable CheckNamespace namespace DotNetNuke.Modules.Admin.Modules // ReSharper restore CheckNamespace { /// <summary> /// The ModuleSettingsPage PortalModuleBase is used to edit the settings for a /// module. /// </summary> /// <remarks> /// </remarks> public partial class ModuleSettingsPage : PortalModuleBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleSettingsPage)); private readonly INavigationManager _navigationManager; public ModuleSettingsPage() { _navigationManager = DependencyProvider.GetRequiredService<INavigationManager>(); } #region Private Members private int _moduleId = -1; private Control _control; private ModuleInfo _module; private bool HideDeleteButton => Request.QueryString["HideDelete"] == "true"; private bool HideCancelButton => Request.QueryString["HideCancel"] == "true"; private bool DoNotRedirectOnUpdate => Request.QueryString["NoRedirectOnUpdate"] == "true"; private ModuleInfo Module { get { return _module ?? (_module = ModuleController.Instance.GetModule(_moduleId, TabId, false)); } } private ISettingsControl SettingsControl { get { return _control as ISettingsControl; } } private string ReturnURL { get { return UrlUtils.ValidReturnUrl(Request.Params["ReturnURL"]) ?? _navigationManager.NavigateURL(); } } #endregion #region Private Methods private void BindData() { if (Module != null) { var desktopModule = DesktopModuleController.GetDesktopModule(Module.DesktopModuleID, PortalId); dgPermissions.ResourceFile = Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + Localization.LocalSharedResourceFile; if (!Module.IsShared) { chkInheritPermissions.Checked = Module.InheritViewPermissions; dgPermissions.InheritViewPermissionsFromTab = Module.InheritViewPermissions; } txtFriendlyName.Text = Module.DesktopModule.FriendlyName; txtTitle.Text = Module.ModuleTitle; ctlIcon.Url = Module.IconFile; if (cboTab.FindItemByValue(Module.TabID.ToString()) != null) { cboTab.FindItemByValue(Module.TabID.ToString()).Selected = true; } rowTab.Visible = cboTab.Items.Count != 1; chkAllTabs.Checked = Module.AllTabs; trnewPages.Visible = chkAllTabs.Checked; allowIndexRow.Visible = desktopModule.IsSearchable; chkAllowIndex.Checked = GetBooleanSetting("AllowIndex", true); txtMoniker.Text = (string)Settings["Moniker"] ?? ""; cboVisibility.SelectedIndex = (int)Module.Visibility; chkAdminBorder.Checked = Settings["hideadminborder"] != null && bool.Parse(Settings["hideadminborder"].ToString()); var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(Module.ModuleDefID); if (objModuleDef.DefaultCacheTime == Null.NullInteger) { cacheWarningRow.Visible = true; txtCacheDuration.Text = Module.CacheTime.ToString(); } else { cacheWarningRow.Visible = false; txtCacheDuration.Text = Module.CacheTime.ToString(); } BindModuleCacheProviderList(); ShowCacheRows(); cboAlign.Items.FindByValue(Module.Alignment).Selected = true; txtColor.Text = Module.Color; txtBorder.Text = Module.Border; txtHeader.Text = Module.Header; txtFooter.Text = Module.Footer; if (!Null.IsNull(Module.StartDate)) { startDatePicker.SelectedDate = Module.StartDate; } if (!Null.IsNull(Module.EndDate) && Module.EndDate <= endDatePicker.MaxDate) { endDatePicker.SelectedDate = Module.EndDate; } BindContainers(); chkDisplayTitle.Checked = Module.DisplayTitle; chkDisplayPrint.Checked = Module.DisplayPrint; chkDisplaySyndicate.Checked = Module.DisplaySyndicate; chkWebSlice.Checked = Module.IsWebSlice; webSliceTitle.Visible = Module.IsWebSlice; webSliceExpiry.Visible = Module.IsWebSlice; webSliceTTL.Visible = Module.IsWebSlice; txtWebSliceTitle.Text = Module.WebSliceTitle; if (!Null.IsNull(Module.WebSliceExpiryDate)) { diWebSliceExpiry.SelectedDate = Module.WebSliceExpiryDate; } if (!Null.IsNull(Module.WebSliceTTL)) { txtWebSliceTTL.Text = Module.WebSliceTTL.ToString(); } if (Module.ModuleID == PortalSettings.Current.DefaultModuleId && Module.TabID == PortalSettings.Current.DefaultTabId) { chkDefault.Checked = true; } if (!Module.IsShared && Module.DesktopModule.Shareable != ModuleSharing.Unsupported) { isShareableCheckBox.Checked = Module.IsShareable; isShareableViewOnlyCheckBox.Checked = Module.IsShareableViewOnly; isShareableRow.Visible = true; chkInheritPermissions.Visible = true; } } } private void BindContainers() { moduleContainerCombo.PortalId = PortalId; moduleContainerCombo.RootPath = SkinController.RootContainer; moduleContainerCombo.Scope = SkinScope.All; moduleContainerCombo.IncludeNoneSpecificItem = true; moduleContainerCombo.NoneSpecificText = "<" + Localization.GetString("None_Specified") + ">"; moduleContainerCombo.SelectedValue = Module.ContainerSrc; } private void BindModulePages() { var tabsByModule = TabController.Instance.GetTabsByModuleID(_moduleId); tabsByModule.Remove(TabId); dgOnTabs.DataSource = tabsByModule.Values; dgOnTabs.DataBind(); } private void BindModuleCacheProviderList() { cboCacheProvider.DataSource = GetFilteredProviders(ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider"); cboCacheProvider.DataBind(); //cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "")); cboCacheProvider.InsertItem(0, Localization.GetString("None_Specified"), ""); //if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null) if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.FindItemByValue(Module.GetEffectiveCacheMethod()) != null) { //cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true; cboCacheProvider.FindItemByValue(Module.GetEffectiveCacheMethod()).Selected = true; } else { //select the None Specified value cboCacheProvider.Items[0].Selected = true; } lblCacheInherited.Visible = Module.CacheMethod != Module.GetEffectiveCacheMethod(); } private IEnumerable GetFilteredProviders<T>(Dictionary<string, T> providerList, string keyFilter) { var providers = from provider in providerList let filteredkey = provider.Key.Replace(keyFilter, String.Empty) select new { filteredkey, provider.Key }; return providers; } private void ShowCacheRows() { divCacheDuration.Visible = !string.IsNullOrEmpty(cboCacheProvider.SelectedValue); } private bool GetBooleanSetting(string settingName, bool defaultValue) { var value = Settings[settingName]; return value == null ? defaultValue : bool.Parse(value.ToString()); } #endregion #region Protected Methods protected string GetInstalledOnLink(object dataItem) { var returnValue = new StringBuilder(); var tab = dataItem as TabInfo; if (tab != null) { var index = 0; TabController.Instance.PopulateBreadCrumbs(ref tab); var defaultAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID) .OrderByDescending(a => a.IsPrimary) .FirstOrDefault(); var portalSettings = new PortalSettings(tab.PortalID) { PortalAlias = defaultAlias }; var tabUrl = _navigationManager.NavigateURL(tab.TabID, portalSettings, string.Empty); foreach (TabInfo t in tab.BreadCrumbs) { if (index > 0) { returnValue.Append(" > "); } if (tab.BreadCrumbs.Count - 1 == index) { returnValue.AppendFormat("<a href=\"{0}\">{1}</a>", tabUrl, t.LocalizedTabName); } else { returnValue.AppendFormat("{0}", t.LocalizedTabName); } index = index + 1; } } return returnValue.ToString(); } protected string GetInstalledOnSite(object dataItem) { string returnValue = String.Empty; var tab = dataItem as TabInfo; if (tab != null) { var portal = PortalController.Instance.GetPortal(tab.PortalID); if (portal != null) { returnValue = portal.PortalName; } } return returnValue; } protected bool IsSharedViewOnly() { return ModuleContext.Configuration.IsShared && ModuleContext.Configuration.IsShareableViewOnly; } #endregion #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); try { chkAllTabs.CheckedChanged += OnAllTabsCheckChanged; chkInheritPermissions.CheckedChanged += OnInheritPermissionsChanged; chkWebSlice.CheckedChanged += OnWebSliceCheckChanged; cboCacheProvider.TextChanged += OnCacheProviderIndexChanged; cmdDelete.Click += OnDeleteClick; cmdUpdate.Click += OnUpdateClick; JavaScript.RequestRegistration(CommonJs.DnnPlugins); //get ModuleId if ((Request.QueryString["ModuleId"] != null)) { _moduleId = Int32.Parse(Request.QueryString["ModuleId"]); } if (Module.ContentItemId == Null.NullInteger && Module.ModuleID != Null.NullInteger) { //This tab does not have a valid ContentItem ModuleController.Instance.CreateContentItem(Module); ModuleController.Instance.UpdateModule(Module); } //Verify that the current user has access to edit this module if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", Module)) { if (!(IsSharedViewOnly() && TabPermissionController.CanAddContentToPage())) { Response.Redirect(Globals.AccessDeniedURL(), true); } } if (Module != null) { //get module TabModuleId = Module.TabModuleID; //get Settings Control ModuleControlInfo moduleControlInfo = ModuleControlController.GetModuleControlByControlKey("Settings", Module.ModuleDefID); if (moduleControlInfo != null) { _control = ModuleControlFactory.LoadSettingsControl(Page, Module, moduleControlInfo.ControlSrc); var settingsControl = _control as ISettingsControl; if (settingsControl != null) { hlSpecificSettings.Text = Localization.GetString("ControlTitle_settings", settingsControl.LocalResourceFile); if (String.IsNullOrEmpty(hlSpecificSettings.Text)) { hlSpecificSettings.Text = String.Format(Localization.GetString("ControlTitle_settings", LocalResourceFile), Module.DesktopModule.FriendlyName); } pnlSpecific.Controls.Add(_control); } } } } catch (Exception err) { Exceptions.ProcessModuleLoadException(this, err); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { cancelHyperLink.NavigateUrl = ReturnURL; if (_moduleId != -1) { ctlAudit.Entity = Module; } if (Page.IsPostBack == false) { ctlIcon.FileFilter = Globals.glbImageFileTypes; dgPermissions.TabId = PortalSettings.ActiveTab.TabID; dgPermissions.ModuleID = _moduleId; BindModulePages(); cboTab.DataSource = TabController.GetPortalTabs(PortalId, -1, false, Null.NullString, true, false, true, false, true); cboTab.DataBind(); //if tab is a host tab, then add current tab if (Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) { cboTab.InsertItem(0, PortalSettings.ActiveTab.LocalizedTabName, PortalSettings.ActiveTab.TabID.ToString()); } if (Module != null) { if (cboTab.FindItemByValue(Module.TabID.ToString()) == null) { var objTab = TabController.Instance.GetTab(Module.TabID, Module.PortalID, false); cboTab.AddItem(objTab.LocalizedTabName, objTab.TabID.ToString()); } } //only Portal Administrators can manage the visibility on all Tabs var isAdmin = PermissionProvider.Instance().IsPortalEditor(); rowAllTabs.Visible = isAdmin; chkAllModules.Enabled = isAdmin; if (HideCancelButton) { cancelHyperLink.Visible = false; } //tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { chkNewTabs.Enabled = false; chkDefault.Enabled = false; chkAllowIndex.Enabled = false; cboTab.Enabled = false; } if (_moduleId != -1) { BindData(); cmdDelete.Visible = (ModulePermissionController.CanDeleteModule(Module) || TabPermissionController.CanAddContentToPage()) && !HideDeleteButton; } else { isShareableCheckBox.Checked = true; isShareableViewOnlyCheckBox.Checked = true; isShareableRow.Visible = true; cboVisibility.SelectedIndex = 0; //maximized chkAllTabs.Checked = false; cmdDelete.Visible = false; } if (Module != null) { cmdUpdate.Visible = ModulePermissionController.HasModulePermission(Module.ModulePermissions, "EDIT,MANAGE") || TabPermissionController.CanAddContentToPage(); permissionsRow.Visible = ModulePermissionController.CanAdminModule(Module) || TabPermissionController.CanAddContentToPage(); } //Set visibility of Specific Settings if (SettingsControl == null == false) { //Get the module settings from the PortalSettings and pass the //two settings hashtables to the sub control to process SettingsControl.LoadSettings(); specificSettingsTab.Visible = true; fsSpecific.Visible = true; } else { specificSettingsTab.Visible = false; fsSpecific.Visible = false; } if (Module != null) { termsSelector.PortalId = Module.PortalID; termsSelector.Terms = Module.Terms; } termsSelector.DataBind(); } if (Module != null) { cultureLanguageLabel.Language = Module.CultureCode; } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnAllTabsCheckChanged(object sender, EventArgs e) { trnewPages.Visible = chkAllTabs.Checked; } protected void OnCacheProviderIndexChanged(object sender, EventArgs e) { ShowCacheRows(); } protected void OnDeleteClick(Object sender, EventArgs e) { try { ModuleController.Instance.DeleteTabModule(TabId, _moduleId, true); Response.Redirect(ReturnURL, true); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnInheritPermissionsChanged(Object sender, EventArgs e) { dgPermissions.InheritViewPermissionsFromTab = chkInheritPermissions.Checked; } protected void OnUpdateClick(object sender, EventArgs e) { try { if (Page.IsValid) { var allTabsChanged = false; //only Portal Administrators can manage the visibility on all Tabs var isAdmin = PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName); chkAllModules.Enabled = isAdmin; //tab administrators can only manage their own tab if (!TabPermissionController.CanAdminPage()) { chkAllTabs.Enabled = false; chkNewTabs.Enabled = false; chkDefault.Enabled = false; chkAllowIndex.Enabled = false; cboTab.Enabled = false; } Module.ModuleID = _moduleId; Module.ModuleTitle = txtTitle.Text; Module.Alignment = cboAlign.SelectedItem.Value; Module.Color = txtColor.Text; Module.Border = txtBorder.Text; Module.IconFile = ctlIcon.Url; Module.CacheTime = !String.IsNullOrEmpty(txtCacheDuration.Text) ? Int32.Parse(txtCacheDuration.Text) : 0; Module.CacheMethod = cboCacheProvider.SelectedValue; Module.TabID = TabId; if (Module.AllTabs != chkAllTabs.Checked) { allTabsChanged = true; } Module.AllTabs = chkAllTabs.Checked; // collect these first as any settings update will clear the cache var originalChecked = Settings["hideadminborder"] != null && bool.Parse(Settings["hideadminborder"].ToString()); var allowIndex = GetBooleanSetting("AllowIndex", true); var oldMoniker = ((string)Settings["Moniker"] ?? "").TrimToLength(100); var newMoniker = txtMoniker.Text.TrimToLength(100); if (!oldMoniker.Equals(txtMoniker.Text)) { var ids = TabModulesController.Instance.GetTabModuleIdsBySetting("Moniker", newMoniker); if (ids != null && ids.Count > 0) { //Warn user - duplicate moniker value Skin.AddModuleMessage(this, Localization.GetString("MonikerExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "Moniker", newMoniker); } if (originalChecked != chkAdminBorder.Checked) { ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "hideadminborder", chkAdminBorder.Checked.ToString()); } //check whether allow index value is changed if (allowIndex != chkAllowIndex.Checked) { ModuleController.Instance.UpdateTabModuleSetting(Module.TabModuleID, "AllowIndex", chkAllowIndex.Checked.ToString()); } switch (Int32.Parse(cboVisibility.SelectedItem.Value)) { case 0: Module.Visibility = VisibilityState.Maximized; break; case 1: Module.Visibility = VisibilityState.Minimized; break; //case 2: default: Module.Visibility = VisibilityState.None; break; } Module.IsDeleted = false; Module.Header = txtHeader.Text; Module.Footer = txtFooter.Text; Module.StartDate = startDatePicker.SelectedDate != null ? startDatePicker.SelectedDate.Value : Null.NullDate; Module.EndDate = endDatePicker.SelectedDate != null ? endDatePicker.SelectedDate.Value : Null.NullDate; Module.ContainerSrc = moduleContainerCombo.SelectedValue; Module.ModulePermissions.Clear(); Module.ModulePermissions.AddRange(dgPermissions.Permissions); Module.Terms.Clear(); Module.Terms.AddRange(termsSelector.Terms); if (!Module.IsShared) { Module.InheritViewPermissions = chkInheritPermissions.Checked; Module.IsShareable = isShareableCheckBox.Checked; Module.IsShareableViewOnly = isShareableViewOnlyCheckBox.Checked; } Module.DisplayTitle = chkDisplayTitle.Checked; Module.DisplayPrint = chkDisplayPrint.Checked; Module.DisplaySyndicate = chkDisplaySyndicate.Checked; Module.IsWebSlice = chkWebSlice.Checked; Module.WebSliceTitle = txtWebSliceTitle.Text; Module.WebSliceExpiryDate = diWebSliceExpiry.SelectedDate != null ? diWebSliceExpiry.SelectedDate.Value : Null.NullDate; if (!string.IsNullOrEmpty(txtWebSliceTTL.Text)) { Module.WebSliceTTL = Convert.ToInt32(txtWebSliceTTL.Text); } Module.IsDefaultModule = chkDefault.Checked; Module.AllModules = chkAllModules.Checked; ModuleController.Instance.UpdateModule(Module); //Update Custom Settings if (SettingsControl != null) { try { SettingsControl.UpdateSettings(); } catch (ThreadAbortException exc) { Logger.Debug(exc); Thread.ResetAbort(); //necessary } catch (Exception ex) { Exceptions.LogException(ex); } } //These Module Copy/Move statements must be //at the end of the Update as the Controller code assumes all the //Updates to the Module have been carried out. //Check if the Module is to be Moved to a new Tab if (!chkAllTabs.Checked) { var newTabId = Int32.Parse(cboTab.SelectedValue); if (TabId != newTabId) { //First check if there already is an instance of the module on the target page var tmpModule = ModuleController.Instance.GetModule(_moduleId, newTabId, false); if (tmpModule == null) { //Move module ModuleController.Instance.MoveModule(_moduleId, TabId, newTabId, Globals.glbDefaultPane); } else { //Warn user Skin.AddModuleMessage(this, Localization.GetString("ModuleExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } } } //Check if Module is to be Added/Removed from all Tabs if (allTabsChanged) { var listTabs = TabController.GetPortalTabs(PortalSettings.PortalId, Null.NullInteger, false, true); if (chkAllTabs.Checked) { if (!chkNewTabs.Checked) { foreach (var destinationTab in listTabs) { var module = ModuleController.Instance.GetModule(_moduleId, destinationTab.TabID, false); if (module != null) { if (module.IsDeleted) { ModuleController.Instance.RestoreModule(module); } } else { if (!PortalSettings.ContentLocalizationEnabled || (Module.CultureCode == destinationTab.CultureCode)) { ModuleController.Instance.CopyModule(Module, destinationTab, Module.PaneName, true); } } } } } else { ModuleController.Instance.DeleteAllModules(_moduleId, TabId, listTabs, true, false, false); } } if (!DoNotRedirectOnUpdate) { //Navigate back to admin page Response.Redirect(ReturnURL, true); } } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } protected void OnWebSliceCheckChanged(object sender, EventArgs e) { webSliceTitle.Visible = chkWebSlice.Checked; webSliceExpiry.Visible = chkWebSlice.Checked; webSliceTTL.Visible = chkWebSlice.Checked; } protected void dgOnTabs_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e) { dgOnTabs.PageIndex = e.NewPageIndex; BindModulePages(); } #endregion } }
43.025066
182
0.498268
[ "MIT" ]
Tychodewaard/Dnn.Platform
DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs
32,615
C#
using GoodToCode.Shared.Specs; using GoodToCode.Subjects.Infrastructure; using GoodToCode.Subjects.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using TechTalk.SpecFlow; namespace GoodToCode.Subjects.Specs { [Binding] public class BusinessUpdateSteps : ICrudSteps<Business> { private readonly SubjectsDbContext _dbContext; private readonly string _connectionString; private readonly IConfiguration _config; private readonly BusinessCreateSteps createSteps = new BusinessCreateSteps(); private string SutName { get; set; } private string SutNameNew { get; set; } public Guid SutKey { get; private set; } public Business Sut { get; private set; } public IList<Business> Suts { get; private set; } = new List<Business>(); public IList<Business> RecycleBin { get; private set; } = new List<Business>(); public BusinessUpdateSteps() { _config = new ConfigurationFactory().CreateFromAzureSettings(); _connectionString = new ConnectionStringFactory(_config).CreateFromAzureSettings("Stack:Shared:SqlConnection"); _dbContext = new DbContextFactory(_connectionString).Create(); } [Given(@"An existing Business has been queried")] public async Task GivenAnExistingBusinessHasBeenQueried() { createSteps.GivenANewBusinessHasBeenCreated(); await createSteps.WhenBusinessIsInsertedViaEntityFramework(); Sut = await _dbContext.Business.FirstAsync(); SutKey = Sut.BusinessKey; } [Given(@"a business was found in persistence")] public void GivenABusinessWasFoundInPersistence() { Assert.IsTrue(Sut.BusinessKey != Guid.Empty); } [When(@"the Business name changes")] public void WhenTheBusinessNameChanges() { SutKey = Sut.BusinessKey; SutName = Sut.BusinessName; SutNameNew = $"Business name as of {DateTime.UtcNow.ToShortTimeString()}"; Sut.BusinessName = SutNameNew; } [When(@"Business is Updated via Entity Framework")] public async Task WhenBusinessIsUpdatedViaEntityFramework() { _dbContext.Entry(Sut).State = EntityState.Modified; var result = await _dbContext.SaveChangesAsync(); Assert.IsTrue(result > 0); } [Then(@"the existing business can be queried by key")] public async Task ThenTheExistingBusinessCanBeQueriedByKey() { Sut = await _dbContext.Business.FirstOrDefaultAsync(x => x.BusinessKey == SutKey); } [Then(@"the Business name matches the new name")] public void ThenTheBusinessNameMatchesTheNewName() { Assert.IsTrue(SutNameNew == Sut.BusinessName); Assert.IsFalse(SutNameNew == SutName); } [TestCleanup] public async Task Cleanup() { foreach (var item in RecycleBin) { _dbContext.Entry(item).State = EntityState.Deleted; await _dbContext.SaveChangesAsync(); } } } }
37.031579
124
0.630756
[ "Apache-2.0" ]
goodtocode/stack
src/Subjects.Specs.Unit/Infrastructure/Associate/BusinessUpdateSteps.cs
3,520
C#
namespace RegularExpressionScratchpad { using System; /// <summary> /// RegexRef. /// </summary> public class RegexRef : IComparable { private readonly int start; private int end; /// <summary> /// Initializes a new instance of the <see cref="RegexRef"/> class. /// </summary> /// <param name="regexItem">The regex item.</param> /// <param name="start">The start.</param> /// <param name="end">The end.</param> public RegexRef(RegexItem regexItem, int start, int end) { if (regexItem == null) { throw new ArgumentNullException(nameof(regexItem), "RegexItem is null"); } this.StringValue = regexItem.ToString(0); this.start = start; this.end = end; } /// <summary> /// Gets or sets the string value. /// </summary> /// <value>The string value.</value> public string StringValue { get; set; } /// <summary> /// Gets the start. /// </summary> /// <value>The start.</value> public int Start => this.start; /// <summary> /// Gets the end. /// </summary> /// <value>The end.</value> public int End => this.end; /// <summary> /// Gets or sets the length. /// </summary> /// <value>The length.</value> public int Length { get => this.end - this.start + 1; set => this.end = this.start + value - 1; } /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance is less than obj. Zero This instance is equal to obj. Greater than zero This instance is greater than obj. /// </returns> /// <exception cref="T:System.ArgumentException">obj is not the same type as this instance. </exception> public int CompareTo(object obj) { RegexRef ref2 = (RegexRef)obj; if (this.Length < ref2.Length) { return -1; } return this.Length > ref2.Length ? 1 : 0; } /// <summary> /// Ins the range. /// </summary> /// <param name="location">The location.</param> /// <returns>bool</returns> public bool InRange(int location) { return (location >= this.start) && (location <= this.end); } } }
31.277778
287
0.523268
[ "MIT" ]
mikefourie-zz/RegularExpressionScratchpad
Classes/RegexRef.cs
2,815
C#
using static ProjectEuler.Problems.Helpers.Funcs; namespace ProjectEuler.Problems.Solutions { /// <summary> /// Smallest multiple /// <see cref="https://projecteuler.net/problem=5"/> /// </summary> public class Problem005 : IProblem { public int Id => 5; public string Title => "Smallest multiple"; public string Description => "2520 is the smallest number that can be divided by each of the numbers " + "from 1 to 10 without any remainder. \r\n" + "What is the smallest positive number that is evenly divisible by all of the numbers " + "from 1 to 20?"; public string GetSolution() { long result = 1; for (int i = 1; i <= 20; i++) result = Lcd(i, result); return result.ToString(); } } }
29.965517
100
0.563867
[ "MIT" ]
cyberpunk2099/Project-Euler
src/ProjectEuler/ProjectEuler.Problems/Solutions/Problem005.cs
871
C#
using Newtonsoft.Json; using Shriek.Events; using Shriek.Exceptions; using Shriek.Messages; using Shriek.Notifications; using System; namespace Shriek.Commands { public class CommandMessageSubscriber<TCommand> : IMessageSubscriber<TCommand> where TCommand : Message { private readonly IServiceProvider container; private readonly ICommandContext commandContext; private readonly IEventBus eventBus; public CommandMessageSubscriber(IServiceProvider container, ICommandContext context, IEventBus eventBus) { this.container = container; this.commandContext = context; this.eventBus = eventBus; } public void Execute(TCommand command) { if (container == null) return; var handler = container.GetService(typeof(ICommandHandler<TCommand>)); if (handler != null) { try { ((ICommandHandler<TCommand>)handler).Execute(commandContext, command); ((ICommandContextSave)commandContext).Save(); } catch (DomainException ex) { eventBus.Publish(new DomainNotification(ex.Message, JsonConvert.SerializeObject(command))); throw; } } else { throw new Exception($"找不到命令{nameof(command)}的处理类,或者IOC未注册。"); } } } }
31.354167
112
0.583389
[ "MIT" ]
1071157808/shriek-fx
src/Shriek/Commands/CommandMessageSubscriber.cs
1,539
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.Kusto.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions; /// <summary>Add Database principals permissions.</summary> /// <remarks> /// [OpenAPI] Databases_AddPrincipals=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/Clusters/{clusterName}/Databases/{databaseName}/addPrincipals" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Add, @"AzKustoDatabasePrincipal_AddViaIdentityExpanded", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipal))] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Description(@"Add Database principals permissions.")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Generated] public partial class AddAzKustoDatabasePrincipal_AddViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Kusto Client => Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.ClientAPI; /// <summary>Backing field for <see cref="DatabasePrincipalsToAddBody" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListRequest _databasePrincipalsToAddBody= new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.DatabasePrincipalListRequest(); /// <summary>The list Kusto database principals operation request.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListRequest DatabasePrincipalsToAddBody { get => this._databasePrincipalsToAddBody; set => this._databasePrincipalsToAddBody = value; } /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Backing field for <see cref="InputObject" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity _inputObject; /// <summary>Identity Parameter</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Path)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>The list of Kusto database principals.</summary> [global::System.Management.Automation.AllowEmptyCollection] [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The list of Kusto database principals.")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info( Required = false, ReadOnly = false, Description = @"The list of Kusto database principals.", SerializedName = @"value", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipal) })] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipal[] Value { get => DatabasePrincipalsToAddBody.Value ?? null /* arrayOf */; set => DatabasePrincipalsToAddBody.Value = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListResult" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListResult> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// Intializes a new instance of the <see cref="AddAzKustoDatabasePrincipal_AddViaIdentityExpanded" /> cmdlet class. /// </summary> public AddAzKustoDatabasePrincipal_AddViaIdentityExpanded() { } /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Information: { var data = messageData(); WriteInformation(data, new[] { data.Message }); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'DatabasesAddPrincipals' operation")) { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token); } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } if (InputObject?.Id != null) { await this.Client.DatabasesAddPrincipalsViaIdentity(InputObject.Id, DatabasePrincipalsToAddBody, onOk, onDefault, this, Pipeline); } else { // try to call with PATH parameters from Input Object if (null == InputObject.ResourceGroupName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ClusterName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.DatabaseName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DatabaseName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.SubscriptionId) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } await this.Client.DatabasesAddPrincipals(InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, InputObject.DatabaseName ?? null, InputObject.SubscriptionId ?? null, DatabasePrincipalsToAddBody, onOk, onDefault, this, Pipeline); } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=DatabasePrincipalsToAddBody}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=DatabasePrincipalsToAddBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=DatabasePrincipalsToAddBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListResult" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20200215.IDatabasePrincipalListResult> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // response should be returning an array of some kind. +Pageable // nested-array / value / <none> WriteObject((await response).Value, true); } } } }
75.506203
451
0.667324
[ "MIT" ]
Arsasana/azure-powershell
src/Kusto/generated/cmdlets/AddAzKustoDatabasePrincipal_AddViaIdentityExpanded.cs
30,027
C#
// ------------------------------------------------------------ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace ServiceFabric.WindowsPatchInstaller { using Microsoft.ServiceFabric.Services.Runtime; using System; using System.Diagnostics; using System.Threading; internal static class Program { /// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime.RegisterServiceAsync("PatchInstallerServiceType", context => new PatchInstallerService(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(PatchInstallerService).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } } } }
39.380952
134
0.551391
[ "MIT" ]
DianeHadley/service-fabric-windows-patch-installer
src/PatchInstallerService/Program.cs
1,656
C#
namespace CustomCode.Core.CodeGeneration.Scripting.Features { using Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An <see cref="IFeatureAnalyzer"/> that analyzes if an <see cref="IScript"/> source code /// uses input parameters. /// </summary> [Export] public sealed class ParameterCollectionAnalyzer : IFeatureAnalyzer { #region Data /// <summary> /// The name of the script's input parameter context. /// </summary> private const string InputContext = nameof(ScriptContext.In); #endregion #region Logic /// <summary> /// Query if the <paramref name="sourceCode"/> uses the <see cref="ParameterCollection"/> feature, i.e. if the /// script makes calls to any of the <see cref="ScriptContext.In"/> dynamic input parameters. /// </summary> /// <param name="sourceCode"> The script's source code (as Roslyn <see cref="SyntaxTree"/> representation). </param> /// <param name="feature"> The script's <see cref="ParameterCollection"/> feature (if present) or null otherwise. </param> /// <returns> True if the <see cref="ParameterCollection"/> feature was found, false otherwise. </returns> public bool HasFeature(IEnumerable<SyntaxTree> sourceCode, out IFeature feature) { if (sourceCode == null || !sourceCode.Any()) { feature = null; return false; } var inputParameter = new List<string>(); foreach (var syntaxTree in sourceCode) { var root = syntaxTree.GetRoot(); var memberNodes = root.DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToList(); if (memberNodes == null || memberNodes.Count == 0) { continue; } var inputNodes = memberNodes.Where(n => n .DescendantNodes() .OfType<IdentifierNameSyntax>() .Any(name => name.Identifier.Text.Equals(InputContext, StringComparison.OrdinalIgnoreCase))) .ToList(); if (inputNodes == null || inputNodes.Count == 0) { continue; } var inputNameNodes = inputNodes .SelectMany(n => n .DescendantNodes() .OfType<IdentifierNameSyntax>()) .Where(name => !name.Identifier.Text.Equals(InputContext, StringComparison.OrdinalIgnoreCase)) .ToList(); if (inputNameNodes == null || inputNameNodes.Count == 0) { continue; } foreach (var name in inputNameNodes.Select(n => n.Identifier.Text)) { inputParameter.Add(name); } } feature = inputParameter.Count == 0 ? null : new ParameterCollection(inputParameter); return inputParameter.Count > 0; } #endregion } }
38.302326
130
0.547055
[ "MIT" ]
git-custom-code/Core-CodeGeneration
src/Core/CodeGeneration.Scripting/Features/ParameterCollection/ParameterCollectionAnalyzer.cs
3,294
C#
using System; using System.Collections.Generic; namespace PenguinSteamerSecondSeason.Common { /// <summary> /// APIなどを呼び出さない単純な関数を集める /// 計算用関数など /// </summary> public class Utility { #region ToRoundDown:指定した精度の数値に切り捨てします。 /// ------------------------------------------------------------------------ /// <summary> /// 指定した精度の数値に切り捨てします。</summary> /// <param name="dValue"> /// 丸め対象の倍精度浮動小数点数。</param> /// <param name="iDigits"> /// 戻り値の有効桁数の精度。小数第何位か</param> /// <returns> /// iDigits に等しい精度の数値に切り捨てられた数値。</returns> /// ------------------------------------------------------------------------ public static double ToRoundDown(double dValue, int iDigits) { double dCoef = System.Math.Pow(10, iDigits); return dValue > 0 ? System.Math.Floor(dValue * dCoef) / dCoef : System.Math.Ceiling(dValue * dCoef) / dCoef; } #endregion #region GetDecimal:小数第n位の数値を取得する /// <summary> /// 小数第n位の数値を取得する /// </summary> /// <param name="dValue">値</param> /// <param name="iDigits">小数第何位か</param> /// <returns></returns> public static int GetDecimal(double dValue, int iDigits) { double dCoef = System.Math.Pow(10, iDigits); int coef = (int)dCoef; coef %= 10; return coef; } #endregion #region last:配列を逆からアクセスします // LastOrDefaultは該当要素がない場合nullや規定値を返却 // 基本的にテクニカルの計算で使用。通常はLINQのLastを使用すること。 /// <summary> /// 配列を逆からアクセスします /// 最後の要素を返却 /// </summary> public static double Last(List<double> list) { if (list.Count == 0) { return 0; } return Last<double>(list); } /// <summary> /// 配列を逆からアクセスします /// 0から /// </summary> public static T Last<T>(List<T> list) { return Last<T>(list, 0); } /// <summary> /// 配列を逆からアクセスします /// 0から /// </summary> public static double Last(List<double> list, int i) { if (list.Count == 0) { return 0; } return Last<double>(list, i); } /// <summary> /// 配列を逆からアクセスします /// 0から /// </summary> public static T Last<T>(List<T> list, int i) { return list[list.Count - 1 - i]; } #endregion #region 配列から、最後から数件を取り出した差分配列を取得する /// <summary> /// 配列から、最後から数件を取り出した差分配列を取得する /// 簡易コピーなので、オブジェクト型の配列の場合は中身を変更しないこと /// 指定した長さ未満だった場合、取れるだけ取る /// </summary> /// <typeparam name="T">配列型</typeparam> /// <param name="list">元ソース配列</param> /// <param name="size">最後からいくつ取り出すか</param> /// <returns>配列</returns> public static List<T> LastSubList<T>(List<T> list, int size) { int index = 0; int count = 0; // どのくらいを引き出すか計算する if (list.Count >= size) { // 十分な要素数の場合、普通に取得 index = list.Count - size; count = size; return list.GetRange(index, count); } else { // 足りない場合はそのまま返す return list; } } #endregion #region calcAve:配列の最新数件の平均を求める /// <summary> /// 配列の最新数件の平均を求める /// </summary> /// <param name="length">最後から何件を平均するか、配列が足りない場合はあるだけ平均する</param> /// <returns></returns> public static double CalcSma(List<double> list, int length) { decimal ave = 0; length = Math.Min(list.Count, length); // 合計を求める for (int i = 0; i < length; i++) { ave += (decimal)Last(list, i); } // 割る decimal result = ave / length; return (double)result; } #endregion #region calcEma:指数移動平均線を求める /// <summary> /// 指数移動平均(EMA)を求める /// </summary> /// <param name="length">長さ</param> /// <param name="refList">計算元の値のリスト</param> /// <param name="lastEma">最新のEMA(無かったら適当な値)</param> /// <returns></returns> public static double CalcEma(int length, List<double> refList, double lastEma) { if (refList.Count <= length) { return CalcSma(refList, length); } else { decimal k = 2.0m / (length + 1); decimal close = (decimal)Last(refList); decimal dLastEma = (decimal)lastEma; return (double)(dLastEma + (close - dLastEma) * k); } } #endregion #region calcSigma:標準偏差を求める /// <summary> /// 標準偏差を求める /// </summary> /// <returns>標準偏差</returns> /// <param name="length">ラストから何件の標準偏差を求めるか</param> /// <param name="refList">単純履歴</param> public static double CalcSigma(int length, List<double> refList, double average) { var lastList = Utility.LastSubList(refList, length); if (lastList.Count > 0 && length > 0) { double sum1 = 0; foreach (var item in lastList) { var temp = item - average; sum1 += temp * temp; } return Math.Sqrt(sum1 / (length - 1)); } return -1; } #endregion #region calcDelta:1回の変化量を求める /// <summary> /// 1回の変化量を求める /// 配列の最後2要素の変化量を算出する /// </summary> /// <param name="refList">平均</param> /// <returns></returns> public static double CalcDelta(List<double> refList) { return Last(refList, 0) - Last(refList, 1); } #endregion #region isBuySignal:売買シグナル /// <summary> /// 売買シグナル /// list1の方に短いスパンの配列を入れること /// リストの最後の要素を入れること /// </summary> /// <param name="list1Last"></param> /// <param name="list2Last"></param> /// <returns>短期の方の値が高ければtrueで買いトレンドとなる、そうでなければfalseで売りトレンド</returns> public static bool IsBuySignal(double list1Last, double list2Last) { return list1Last > list2Last; } #endregion #region isCross:クロスしたかどうかを判定する /// <summary> /// クロスしたかどうかを判定する /// </summary> /// <param name="aOld">Aの1個前のデータ</param> /// <param name="bOld">Bの1個前のデータ</param> /// <param name="aCurrent">Aの現在のデータ</param> /// <param name="bCurrent">Bの現在のデータ</param> /// <returns>クロスしていたらtrue</returns> public static bool IsCross(double aOld, double bOld, double aCurrent, double bCurrent) { double lastd = aOld - bOld; double current = aCurrent - bCurrent; // 符号が違ってたらクロス return lastd * current < 0; } #endregion } }
29.596774
94
0.473706
[ "MIT" ]
genkokudo/PenguinSteamerSecondSeason
PenguinSteamerSecondSeason/Common/Utility.cs
8,914
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameMemento.Session { /// <summary> /// Clase Originator (Creador). /// </summary> public class Player { #region State /// <summary> /// Nivel. /// </summary> public int Level { get; set; } /// <summary> /// Puntaje. /// </summary> public int Score { get; set; } /// <summary> /// Salud. /// </summary> public int Health { get; set; } #endregion #region Other Attributes private int lives = 3; /// <summary> /// Numero de vidas . /// </summary> public int Lives { get { return lives; } private set { lives = value; } } #endregion /// <summary> /// Crea una instancia de Memento, con el estado actual del jugador. /// </summary> /// <returns>Memento creado, representado por su interfaz pública.</returns> public IPublicMemento CreateCheckpoint() { IPublicMemento memento = new CheckpointMemento { Level = this.Level, Score = this.Score, Health = this.Health }; return memento; } /// <summary> /// Restaura el estado del jugador utilizando el estado del memento. /// </summary> /// <returns>Memento que contiene el estado a restaurar.</returns> public void RestoreCheckpoint(IPublicMemento memento) { if (memento == null) { throw new ArgumentException("Memento no debe ser nulo."); } IInternalMemento internalMemento = memento as IInternalMemento; if (internalMemento == null) { throw new InvalidCastException("Memento inválido."); } this.Level = internalMemento.Level; this.Score = internalMemento.Score; this.Health = internalMemento.Health; this.Lives--; } public override string ToString() { return $"Nivel: {this.Level}\nPuntaje: {this.Score}\nSalud: {this.Health}%\nVidas: {this.Lives}"; } } }
24.62
109
0.500812
[ "Unlicense" ]
wilmerbz/designpatterns
GameMemento/GameMemento.Session/Player.cs
2,466
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Security.Claims; using Microsoft.Azure.WebJobs.Extensions.SignalRService; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using LCU.StateAPI; using Microsoft.Azure.Storage.Blob; using LCU.StateAPI.Utilities; using LCU.State.API.NapkinIDE.ApplicationManagement.State; namespace LCU.State.API.NapkinIDE.ApplicationManagement.Host { public static class ConnectToState { [FunctionName("ConnectToState")] public static async Task<ConnectToStateResponse> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req, ILogger log, ClaimsPrincipal claimsPrincipal, //[LCUStateDetails]StateDetails stateDetails, [SignalR(HubName = ApplicationManagementState.HUB_NAME)]IAsyncCollector<SignalRMessage> signalRMessages, [SignalR(HubName = ApplicationManagementState.HUB_NAME)]IAsyncCollector<SignalRGroupAction> signalRGroupActions, [Blob("state-api/{headers.lcu-ent-lookup}/{headers.lcu-hub-name}/{headers.x-ms-client-principal-id}/{headers.lcu-state-key}", FileAccess.ReadWrite)] CloudBlockBlob stateBlob) { var stateDetails = StateUtils.LoadStateDetails(req); if (stateDetails.StateKey == "data-apps") return await signalRMessages.ConnectToState<DataAppsManagementState>(req, log, claimsPrincipal, stateBlob, signalRGroupActions); else return await signalRMessages.ConnectToState<ApplicationManagementState>(req, log, claimsPrincipal, stateBlob, signalRGroupActions); } } }
49.972222
187
0.74597
[ "Apache-2.0" ]
napkin-ide/state-api-application-management
state-api-application-management/Host/ConnectToState.cs
1,799
C#
using UnityEngine; using System.Collections.Generic; namespace Telescopes { public static class TelescopeUtils { static int segmentCount = 0; /// <summary> /// Returns the coordinate-wise min of two vectors. /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> /// <returns></returns> public static Vector3 VectorMin(Vector3 v1, Vector3 v2) { return new Vector3( Mathf.Min(v1.x, v2.x), Mathf.Min(v1.y, v2.y), Mathf.Min(v1.z, v2.z)); } /// <summary> /// Converts a discrete curvature (bend angle) to the continuous quantity. /// </summary> /// <param name="discreteAngle"></param> /// <param name="segLength"></param> /// <returns></returns> public static float CurvatureOfDiscrete(float discreteAngle, float segLength) { return discreteAngle / segLength; } /// <summary> /// Returns the signed angle in degrees between the first vector and the second. /// </summary> /// <param name="from">The first vector.</param> /// <param name="to">The second vector.</param> /// <param name="up">The vector about which the rotation should be measured.</param> /// <returns>Signed angle in degrees between from and to.</returns> public static float AngleBetween(Vector3 from, Vector3 to, Vector3 up) { Vector3 cross = Vector3.Cross(from, to); float sgn = Mathf.Sign(Vector3.Dot(cross, up)); return Mathf.Rad2Deg * sgn * Mathf.Atan2(cross.magnitude, Vector3.Dot(from, to)); } public static Vector3 TranslateAlongHelix(float curvature, float torsion, float arcLength) { if (Mathf.Abs(torsion) < 1e-6) return translateAlongCircle(curvature, arcLength); if (curvature < 1e-6) return Vector3.forward * arcLength; // Correct because the initial tangent of a helix isn't (0, 0, 1), // but we want it to be for linking up of helical pieces. OrthonormalFrame zeroFrame = FrameAlongHelix(curvature, torsion, 0); Quaternion correctiveR = Quaternion.Inverse(Quaternion.LookRotation(zeroFrame.T, zeroFrame.N)); float sumSq = curvature * curvature + torsion * torsion; float a = curvature / sumSq; float b = torsion / sumSq; float abSqrt = Mathf.Sqrt(a * a + b * b); float t = arcLength; Vector3 pos = new Vector3(b * t / abSqrt, a * Mathf.Cos(t / abSqrt), a * Mathf.Sin(t / abSqrt)); // This treats (0, 0, 0) as the center and (0, 0, a) as the first point. // Want to treat (0, -a, 0) as the first point, so rotate. //Quaternion r = Quaternion.FromToRotation(Vector3.forward, Vector3.down); pos.y *= -1; // Shift so that (0, a, 0) is the center and (0, 0, 0) is the first point. pos += (a * Vector3.up); return correctiveR * pos; } public static OrthonormalFrame FrameAlongHelix(float curvature, float torsion, float arcLength) { // No torsion = just a circular rotation. if (Mathf.Abs(torsion) < 1e-6) { OrthonormalFrame defaultFrame = new OrthonormalFrame(Vector3.forward, Vector3.up, Vector3.Cross(Vector3.forward, Vector3.up)); Quaternion r = rotateAlongCircle(curvature, arcLength); return defaultFrame.RotatedBy(r); } // Torsion but no curvature = rotate about forward axis in a screw motion if (curvature < 1e-6) { OrthonormalFrame defaultFrame = new OrthonormalFrame(Vector3.forward, Vector3.up, Vector3.Cross(Vector3.forward, Vector3.up)); float rotationAngle = torsion * arcLength; Quaternion r = Quaternion.AngleAxis(Mathf.Rad2Deg * rotationAngle, Vector3.forward); return defaultFrame.RotatedBy(r); } float sumSq = curvature * curvature + torsion * torsion; float a = curvature / sumSq; float b = torsion / sumSq; float abSqrt = Mathf.Sqrt(a * a + b * b); float t = arcLength; Vector3 tangent = new Vector3(b, -a * Mathf.Sin(t / abSqrt), a * Mathf.Cos(t / abSqrt)) / abSqrt; tangent.y *= -1; tangent.Normalize(); Vector3 normal = new Vector3(0, Mathf.Cos(t / abSqrt), Mathf.Sin(t / abSqrt)) * -1; normal.y *= -1; normal.Normalize(); Vector3 binormal = Vector3.Cross(tangent, normal); return new OrthonormalFrame(tangent, normal, binormal); } public static Quaternion RotateAlongHelix(float curvature, float torsion, float arcLength) { // No torsion = just a circular rotation. if (Mathf.Abs(torsion) < 1e-6) { return rotateAlongCircle(curvature, arcLength); } // Torsion but no curvature = rotate about forward axis in a screw motion if (curvature < 1e-6) { float rotationAngle = torsion * arcLength; return Quaternion.AngleAxis(Mathf.Rad2Deg * rotationAngle, Vector3.forward); } // Correct because the initial tangent of a helix isn't (0, 0, 1), // but we want it to be for linking up of helical pieces. OrthonormalFrame zeroFrame = FrameAlongHelix(curvature, torsion, 0); Quaternion correctiveR = Quaternion.Inverse(Quaternion.LookRotation(zeroFrame.T, zeroFrame.N)); OrthonormalFrame frame = FrameAlongHelix(curvature, torsion, arcLength); // Corrective rotation so that initial tangent is forward. //Quaternion r = Quaternion.FromToRotation(Vector3.forward, Vector3.down); return correctiveR * Quaternion.LookRotation(frame.T, frame.N); } public static Vector3 translateAlongCircle(float curvatureAmount, float arcLength) { if (curvatureAmount > 1e-6) { float curvatureRadius = 1f / curvatureAmount; // Start at the bottom of the circle. float baseAngle = 3 * Mathf.PI / 2; // + baseRadians; // Compute how many radians we moved. float radians = arcLength * curvatureAmount; float finalAngle = baseAngle + radians; // Compute on the circle centered at (0, 0, 0), // and then add (0, r, 0). Vector3 center = Vector3.up * curvatureRadius; Vector3 displacement = Vector3.zero; displacement.z = Mathf.Cos(finalAngle) * curvatureRadius; displacement.y = Mathf.Sin(finalAngle) * curvatureRadius; displacement += center; return displacement; } else { Vector3 displacement = (arcLength /* + baseRadians */) * Vector3.forward; return displacement; } } public static Quaternion rotateAlongCircle(float curvatureAmount, float arcLength) { if (curvatureAmount < 1e-6) return Quaternion.identity; // Compute how many radians we moved. float radians = arcLength * curvatureAmount; // + baseRadians; // Now rotate the forward vector by that amount. Vector3 axisOfRotation = Vector3.right; float degrees = radians / Mathf.Deg2Rad; Quaternion rotation = Quaternion.AngleAxis(-degrees, axisOfRotation); return rotation; } /// <summary> /// Returns the local position of a child shell with the given parameters, /// such that (when combined with the local rotation from childBaseRotation) /// the end cross-section of the child will be perfectly aligned /// with the end cross-section of the parent with its parameters. /// </summary> /// <param name="parent"></param> /// <param name="child"></param> /// <param name="useTorsion"></param> /// <returns></returns> public static Vector3 childBasePosition(TelescopeParameters parent, TelescopeParameters child, bool useTorsion = true) { float parentTorsion = (useTorsion) ? parent.torsion : 0; float childTorsion = (useTorsion) ? child.torsion : 0; Vector3 translationToBase = TranslateAlongHelix(parent.curvature, parentTorsion, parent.length); Quaternion rotationToBase = RotateAlongHelix(parent.curvature, parentTorsion, parent.length); Vector3 translationBackwards = TranslateAlongHelix(child.curvature, childTorsion, -child.length); translationToBase = translationToBase + (rotationToBase * translationBackwards); return translationToBase; } /// <summary> /// Returns the local rotation of a child shell with the given parameters, /// such that, when used with the local position from childBasePosition, /// the end cross-section of the child will be perfectly aligned /// with the end cross-section of the parent with its parameters. /// </summary> /// <param name="parent"></param> /// <param name="child"></param> /// <param name="useTorsion"></param> /// <returns></returns> public static Quaternion childBaseRotation(TelescopeParameters parent, TelescopeParameters child, bool useTorsion = true) { float parentTorsion = (useTorsion) ? parent.torsion : 0; float childTorsion = (useTorsion) ? child.torsion : 0; Quaternion rotationToBase = RotateAlongHelix(parent.curvature, parentTorsion, parent.length); Quaternion rotationBack = RotateAlongHelix(child.curvature, childTorsion, -child.length); return rotationToBase * rotationBack; } public static Vector3 FarthestPointOnCircle(Vector3 circCenter, Vector3 circNormal, float radius, Vector3 point) { Vector3 ptToCenter = circCenter - point; Vector3 perpToNormal = ptToCenter - circNormal * Vector3.Dot(ptToCenter, circNormal); float norm = perpToNormal.magnitude; if (norm <= 0) { if (circNormal == Vector3.up) return circCenter + radius * Vector3.right; else { perpToNormal = Vector3.up - circNormal * Vector3.Dot(circNormal, Vector3.up); return circCenter + radius * perpToNormal.normalized; } } perpToNormal /= norm; Vector3 circPoint = circCenter + radius * perpToNormal; return circPoint; } public static void growParentToChildHelix(TelescopeParameters parent, TelescopeParameters child, bool shrinkFit = false) { float maxRequiredRadius = 0; // Find the largest radius necessary at every point along the parent arc for (int i = 0; i <= Constants.CUTS_PER_CYLINDER; i++) { float arcPos = parent.length / Constants.CUTS_PER_CYLINDER * i; Vector3 parentPos = TranslateAlongHelix(parent.curvature, parent.torsion, arcPos); Vector3 parentT = FrameAlongHelix(parent.curvature, parent.torsion, arcPos).T; float minDot = 1; Vector3 closestPoint = parentPos; float closestArc = 0; // Find the point on the second arc nearest to the normal of the first one. for (int j = 0; j <= Constants.CUTS_PER_CYLINDER; j++) { float childArc = child.length / Constants.CUTS_PER_CYLINDER * j; Vector3 childPos = TranslateAlongHelix(child.curvature, child.torsion, childArc); Vector3 childOffset = childPos - parentPos; // Want the point to be in the orthogonal plane of the tangent, since // the cross-sections of the shell are circular in that plane float dot = Vector3.Dot(childOffset.normalized, parentT.normalized); if (Mathf.Abs(dot) < minDot) { minDot = Mathf.Abs(dot); closestPoint = childPos; closestArc = childArc; } } // Don't count the change if the dot product is too large, because this probably means // we went past the end of the arc segment. if (minDot > 0.3f) continue; // Write out the parameters for the circle in the child shell Vector3 closestTangent = FrameAlongHelix(child.curvature, child.torsion, closestArc).T; // Get the farthest point on the outside of the child shell Vector3 farthest = FarthestPointOnCircle(closestPoint, closestTangent, child.radius, parentPos); float requiredRadius = Vector3.Distance(farthest, parentPos); maxRequiredRadius = Mathf.Max(requiredRadius, maxRequiredRadius); } // Account for wall thickness maxRequiredRadius += Constants.WALL_THICKNESS; // Widen the parent so it contains the child shell. // However, don't ever decrease the thickness. parent.radius = Mathf.Max(parent.radius, maxRequiredRadius); } public static void growParentToChild(TelescopeParameters parent, TelescopeParameters child, bool shrinkFit=false) { // Compute the coordinates of the child's starting position, // in the parent's coordinate frame. Vector3 childBasePos = childBasePosition(parent, child); Quaternion childBaseRot = childBaseRotation(parent, child); Vector3 childOutward = childBaseRot * Vector3.down; // Compute the two inner corners of the child, when nested inside its // parent; these are the corners we want to bounds check. Vector3 retractedInner = childBasePos - (child.radius * childOutward); Vector3 retractedOuter = childBasePos + (child.radius * childOutward); // If the parent has no curvature, then the required width is just the // max absolute y value of the child. float finalRadius; if (parent.curvature < 1e-6) { finalRadius = Mathf.Max(Mathf.Abs(retractedInner.y), Mathf.Abs(retractedOuter.y)) + parent.thickness; if (!shrinkFit) finalRadius = Mathf.Max(finalRadius, parent.radius); } // Otherwise we need to compute the distance from the center line to the // corners, and take their max distance. else { // Fact: The centers of rotation for the parent and the extended child both lie // on the line (in the ZY plane) defined by the parent's center and its far face. float parentRadius = 1f / parent.curvature; Vector3 centerOfRotation = new Vector3(0, parentRadius, 0); // Now we can determine what width we need to 'fatten' the parent by. float innerDistance = Vector3.Distance(retractedInner, centerOfRotation); float outerDistance = Vector3.Distance(retractedOuter, centerOfRotation); float innerDiff = Mathf.Abs(innerDistance - parentRadius); float outerDiff = Mathf.Abs(outerDistance - parentRadius); finalRadius = Mathf.Max(innerDiff, outerDiff) + parent.thickness; if (!shrinkFit) finalRadius = Mathf.Max(finalRadius, parent.radius); } parent.radius = finalRadius; // parent.thickness += widthChange; } public static void growChainToFit(List<TelescopeParameters> parameters, bool shrinkFit = false) { // Make a pass in reverse that grows each parent so that it is large enough // to contain its child. for (int i = parameters.Count - 1; i > 0; i--) { if (parameters[i-1].torsion != 0 || parameters[i].torsion != 0) { TelescopeUtils.growParentToChildHelix(parameters[i - 1], parameters[i], shrinkFit); } else { TelescopeUtils.growParentToChild(parameters[i - 1], parameters[i], shrinkFit); } } } public static TelescopeParameters shrinkChildToParent(TelescopeParameters parent, TelescopeParameters child) { Debug.Log("Unimplemented"); return child; } public static float GeodesicDistanceOnSphere(float radius, Vector3 v1, Vector3 v2) { Vector3 n1 = v1.normalized; Vector3 n2 = v2.normalized; float dot = Vector3.Dot(n1, n2); float angle; if (dot > 0.9999f) angle = 0; else angle = Mathf.Acos(Vector3.Dot(n1, n2)); return radius * angle; } private static int BulbCount = 0; public static TelescopeBulb bulbOfRadius(Vector3 position, float radius) { GameObject sphereObj = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphereObj.transform.localScale = new Vector3(2 * radius, 2 * radius, 2 * radius); sphereObj.name = "bulbSphere" + BulbCount; GameObject bulbObj = new GameObject(); bulbObj.name = "bulb" + (BulbCount++); sphereObj.transform.parent = bulbObj.transform; TelescopeBulb bulb = bulbObj.AddComponent<TelescopeBulb>(); bulb.sphereObject = sphereObj; bulb.transform.position = position; bulb.SetMaterial(DesignerController.instance.defaultTelescopeMaterial); bulb.childSegments = new List<TelescopeSegment>(); return bulb; } public static float ArcLengthFromChord(Vector3 v1, Vector3 v2, float curvature) { float c = Vector3.Distance(v1, v2); // If there is no curvature, then return the straight segment. if (curvature < 1e-6) { return c; } float r = 1 / curvature; float theta = 2 * Mathf.Asin(c / (2 * r)); float arcLength = theta * r; return arcLength; } /// <summary> /// Compute the initial tangent to an arc of nonzero curvature, /// given the start point, end point, and center of rotation. /// </summary> /// <param name="parent"></param> /// <param name="child"></param> /// <param name="center"></param> /// <returns></returns> static Vector3 CurveDirectionFromParent(Vector3 parent, Vector3 child, Vector3 center) { Vector3 toParent = parent - center; Vector3 parentToChild = child - parent; toParent.Normalize(); Vector3 planeNormal = Vector3.Cross(toParent, parentToChild).normalized; Vector3 parentPerp = parentToChild - (Vector3.Dot(toParent, parentToChild)) * toParent; Vector3 inPlanePerp = parentPerp - (Vector3.Dot(planeNormal, parentPerp)) * planeNormal; return inPlanePerp.normalized; } public static TelescopeSegment telescopeOfCone(Vector3 startPos, float startRadius, Vector3 endPos, float endRadius, float wallThickness = Constants.WALL_THICKNESS) { return telescopeOfCone(startPos, startRadius, endPos, endRadius, Vector3.zero); } public static TelescopeSegment telescopeOfCone(Vector3 startPos, float startRadius, Vector3 endPos, float endRadius, Vector3 curvatureCenter, float wallThickness = Constants.WALL_THICKNESS, bool useCurvature = false) { float curvature; Vector3 segmentDirection; if (useCurvature) { float radius = Vector3.Distance(curvatureCenter, startPos); curvature = 1f / radius; if (curvature < 1e-6) { curvature = 0; segmentDirection = endPos - startPos; segmentDirection.Normalize(); } else { segmentDirection = CurveDirectionFromParent(startPos, endPos, curvatureCenter); } } else { curvature = 0; segmentDirection = endPos - startPos; segmentDirection.Normalize(); } float distance = ArcLengthFromChord(startPos, endPos, curvature); int numShells = Mathf.CeilToInt((Mathf.Max(startRadius, endRadius) - Mathf.Min(startRadius, endRadius)) / wallThickness); if (numShells < 2) numShells = 2; // int numShells = Mathf.CeilToInt(distance / Mathf.Min(startRadius, endRadius)); // Length is just the distance we need to cover divided by the number of shells. float lengthPerShell = distance / numShells; // We attempt to choose the radii such that the telescope tapers from the start // radius to the end radius over the given number of shells. float radiusStep = (startRadius - endRadius) / numShells; float twist = 0; if (curvature >= 1e-6) { // Compute twist angles Quaternion rotationToOrigin = Quaternion.FromToRotation(Vector3.forward, segmentDirection); // The "up" direction we would like to have -- orthogonal direction from circle center. Vector3 startEnd = endPos - startPos; Vector3 desiredUp = startEnd - Vector3.Dot(segmentDirection, startEnd) * segmentDirection; desiredUp.Normalize(); Vector3 inverseDesired = Quaternion.Inverse(rotationToOrigin) * desiredUp; // The angle computation doesn't work right in 3rd and 4th quadrants, // so work around it by doing everything in 1st and 2nd. if (inverseDesired.x < 0) { inverseDesired *= -1; twist = 180; } float angleBetween = Mathf.Atan2(Vector3.Cross(Vector3.up, inverseDesired).magnitude, Vector3.Dot(Vector3.up, inverseDesired)); twist += -angleBetween * Mathf.Rad2Deg; } List<TelescopeParameters> diffList = new List<TelescopeParameters>(); // Create the initial shell parameters. TelescopeParameters initialParams = new TelescopeParameters(lengthPerShell, startRadius, wallThickness, curvature, 0, twist); diffList.Add(initialParams); // Create all the diffs. for (int i = 1; i < numShells; i++) { TelescopeParameters tp = new TelescopeParameters(0, -radiusStep, wallThickness, 0, 0, 0); diffList.Add(tp); } // Create a game object that will be the new segment. GameObject obj = new GameObject(); obj.name = "segment" + segmentCount; segmentCount++; obj.transform.position = startPos; TelescopeSegment seg = obj.AddComponent<TelescopeSegment>(); seg.material = DesignerController.instance.defaultTelescopeMaterial; seg.initialDirection = segmentDirection; seg.MakeShellsFromDiffs(diffList); seg.transform.position = startPos; return seg; } public static float CircleIntersectionArea(float dist, float radius1, float radius2) { float r = Mathf.Min(radius1, radius2); float R = Mathf.Max(radius1, radius2); if (dist >= r + R) return 0; else if (dist <= R - r) { return Mathf.PI * r * r; } float d2 = dist * dist; float R2 = R * R; float r2 = r * r; // Formula from http://jwilson.coe.uga.edu/EMAT6680Su12/Carreras/EMAT6690/Essay2/essay2.html float sector1 = R2 * Mathf.Acos(dist / (2 * R)) - (dist / 4) * Mathf.Sqrt(4 * R2 - d2); float sector2 = r2 * Mathf.Acos(dist / (2 * r)) - (dist / 4) * Mathf.Sqrt(4 * r2 - d2); return sector1 + sector2; } public static float CircleIntersectionArea(Vector3 center1, float radius1, Vector3 center2, float radius2) { float dist = Vector3.Distance(center1, center2); return CircleIntersectionArea(dist, radius1, radius2); } public static bool IsColinear(Vector3 pt1, Vector3 pt2, Vector3 pt3) { Vector3 v1 = pt2 - pt1; Vector3 v2 = pt3 - pt2; v1.Normalize(); v2.Normalize(); float dot = Vector3.Dot(v1, v2); return (Mathf.Abs(dot) > 0.9999f); } public static Vector3 Circumcenter(Vector3 pt1, Vector3 pt2, Vector3 pt3) { // Get the perpendicular bisector of pt1, pt2 Vector3 v12 = pt2 - pt1; Vector3 v12normalized = v12.normalized; Vector3 v13 = pt3 - pt1; Vector3 v13normalized = v13.normalized; Vector3 v12perp = v13 - (Vector3.Dot(v13, v12normalized)) * v12normalized; v12perp.Normalize(); // Get the perpendicular bisector of pt1, pt3 Vector3 v13perp = v12 - (Vector3.Dot(v12, v13normalized)) * v13normalized; v13perp.Normalize(); Vector3 v12base = (pt1 + pt2) / 2; Vector3 v13base = (pt1 + pt3) / 2; // Compute intersection of the two bisectors Vector3 closest1, closest2; Math3d.ClosestPointsOnTwoLines(out closest1, out closest2, v12base, v12perp, v13base, v13perp); return (closest1 + closest2) / 2; } static List<GameObject> displayedPoints = new List<GameObject>(); public static void DisplayPoint(Vector3 point) { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.transform.position = point; sphere.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); displayedPoints.Add(sphere); MeshRenderer renderer = sphere.GetComponent<MeshRenderer>(); renderer.material.color = Color.blue; } public static void ClearDisplayedPoints() { foreach (GameObject o in displayedPoints) { GameObject.Destroy(o); } displayedPoints.Clear(); } public static void DisplayLine(List<Vector3> linePoints) { GameObject sampledPoints = new GameObject(); sampledPoints.name = "points"; LineRenderer sampledLine = sampledPoints.AddComponent<LineRenderer>(); sampledLine.material = DesignerController.instance.defaultLineMaterial; sampledLine.SetVertexCount(linePoints.Count); sampledLine.SetPositions(linePoints.ToArray()); sampledLine.SetColors(Color.red, Color.red); sampledLine.SetWidth(0.1f, 0.1f); } } }
42.58006
137
0.57858
[ "MIT" ]
icethrush/telescoping-structures
Assets/Scripts/TelescopeUtils.cs
28,190
C#
namespace OpenORPG.Toolkit.Views.Content { partial class MonsterEditorForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textDescription = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.numericExperience = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.numericLevel = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textName = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.spriteSelectControl1 = new OpenORPG.Toolkit.Controls.SpriteSelectControl(); this.label4 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.textNotes = new System.Windows.Forms.TextBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.attributeListControl1 = new OpenORPG.Toolkit.Controls.AttributeListControl(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericExperience)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericLevel)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // textDescription // this.textDescription.Location = new System.Drawing.Point(47, 80); this.textDescription.Multiline = true; this.textDescription.Name = "textDescription"; this.textDescription.Size = new System.Drawing.Size(270, 48); this.textDescription.TabIndex = 13; // // groupBox2 // this.groupBox2.Controls.Add(this.numericExperience); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Location = new System.Drawing.Point(12, 284); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(366, 90); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "Rewards"; // // numericExperience // this.numericExperience.Location = new System.Drawing.Point(72, 27); this.numericExperience.Name = "numericExperience"; this.numericExperience.Size = new System.Drawing.Size(245, 20); this.numericExperience.TabIndex = 10; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 29); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(60, 13); this.label3.TabIndex = 4; this.label3.Text = "Experience"; // // numericLevel // this.numericLevel.Location = new System.Drawing.Point(47, 48); this.numericLevel.Name = "numericLevel"; this.numericLevel.Size = new System.Drawing.Size(270, 20); this.numericLevel.TabIndex = 16; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(7, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(33, 13); this.label1.TabIndex = 15; this.label1.Text = "Level"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(35, 13); this.label2.TabIndex = 14; this.label2.Text = "Desc."; // // groupBox1 // this.groupBox1.Controls.Add(this.numericLevel); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textDescription); this.groupBox1.Controls.Add(this.textName); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.spriteSelectControl1); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(366, 266); this.groupBox1.TabIndex = 16; this.groupBox1.TabStop = false; this.groupBox1.Text = "General Settings"; // // textName // this.textName.Location = new System.Drawing.Point(47, 16); this.textName.Name = "textName"; this.textName.Size = new System.Drawing.Size(270, 20); this.textName.TabIndex = 12; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(7, 127); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(34, 13); this.label6.TabIndex = 11; this.label6.Text = "Sprite"; // // spriteSelectControl1 // this.spriteSelectControl1.Location = new System.Drawing.Point(9, 143); this.spriteSelectControl1.Name = "spriteSelectControl1"; this.spriteSelectControl1.Size = new System.Drawing.Size(214, 117); this.spriteSelectControl1.TabIndex = 10; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 19); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(35, 13); this.label4.TabIndex = 5; this.label4.Text = "Name"; // // groupBox3 // this.groupBox3.Controls.Add(this.textNotes); this.groupBox3.Location = new System.Drawing.Point(721, 12); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(233, 362); this.groupBox3.TabIndex = 18; this.groupBox3.TabStop = false; this.groupBox3.Text = "Notes"; // // textNotes // this.textNotes.Dock = System.Windows.Forms.DockStyle.Fill; this.textNotes.Location = new System.Drawing.Point(3, 16); this.textNotes.Multiline = true; this.textNotes.Name = "textNotes"; this.textNotes.Size = new System.Drawing.Size(227, 343); this.textNotes.TabIndex = 8; // // groupBox4 // this.groupBox4.Controls.Add(this.attributeListControl1); this.groupBox4.Location = new System.Drawing.Point(384, 12); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(331, 362); this.groupBox4.TabIndex = 19; this.groupBox4.TabStop = false; this.groupBox4.Text = "Attributes"; // // attributeListControl1 // this.attributeListControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.attributeListControl1.Location = new System.Drawing.Point(3, 16); this.attributeListControl1.Name = "attributeListControl1"; this.attributeListControl1.Size = new System.Drawing.Size(325, 343); this.attributeListControl1.TabIndex = 0; this.panel1.Controls.Add(this.groupBox1); this.panel1.Controls.Add(this.groupBox2); this.panel1.Controls.Add(this.groupBox3); this.panel1.Controls.Add(this.groupBox4); // // MonsterEditorForm // this.ClientSize = new System.Drawing.Size(974, 431); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "MonsterEditorForm"; this.Text = "Edit Monster"; this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericExperience)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericLevel)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.NumericUpDown numericExperience; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.NumericUpDown numericLevel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textDescription; private System.Windows.Forms.TextBox textName; private System.Windows.Forms.Label label6; private Controls.SpriteSelectControl spriteSelectControl1; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TextBox textNotes; private System.Windows.Forms.GroupBox groupBox4; private Controls.AttributeListControl attributeListControl1; } }
44.156
161
0.582571
[ "MIT" ]
hilts-vaughan/OpenORPG
OpenORPG.Toolkit/Views/Content/MonsterEditorForm.Designer.cs
11,041
C#
using Elsa.Mediator.Middleware.Notification.Contracts; using Microsoft.Extensions.DependencyInjection; namespace Elsa.Mediator.Middleware.Notification; public static class MiddlewareExtensions { public static INotificationPipelineBuilder UseMiddleware<TMiddleware>(this INotificationPipelineBuilder builder, params object[] args) where TMiddleware: INotificationMiddleware { var middleware = typeof(TMiddleware); return builder.Use(next => { var invokeMethod = MiddlewareHelpers.GetInvokeMethod(middleware); var ctorParams = new[] { next }.Concat(args).Select(x => x!).ToArray(); var instance = ActivatorUtilities.CreateInstance(builder.ApplicationServices, middleware, ctorParams); return (NotificationMiddlewareDelegate)invokeMethod.CreateDelegate(typeof(NotificationMiddlewareDelegate), instance); }); } }
45.15
181
0.748616
[ "MIT" ]
elsa-workflows/experimental
src/core/Elsa.Mediator/Middleware/Notification/MiddlewareExtensions.cs
903
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Oci.Database.Outputs { [OutputType] public sealed class KeyStoreAssociatedDatabase { /// <summary> /// The name of the database that is associated with the key store. /// </summary> public readonly string? DbName; /// <summary> /// The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the key store. /// </summary> public readonly string? Id; [OutputConstructor] private KeyStoreAssociatedDatabase( string? dbName, string? id) { DbName = dbName; Id = id; } } }
27.611111
117
0.622736
[ "ECL-2.0", "Apache-2.0" ]
EladGabay/pulumi-oci
sdk/dotnet/Database/Outputs/KeyStoreAssociatedDatabase.cs
994
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07-Lower-Or-Upper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07-Lower-Or-Upper")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9f89f111-ae88-4c22-9e83-73a53f2f47ff")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.891892
84
0.745364
[ "Apache-2.0" ]
KostadinovK/Technology-Fundamentals
03-Data-Types-And-Variables/Homework/07-Lower-Or-Upper/Properties/AssemblyInfo.cs
1,405
C#
namespace Caliburn.Micro.HelloWP7 { public class PivotPageModelStorage : StorageHandler<PivotPageViewModel> { public override void Configure() { this.ActiveItemIndex() .InPhoneState() .RestoreAfterViewLoad(); } } }
32.333333
78
0.591065
[ "MIT" ]
anaisbetts/CaliburnMicro
samples/Caliburn.Micro.HelloWP7/Caliburn.Micro.HelloWP7/PivotPageModelStorage.cs
293
C#
namespace Silence.Simulation { /// <summary> /// The mouse button /// </summary> public enum MouseButton { /// <summary> /// Left mouse button /// </summary> LeftButton, /// <summary> /// Middle mouse button /// </summary> MiddleButton, /// <summary> /// Right moust button /// </summary> RightButton, } }
18.608696
31
0.462617
[ "MIT" ]
MisterDr/silence
Silence.Simulation/MouseButton.cs
430
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; using System.Threading; namespace Plan.Domain { // Generated 07/26/2013 00:00:42 // Add custom code inside partial class public partial class Entity<T> where T : Entity<T>, new() { } }
17.315789
61
0.729483
[ "MIT" ]
kiapanahi/famous-design-patterns
Plan/Plan.Domain/Domain/Entity.partial.cs
329
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cloud : MonoBehaviour { // Use this for initialization void Start () { transform.position = new Vector3(Random.Range(-9f, 9f), Random.Range(4.2f, 3f), transform.position.z); } // Update is called once per frame void FixedUpdate () { transform.position = new Vector3(transform.position.x - 0.01f, transform.position.y, transform.position.z); if(transform.position.x < -9){ transform.position = new Vector3(9f, Random.Range(4.2f, 3f), transform.position.z); } } }
28.8
109
0.720486
[ "MIT" ]
jlawcordova/Baho-Kog-Ahem
Assets/Scripts/Cloud.cs
578
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Helpers { using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using StyleCop.Analyzers.Settings.ObjectModel; /// <summary> /// Class containing the extension methods for the <see cref="UsingDirectiveSyntax"/> class. /// </summary> internal static class UsingDirectiveSyntaxHelpers { private const string SystemUsingDirectiveIdentifier = nameof(System); /// <summary> /// Check if <see cref="UsingDirectiveSyntax"/> is system using directive. /// </summary> /// <param name="usingDirective">The <see cref="UsingDirectiveSyntax"/> that will be checked.</param> /// <returns>Return true if the <see cref="UsingDirectiveSyntax"/>is system using directive, otherwise false.</returns> internal static bool IsSystemUsingDirective(this UsingDirectiveSyntax usingDirective) => string.Equals(SystemUsingDirectiveIdentifier, GetFirstIdentifierInUsingDirective(usingDirective)?.ValueText, StringComparison.Ordinal); /// <summary> /// Check if <see cref="UsingDirectiveSyntax"/> is preceded by a preprocessor directive. /// </summary> /// <param name="usingDirective">The using directive.</param> /// <returns>True if the <see cref="UsingDirectiveSyntax"/> is preceded by a preprocessor directive, otherwise false.</returns> internal static bool IsPrecededByPreprocessorDirective(this UsingDirectiveSyntax usingDirective) { if (!usingDirective.HasLeadingTrivia) { return false; } foreach (var trivia in usingDirective.GetLeadingTrivia()) { if (trivia.IsDirective) { return true; } } return false; } /// <summary> /// Check if the name of using directive contains a namespace alias qualifier. /// </summary> /// <param name="usingDirective">The <see cref="UsingDirectiveSyntax"/> that will be checked.</param> /// <returns> /// <see langword="true"/> if the <see cref="UsingDirectiveSyntax"/> contains a namespace alias qualifier; /// otherwise, <see langword="false"/>. /// </returns> internal static bool HasNamespaceAliasQualifier(this UsingDirectiveSyntax usingDirective) => usingDirective.DescendantNodes().Any(node => node.IsKind(SyntaxKind.AliasQualifiedName)); /// <summary> /// Get the <see cref="UsingGroup"/> for the give using directive. /// </summary> /// <param name="usingDirective">The <see cref="UsingDirectiveSyntax"/> that will be used.</param> /// <param name="settings">The <see cref="StyleCopSettings"/> that will be used.</param> /// <returns>The <see cref="UsingGroup"/> for the given <paramref name="usingDirective"/>.</returns> internal static UsingGroup GetUsingGroupType(this UsingDirectiveSyntax usingDirective, StyleCopSettings settings) { if (usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) { return UsingGroup.Static; } if (usingDirective.Alias != null) { return UsingGroup.Alias; } if (settings.OrderingRules.SystemUsingDirectivesFirst && usingDirective.IsSystemUsingDirective()) { return UsingGroup.System; } return UsingGroup.Regular; } /// <summary> /// Checks if the Name part of the given using directive starts with an alias. /// </summary> /// <param name="usingDirective">The <see cref="UsingDirectiveSyntax"/> that will be used.</param> /// <param name="semanticModel">The <see cref="SemanticModel"/> that will be used.</param> /// <param name="cancellationToken">The cancellation token that can be used to interrupt the operation.</param> /// <returns>True if the name part of the using directive starts with an alias.</returns> internal static bool StartsWithAlias(this UsingDirectiveSyntax usingDirective, SemanticModel semanticModel, CancellationToken cancellationToken) { var firstPart = usingDirective.Name.DescendantNodes().FirstOrDefault() ?? usingDirective.Name; return semanticModel.GetAliasInfo(firstPart, cancellationToken) != null; } private static bool ExcludeGlobalKeyword(IdentifierNameSyntax token) => !token.Identifier.IsKind(SyntaxKind.GlobalKeyword); private static SyntaxToken? GetFirstIdentifierInUsingDirective(UsingDirectiveSyntax usingDirective) { foreach (var identifier in usingDirective.DescendantNodes()) { if (identifier is IdentifierNameSyntax identifierName && ExcludeGlobalKeyword(identifierName)) { return identifierName.Identifier; } } return null; } } }
45.872881
232
0.643451
[ "Apache-2.0" ]
Andreyul/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/Helpers/UsingDirectiveSyntaxHelpers.cs
5,415
C#
using System; static class Crash { static X GetFoo () { return null; } static int Main () { int res = (GetFoo ()?.ToLower ()).ToUpper (); if (res != 0) return 1; return 0; } } class X { public Y ToLower () { throw new ApplicationException ("should not be called"); } } class Y { } static class SS { public static int ToUpper (this Y y) { if (y != null) return 1; return 0; } }
10.121951
58
0.583133
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/tests/test-null-operator-13.cs
415
C#
using System; namespace TableClothKernel { public class InputProcessor { readonly Parser _parser; readonly Solution _solution; public InputProcessor( Solution solution ) { _solution = solution; _parser = new Parser(); _parser.Errors.Message += MessagesDispatcher; } public RequestResult Process( string input ) { var result = new RequestResult(); try { ProcessWithExceptions( input, result ); result.Success = true; } catch ( TcException exception ) { TcDebug.Log( String.Format( "Error in line {0} in column {1} : {2}", exception.TcData.Line, exception.TcData.Column, exception.TcData.Text ) ); result.Exception = exception; } catch { } return result; } void ProcessWithExceptions( string input, RequestResult result ) { result.Input = Parse( input ); foreach ( var command in result.Input.Commands ) { ValidateCommand( command ); var commandResult = ProcessCommand( command ); result.Output.Add( commandResult ); } } void ValidateCommand( Command command ) { command.Validate(); } RequestResult.CommandResult ProcessCommand( Command cmd ) { return _solution.Commands.Process( cmd ); } void MessagesDispatcher( ParserErrors.Data data ) { if ( data.Type == ParserErrors.EType.SyntaxError ) { throw new TcException( data ); } } UserInput Parse( string s ) { _parser.Parse( new Scanner( s ) ); return _parser.ParseResult; } } }
20.024691
72
0.616523
[ "MIT" ]
lis355/TableCloth
Source/TCKernel/Base Classes/Solution/InputProcessor.cs
1,624
C#
// hardcodet.net NotifyIcon for WPF // Copyright (c) 2009 - 2013 Philipp Sumi // Contact and Information: http://www.hardcodet.net // // This library is free software; you can redistribute it and/or // modify it under the terms of the Code Project Open License (CPOL); // either version 1.0 of the License, or (at your option) any later // version. // // 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. // // THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE namespace Hardcodet.Wpf.TaskbarNotification { ///<summary> /// Supported icons for the tray's balloon messages. ///</summary> public enum BalloonIcon { /// <summary> /// The balloon message is displayed without an icon. /// </summary> None, /// <summary> /// An information is displayed. /// </summary> Info, /// <summary> /// A warning is displayed. /// </summary> Warning, /// <summary> /// An error is displayed. /// </summary> Error } }
31.442308
69
0.655657
[ "MIT" ]
HavenDV/H.NotifyIcon.WPF
src/libs/H.NotifyIcon/BalloonIcon.cs
1,637
C#
/* Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a> 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.Data; using System.Linq; using Utilities.ORM.BaseClasses; using Utilities.ORM.Interfaces; using Utilities.ORM.Manager.Aspect.Interfaces; using Xunit; namespace UnitTests.ORM.Manager { public class SessionUsingComposition : DatabaseBaseClass { public SessionUsingComposition() { var BootLoader = Utilities.IoC.Manager.Bootstrapper; new Utilities.ORM.Manager.ORMManager(Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Mapper.Manager>(), Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.QueryProvider.Manager>(), Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Schema.Manager>(), Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.SourceProvider.Manager>(), Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()); } public enum TestEnum { Value1 = 0, Value2, Value3 } [Fact] public void All() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } IEnumerable<TestClass2> ItemList = TestObject.All<TestClass2>(); Assert.Equal(100, ItemList.Count()); foreach (TestClass2 Item in ItemList) { Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } } [Fact] public void Any() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } TestClass2 Item = TestObject.Any<TestClass2>(); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Item = TestObject.Any<TestClass2>(new Utilities.ORM.Parameters.EqualParameter<int>(1000, "ID_")); Assert.Null(Item); Item = TestObject.Any<TestClass2>(new Utilities.ORM.Parameters.EqualParameter<int>(10, "ID_")); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Assert.Equal(10, Item.ID); Item = TestObject.Any<TestClass2>(new Utilities.ORM.Parameters.EqualParameter<int>(20, "ID_")); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Assert.Equal(20, Item.ID); } [Fact] public void AnyByID() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } TestClass2 Item = TestObject.Any<TestClass2, int>(10); Assert.Equal(10, Item.ID); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Item = TestObject.Any<TestClass2, int>(20); Assert.Equal(20, Item.ID); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } [Fact] public void Create() { new Utilities.ORM.Manager.Session(); } [Fact] public void Delete() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } TestObject.Delete(TestObject.Any<TestClass2>()); IEnumerable<TestClass2> ItemList = TestObject.All<TestClass2>(); Assert.Equal(99, ItemList.Count()); } public override void Dispose() { base.Dispose(); var Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(MasterDatabaseSource); try { Temp.AddCommand(null, null, CommandType.Text, "ALTER DATABASE SessionUsingComposition SET OFFLINE WITH ROLLBACK IMMEDIATE") .AddCommand(null, null, CommandType.Text, "ALTER DATABASE SessionUsingComposition SET ONLINE") .AddCommand(null, null, CommandType.Text, "DROP DATABASE SessionUsingComposition") .Execute(); } catch { } } [Fact] public void PageCount() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } Assert.Equal(4, TestObject.PageCount<TestClass2>()); } [Fact] public void Paged() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); for (int x = 0; x < 100; ++x) { var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); } IEnumerable<TestClass2> ItemList = TestObject.Paged<TestClass2>(); Assert.Equal(25, ItemList.Count()); foreach (TestClass2 Item in ItemList) { Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } ItemList = TestObject.Paged<TestClass2>(CurrentPage: 1); Assert.Equal(25, ItemList.Count()); foreach (TestClass2 Item in ItemList) { Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } ItemList = TestObject.Paged<TestClass2>(CurrentPage: 2); Assert.Equal(25, ItemList.Count()); foreach (TestClass2 Item in ItemList) { Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } ItemList = TestObject.Paged<TestClass2>(CurrentPage: 3); Assert.Equal(25, ItemList.Count()); foreach (TestClass2 Item in ItemList) { Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } ItemList = TestObject.Paged<TestClass2>(CurrentPage: 4); Assert.Equal(0, ItemList.Count()); } [Fact] public void Save() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.ManyToManyIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2() }; TempObject.ManyToManyList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToOneIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2(), new TestClass2() }; TempObject.ManyToOneItem = new TestClass2(); TempObject.ManyToOneList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.Map = new TestClass2(); TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); Assert.Equal(true, TempObject.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, TempObject.ByteArrayReference); Assert.Equal(12, TempObject.ByteReference); Assert.Equal('v', TempObject.CharReference); Assert.Equal(1.4213m, TempObject.DecimalReference); Assert.Equal(1.32645d, TempObject.DoubleReference); Assert.Equal(TestEnum.Value2, TempObject.EnumReference); Assert.Equal(1234.5f, TempObject.FloatReference); Assert.Equal(TempGuid, TempObject.GuidReference); Assert.Equal(145145, TempObject.IntReference); Assert.Equal(763421, TempObject.LongReference); Assert.Equal(2, TempObject.ManyToManyIEnumerable.Count()); Assert.Equal(3, TempObject.ManyToManyList.Count); Assert.Equal(3, TempObject.ManyToOneIEnumerable.Count()); Assert.NotNull(TempObject.ManyToOneItem); Assert.Equal(3, TempObject.ManyToOneList.Count); Assert.NotNull(TempObject.Map); Assert.Equal(null, TempObject.NullStringReference); Assert.Equal(5423, TempObject.ShortReference); Assert.Equal("agsdpghasdg", TempObject.StringReference); var Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(new Utilities.ORM.Manager.SourceProvider.Manager(Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()).GetSource("Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false")); IList<dynamic> Items = Temp.AddCommand(null, null, CommandType.Text, "SELECT * FROM TestClass2_").Execute().First(); TestClass2 Item = Items.FirstOrDefault(x => x.BoolReference_); ((IORMObject)Item).Session0 = new Utilities.ORM.Manager.Session(); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(2, Item.ManyToManyIEnumerable.Count()); Assert.Equal(3, Item.ManyToManyList.Count); Assert.Equal(3, Item.ManyToOneIEnumerable.Count()); Assert.NotNull(Item.ManyToOneItem); Assert.Equal(3, Item.ManyToOneList.Count); Assert.NotNull(Item.Map); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); } [Fact] public void Update() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.ManyToManyIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2() }; TempObject.ManyToManyList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToOneIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2(), new TestClass2() }; TempObject.ManyToOneItem = new TestClass2(); TempObject.ManyToOneList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.Map = new TestClass2(); TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); Assert.Equal(true, TempObject.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, TempObject.ByteArrayReference); Assert.Equal(12, TempObject.ByteReference); Assert.Equal('v', TempObject.CharReference); Assert.Equal(1.4213m, TempObject.DecimalReference); Assert.Equal(1.32645d, TempObject.DoubleReference); Assert.Equal(TestEnum.Value2, TempObject.EnumReference); Assert.Equal(1234.5f, TempObject.FloatReference); Assert.Equal(TempGuid, TempObject.GuidReference); Assert.Equal(145145, TempObject.IntReference); Assert.Equal(763421, TempObject.LongReference); Assert.Equal(2, TempObject.ManyToManyIEnumerable.Count()); Assert.Equal(3, TempObject.ManyToManyList.Count); Assert.Equal(3, TempObject.ManyToOneIEnumerable.Count()); Assert.NotNull(TempObject.ManyToOneItem); Assert.Equal(3, TempObject.ManyToOneList.Count); Assert.NotNull(TempObject.Map); Assert.Equal(null, TempObject.NullStringReference); Assert.Equal(5423, TempObject.ShortReference); Assert.Equal("agsdpghasdg", TempObject.StringReference); var Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(new Utilities.ORM.Manager.SourceProvider.Manager(Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()).GetSource("Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false")); IList<dynamic> Items = Temp.AddCommand(null, null, CommandType.Text, "SELECT * FROM TestClass2_").Execute().First(); TestClass2 Item = Items.FirstOrDefault(x => x.BoolReference_); ((IORMObject)Item).Session0 = new Utilities.ORM.Manager.Session(); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(2, Item.ManyToManyIEnumerable.Count()); Assert.Equal(3, Item.ManyToManyList.Count); Assert.Equal(3, Item.ManyToOneIEnumerable.Count()); Assert.NotNull(Item.ManyToOneItem); Assert.Equal(3, Item.ManyToOneList.Count); Assert.NotNull(Item.Map); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Item.ByteArrayReference = new byte[] { 11, 12, 13, 14, 15, 16, 17, 18, 19, 110 }; Item.ByteReference = 121; Item.CharReference = 'V'; Item.DecimalReference = 11.4213m; Item.DoubleReference = 11.32645d; Item.EnumReference = TestEnum.Value3; Item.FloatReference = 14.5f; Item.IntReference = 1451445; Item.LongReference = 7634121; Item.ShortReference = 43; Item.StringReference = "Something"; TestObject.Save<TestClass2, int>(Item); Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(new Utilities.ORM.Manager.SourceProvider.Manager(Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()).GetSource("Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false")); Items = Temp.AddCommand(null, null, CommandType.Text, "SELECT * FROM TestClass2_").Execute().First(); Item = Items.FirstOrDefault(x => x.BoolReference_); ((IORMObject)Item).Session0 = new Utilities.ORM.Manager.Session(); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 11, 12, 13, 14, 15, 16, 17, 18, 19, 110 }, Item.ByteArrayReference); Assert.Equal(121, Item.ByteReference); Assert.Equal('V', Item.CharReference); Assert.Equal(11.4213m, Item.DecimalReference); Assert.Equal(11.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value3, Item.EnumReference); Assert.Equal(14.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(1451445, Item.IntReference); Assert.Equal(7634121, Item.LongReference); Assert.Equal(2, Item.ManyToManyIEnumerable.Count()); Assert.Equal(3, Item.ManyToManyList.Count); Assert.Equal(3, Item.ManyToOneIEnumerable.Count()); Assert.NotNull(Item.ManyToOneItem); Assert.Equal(3, Item.ManyToOneList.Count); Assert.NotNull(Item.Map); Assert.Equal(null, Item.NullStringReference); Assert.Equal(43, Item.ShortReference); Assert.Equal("Something", Item.StringReference); } [Fact] public void UpdateCascade() { Guid TempGuid = Guid.NewGuid(); var TestObject = new Utilities.ORM.Manager.Session(); var TempObject = new TestClass2(); TempObject.BoolReference = true; TempObject.ByteArrayReference = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; TempObject.ByteReference = 12; TempObject.CharReference = 'v'; TempObject.DecimalReference = 1.4213m; TempObject.DoubleReference = 1.32645d; TempObject.EnumReference = TestEnum.Value2; TempObject.FloatReference = 1234.5f; TempObject.GuidReference = TempGuid; TempObject.IntReference = 145145; TempObject.LongReference = 763421; TempObject.ManyToManyIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2() }; TempObject.ManyToManyList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToOneIEnumerable = new TestClass2[] { new TestClass2(), new TestClass2(), new TestClass2() }; TempObject.ManyToOneItem = new TestClass2(); TempObject.ManyToOneList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToOneIList = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToManyIList = new ITestInterface[] { new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToOneICollection = new ITestInterface[] { new TestClass2(), new TestClass2(), new TestClass2(), new TestClass2() }.ToList(); TempObject.ManyToManyICollection = new ITestInterface[] { new TestClass2() }.ToList(); TempObject.Map = new TestClass2(); TempObject.NullStringReference = null; TempObject.ShortReference = 5423; TempObject.StringReference = "agsdpghasdg"; TestObject.Save<TestClass2, int>(TempObject); Assert.Equal(true, TempObject.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, TempObject.ByteArrayReference); Assert.Equal(12, TempObject.ByteReference); Assert.Equal('v', TempObject.CharReference); Assert.Equal(1.4213m, TempObject.DecimalReference); Assert.Equal(1.32645d, TempObject.DoubleReference); Assert.Equal(TestEnum.Value2, TempObject.EnumReference); Assert.Equal(1234.5f, TempObject.FloatReference); Assert.Equal(TempGuid, TempObject.GuidReference); Assert.Equal(145145, TempObject.IntReference); Assert.Equal(763421, TempObject.LongReference); Assert.Equal(2, TempObject.ManyToManyIEnumerable.Count()); Assert.Equal(3, TempObject.ManyToManyList.Count); Assert.Equal(3, TempObject.ManyToOneIEnumerable.Count()); Assert.NotNull(TempObject.ManyToOneItem); Assert.Equal(3, TempObject.ManyToOneList.Count); Assert.Equal(3, TempObject.ManyToOneIList.Count); Assert.Equal(2, TempObject.ManyToManyIList.Count); Assert.Equal(4, TempObject.ManyToOneICollection.Count); Assert.Equal(1, TempObject.ManyToManyICollection.Count); Assert.NotNull(TempObject.Map); Assert.Equal(null, TempObject.NullStringReference); Assert.Equal(5423, TempObject.ShortReference); Assert.Equal("agsdpghasdg", TempObject.StringReference); var Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(new Utilities.ORM.Manager.SourceProvider.Manager(Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()).GetSource("Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false")); IList<dynamic> Items = Temp.AddCommand(null, null, CommandType.Text, "SELECT * FROM TestClass2_").Execute().First(); TestClass2 Item = Items.FirstOrDefault(x => x.BoolReference_); ((IORMObject)Item).Session0 = new Utilities.ORM.Manager.Session(); Assert.Equal(true, Item.BoolReference); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, Item.ByteArrayReference); Assert.Equal(12, Item.ByteReference); Assert.Equal('v', Item.CharReference); Assert.Equal(1.4213m, Item.DecimalReference); Assert.Equal(1.32645d, Item.DoubleReference); Assert.Equal(TestEnum.Value2, Item.EnumReference); Assert.Equal(1234.5f, Item.FloatReference); Assert.Equal(TempGuid, Item.GuidReference); Assert.Equal(145145, Item.IntReference); Assert.Equal(763421, Item.LongReference); Assert.Equal(2, Item.ManyToManyIEnumerable.Count()); Assert.Equal(3, Item.ManyToManyList.Count); Assert.Equal(3, Item.ManyToOneIEnumerable.Count()); Assert.NotNull(Item.ManyToOneItem); Assert.Equal(3, Item.ManyToOneList.Count); Assert.NotNull(Item.Map); Assert.Equal(null, Item.NullStringReference); Assert.Equal(5423, Item.ShortReference); Assert.Equal("agsdpghasdg", Item.StringReference); Item.Map = new TestClass2 { FloatReference = 10f }; Item.ManyToManyIEnumerable.First().FloatReference = 11f; Item.ManyToManyList.Add(new TestClass2 { FloatReference = 12f }); Item.ManyToOneIEnumerable.First().FloatReference = 13f; Item.ManyToOneItem.FloatReference = 14f; Item.ManyToOneList = new ITestInterface[] { new TestClass2(), new TestClass2() }.ToList(); Item.ManyToManyIList.Add(new TestClass2 { FloatReference = 15f }); Item.ManyToOneIList.Add(new TestClass2 { FloatReference = 16f }); Item.ManyToManyICollection.Add(new TestClass2 { FloatReference = 17f }); Item.ManyToOneICollection.Add(new TestClass2 { FloatReference = 18f }); TestObject.Save<TestClass2, int>(Item); Temp = new Utilities.ORM.Manager.QueryProvider.Default.DatabaseBatch(new Utilities.ORM.Manager.SourceProvider.Manager(Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>()).GetSource("Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false")); Items = Temp.AddCommand(null, null, CommandType.Text, "SELECT * FROM TestClass2_").Execute().First(); Item = Items.FirstOrDefault(x => x.BoolReference_); ((IORMObject)Item).Session0 = new Utilities.ORM.Manager.Session(); Assert.Equal(10, Item.Map.FloatReference); Assert.Equal(11f, Item.ManyToManyIEnumerable.First().FloatReference); Assert.Equal(12f, Item.ManyToManyList.Last().FloatReference); Assert.Equal(13f, Item.ManyToOneIEnumerable.First().FloatReference); Assert.Equal(14f, Item.ManyToOneItem.FloatReference); Assert.Equal(15f, Item.ManyToManyIList.Last().FloatReference); Assert.Equal(16f, Item.ManyToOneIList.Last().FloatReference); Assert.Equal(17f, Item.ManyToManyICollection.Last().FloatReference); Assert.Equal(18f, Item.ManyToOneICollection.Last().FloatReference); Assert.Equal(2, Item.ManyToOneList.Count); } public interface ITestInterface { bool BoolReference { get; set; } byte[] ByteArrayReference { get; set; } byte ByteReference { get; set; } char CharReference { get; set; } decimal DecimalReference { get; set; } double DoubleReference { get; set; } TestEnum EnumReference { get; set; } float FloatReference { get; set; } Guid GuidReference { get; set; } int ID { get; set; } int IntReference { get; set; } long LongReference { get; set; } } public abstract class TestAbstractClass : ITestInterface { protected TestAbstractClass() { } public abstract bool BoolReference { get; set; } public abstract byte[] ByteArrayReference { get; set; } public abstract byte ByteReference { get; set; } public abstract char CharReference { get; set; } public abstract decimal DecimalReference { get; set; } public abstract double DoubleReference { get; set; } public abstract TestEnum EnumReference { get; set; } public abstract float FloatReference { get; set; } public abstract Guid GuidReference { get; set; } public abstract int ID { get; set; } public abstract int IntReference { get; set; } public abstract long LongReference { get; set; } public abstract ICollection<ITestInterface> ManyToManyICollection { get; set; } public abstract IEnumerable<ITestInterface> ManyToManyIEnumerable { get; set; } public abstract IList<ITestInterface> ManyToManyIList { get; set; } public abstract List<ITestInterface> ManyToManyList { get; set; } public abstract ICollection<ITestInterface> ManyToOneICollection { get; set; } public abstract IEnumerable<ITestInterface> ManyToOneIEnumerable { get; set; } public abstract IList<ITestInterface> ManyToOneIList { get; set; } public abstract ITestInterface ManyToOneItem { get; set; } public abstract List<ITestInterface> ManyToOneList { get; set; } public abstract ITestInterface Map { get; set; } } public class TestAbstractClassMapping : MappingBaseClass<TestAbstractClass, TestCompositionDatabase> { public TestAbstractClassMapping() { ID(x => x.ID); ManyToMany(x => x.ManyToManyIEnumerable).SetTableName("ManyToManyIEnumerable").SetCascade(); ManyToMany(x => x.ManyToManyList).SetTableName("ManyToManyList").SetCascade(); ManyToOne(x => x.ManyToOneIEnumerable).SetTableName("ManyToOneIEnumerable").SetCascade(); ManyToOne(x => x.ManyToOneList).SetTableName("ManyToOneList").SetCascade(); ManyToOne(x => x.ManyToOneItem).SetTableName("ManyToOneList").SetCascade(); ManyToOne(x => x.ManyToOneIList).SetTableName("ManyToOneIList").SetCascade(); ManyToMany(x => x.ManyToManyIList).SetTableName("ManyToManyIList").SetCascade(); ManyToOne(x => x.ManyToOneICollection).SetTableName("ManyToOneICollection").SetCascade(); ManyToMany(x => x.ManyToManyICollection).SetTableName("ManyToManyICollection").SetCascade(); Map(x => x.Map).SetCascade(); } } public class TestClass2 : TestAbstractClass { public override bool BoolReference { get; set; } public override byte[] ByteArrayReference { get; set; } public override byte ByteReference { get; set; } public override char CharReference { get; set; } public override decimal DecimalReference { get; set; } public override double DoubleReference { get; set; } public override TestEnum EnumReference { get; set; } public override float FloatReference { get; set; } public override Guid GuidReference { get; set; } public override int ID { get; set; } public override int IntReference { get; set; } public override long LongReference { get; set; } public override ICollection<ITestInterface> ManyToManyICollection { get; set; } public override IEnumerable<ITestInterface> ManyToManyIEnumerable { get; set; } public override IList<ITestInterface> ManyToManyIList { get; set; } public override List<ITestInterface> ManyToManyList { get; set; } public override ICollection<ITestInterface> ManyToOneICollection { get; set; } public override IEnumerable<ITestInterface> ManyToOneIEnumerable { get; set; } public override IList<ITestInterface> ManyToOneIList { get; set; } public override ITestInterface ManyToOneItem { get; set; } public override List<ITestInterface> ManyToOneList { get; set; } public override ITestInterface Map { get; set; } public string NullStringReference { get; set; } public short ShortReference { get; set; } public string StringReference { get; set; } } public class TestClass2Mapping : MappingBaseClass<TestClass2, TestCompositionDatabase> { public TestClass2Mapping() { ID(x => x.ID); Reference(x => x.NullStringReference).SetMaxLength(100); Reference(x => x.ShortReference); Reference(x => x.StringReference).SetMaxLength(100); } } public class TestCompositionDatabase : IDatabase { public bool Audit { get { return false; } } public string Name { get { return "Data Source=localhost;Initial Catalog=SessionUsingComposition;Integrated Security=SSPI;Pooling=false"; } } public int Order { get { return 0; } } public bool Readable { get { return true; } } public bool Update { get { return true; } } public bool Writable { get { return true; } } } public class TestInterfaceMapping : MappingBaseClass<ITestInterface, TestCompositionDatabase> { public TestInterfaceMapping() { ID(x => x.ID).SetAutoIncrement(); Reference(x => x.BoolReference); Reference(x => x.ByteArrayReference).SetMaxLength(100); Reference(x => x.ByteReference); Reference(x => x.CharReference); Reference(x => x.DecimalReference).SetMaxLength(8); Reference(x => x.DoubleReference); Reference(x => x.EnumReference); Reference(x => x.FloatReference); Reference(x => x.GuidReference); Reference(x => x.IntReference); Reference(x => x.LongReference); } } } }
53.135347
310
0.597962
[ "MIT" ]
sealong/Craig-s-Utility-Library
UnitTests/ORM/Manager/SessionUsingComposition.cs
47,505
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Game.Graphics; using osu.Game.Rulesets.Taiko.Objects.Drawables.Pieces; namespace osu.Game.Rulesets.Taiko.Objects.Drawables { public class DrawableCentreHit : DrawableHit { public override TaikoAction[] HitActions { get; } = { TaikoAction.LeftCentre, TaikoAction.RightCentre }; public DrawableCentreHit(Hit hit) : base(hit) { MainPiece.Add(new CentreHitSymbolPiece()); } [BackgroundDependencyLoader] private void load(OsuColour colours) { MainPiece.AccentColour = colours.PinkDarker; } } }
30.481481
113
0.651276
[ "MIT" ]
123tris/osu
osu.Game.Rulesets.Taiko/Objects/Drawables/DrawableCentreHit.cs
799
C#
namespace ParaInfo.Web.Settings { public class MongoDbSettings : IMongoDbSettings { public string DatabaseName { get; set; } public string ConnectionString { get; set; } } }
22.555556
52
0.660099
[ "Apache-2.0" ]
krum142/ParaInfo
Server/ParaInfoServer/Settings/MongoDBSettings.cs
205
C#
using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using BlazorProject.Backend.Roles.Dto; using BlazorProject.Backend.Users.Dto; namespace BlazorProject.Backend.Users { public interface IUserAppService : IAsyncCrudAppService<UserDto, long, PagedUserResultRequestDto, CreateUserDto, UserDto> { Task<ListResultDto<RoleDto>> GetRoles(); Task ChangeLanguage(ChangeUserLanguageDto input); } }
29.0625
125
0.782796
[ "MIT" ]
274188A/BlazorProjectASPBoilerplateBackend
aspnet-core/src/BlazorProject.Backend.Application/Users/IUserAppService.cs
465
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.IotData")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Data Plane. AWS IoT-Data enables secure, bi-directional communication between Internet-connected things (such as sensors, actuators, embedded devices, or smart appliances) and the AWS cloud. It implements a broker for applications and things to publish messages over HTTP (Publish) and retrieve, update, and delete thing shadows. A thing shadow is a persistent representation of your things and their state in the AWS cloud.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.28")]
55.40625
512
0.759729
[ "Apache-2.0" ]
augustoproiete-forks/aws--aws-sdk-net
sdk/code-analysis/ServiceAnalysis/IotData/Properties/AssemblyInfo.cs
1,773
C#
namespace _03.Mission_Private_Impossible___Lab { using System; using _03.Mission_Private_Impossible___Lab.Models; public class Startup { public static void Main() { Spy spy = new Spy(); string result = spy.RevealPrivateMethods("Hacker"); Console.WriteLine(result); } } }
22.0625
63
0.606232
[ "MIT" ]
alexandrateneva/CSharp-Fundamentals-SoftUni
CSharp OOP Advanced/Reflection/03. Mission Private Impossible - Lab/Startup.cs
355
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.ML; using Microsoft.ML.Data; namespace Samples.Dynamic.Trainers.Regression { public static class FastTreeTweedieRegression { // This example requires installation of additional NuGet // package for Microsoft.ML.FastTree found at // https://www.nuget.org/packages/Microsoft.ML.FastTree/ public static void Example() { // Create a new context for ML.NET operations. It can be used for // exception tracking and logging, as a catalog of available operations // and as the source of randomness. Setting the seed to a fixed number // in this example to make outputs deterministic. var mlContext = new MLContext(seed: 0); // Create a list of training data points. var dataPoints = GenerateRandomDataPoints(1000); // Convert the list of data points to an IDataView object, which is // consumable by ML.NET API. var trainingData = mlContext.Data.LoadFromEnumerable(dataPoints); // Define the trainer. var pipeline = mlContext.Regression.Trainers.FastForest( labelColumnName: nameof(DataPoint.Label), featureColumnName: nameof(DataPoint.Features)); // Train the model. var model = pipeline.Fit(trainingData); // Create testing data. Use different random seed to make it different // from training data. var testData = mlContext.Data.LoadFromEnumerable( GenerateRandomDataPoints(5, seed: 123)); // Run the model on test data set. var transformedTestData = model.Transform(testData); // Convert IDataView object to a list. var predictions = mlContext.Data.CreateEnumerable<Prediction>( transformedTestData, reuseRowObject: false).ToList(); // Look at 5 predictions for the Label, side by side with the actual // Label for comparison. foreach (var p in predictions) Console.WriteLine($"Label: {p.Label:F3}, Prediction: {p.Score:F3}"); // Expected output: // Label: 0.985, Prediction: 0.945 // Label: 0.155, Prediction: 0.104 // Label: 0.515, Prediction: 0.515 // Label: 0.566, Prediction: 0.448 // Label: 0.096, Prediction: 0.082 // Evaluate the overall metrics var metrics = mlContext.Regression.Evaluate(transformedTestData); PrintMetrics(metrics); // Expected output: // Mean Absolute Error: 0.04 // Mean Squared Error: 0.00 // Root Mean Squared Error: 0.06 // RSquared: 0.96 (closer to 1 is better. The worest case is 0) } private static IEnumerable<DataPoint> GenerateRandomDataPoints(int count, int seed=0) { var random = new Random(seed); for (int i = 0; i < count; i++) { float label = (float)random.NextDouble(); yield return new DataPoint { Label = label, // Create random features that are correlated with the label. Features = Enumerable.Repeat(label, 50).Select( x => x + (float)random.NextDouble()).ToArray() }; } } // Example with label and 50 feature values. A data set is a collection of // such examples. private class DataPoint { public float Label { get; set; } [VectorType(50)] public float[] Features { get; set; } } // Class used to capture predictions. private class Prediction { // Original label. public float Label { get; set; } // Predicted score from the trainer. public float Score { get; set; } } // Print some evaluation metrics to regression problems. private static void PrintMetrics(RegressionMetrics metrics) { Console.WriteLine("Mean Absolute Error: " + metrics.MeanAbsoluteError); Console.WriteLine("Mean Squared Error: " + metrics.MeanSquaredError); Console.WriteLine( "Root Mean Squared Error: " + metrics.RootMeanSquaredError); Console.WriteLine("RSquared: " + metrics.RSquared); } } }
38.458333
84
0.575081
[ "MIT" ]
AhmedsafwatEwida/machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/FastTreeTweedie.cs
4,617
C#
using Microsoft.Extensions.DependencyInjection.Extensions; using Rabble.EventBus.Abstractions; using Rabble.EventBus.InMemory; using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// /// </summary> public static class InMemoryEventBusServiceCollectionExtensions { /// <summary> /// 添加RabbitMQ实现的事件总线 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddInMemoryEventBus(this IServiceCollection services) { services.TryAddSingleton<IEventBus>(sp => { return new InMemoryEventBus(sp.CreateScope().ServiceProvider); }); return services; } } }
26.967742
94
0.638756
[ "MIT" ]
1015450578/EventBus
src/Rabble.EventBus.InMemory/InMemoryEventBusServiceCollectionExtensions.cs
856
C#
//---------------------- // <auto-generated> // Generated using the NJsonSchema v10.3.2.0 (Newtonsoft.Json v12.0.0.0) (http://NJsonSchema.org) // </auto-generated> //---------------------- namespace Redox.Ehr.Contracts.Models.Redox.Referral.Authresponse { #pragma warning disable // Disable all warnings [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Authresponse { [Newtonsoft.Json.JsonProperty("Meta", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] public Meta Meta { get; set; } = new Meta(); [Newtonsoft.Json.JsonProperty("Referral", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Referral Referral { get; set; } [Newtonsoft.Json.JsonProperty("Patient", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] public Patient Patient { get; set; } = new Patient(); private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Meta { [Newtonsoft.Json.JsonProperty("DataModel", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string DataModel { get; set; } [Newtonsoft.Json.JsonProperty("EventType", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string EventType { get; set; } [Newtonsoft.Json.JsonProperty("EventDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string EventDateTime { get; set; } [Newtonsoft.Json.JsonProperty("Test", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool? Test { get; set; } [Newtonsoft.Json.JsonProperty("Source", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Source Source { get; set; } [Newtonsoft.Json.JsonProperty("Destinations", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Destinations> Destinations { get; set; } [Newtonsoft.Json.JsonProperty("Message", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Message Message { get; set; } [Newtonsoft.Json.JsonProperty("Transmission", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Transmission Transmission { get; set; } [Newtonsoft.Json.JsonProperty("FacilityCode", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FacilityCode { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Referral { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("AlternateID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string AlternateID { get; set; } [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("Category", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Category { get; set; } [Newtonsoft.Json.JsonProperty("Priority", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Priority { get; set; } [Newtonsoft.Json.JsonProperty("Status", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Status { get; set; } [Newtonsoft.Json.JsonProperty("DateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DateTime { get; set; } [Newtonsoft.Json.JsonProperty("ExpirationDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExpirationDateTime { get; set; } [Newtonsoft.Json.JsonProperty("ProcessDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ProcessDateTime { get; set; } [Newtonsoft.Json.JsonProperty("Reason", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Reason { get; set; } [Newtonsoft.Json.JsonProperty("ProviderSpecialty", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ProviderSpecialty { get; set; } [Newtonsoft.Json.JsonProperty("DepartmentSpecialty", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DepartmentSpecialty { get; set; } [Newtonsoft.Json.JsonProperty("Notes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Notes { get; set; } [Newtonsoft.Json.JsonProperty("Authorization", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Authorization Authorization { get; set; } [Newtonsoft.Json.JsonProperty("Diagnoses", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Diagnoses> Diagnoses { get; set; } [Newtonsoft.Json.JsonProperty("Procedures", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Procedures> Procedures { get; set; } [Newtonsoft.Json.JsonProperty("Providers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Providers> Providers { get; set; } [Newtonsoft.Json.JsonProperty("Visit", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Visit Visit { get; set; } [Newtonsoft.Json.JsonProperty("ServiceLocation", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ServiceLocation { get; set; } [Newtonsoft.Json.JsonProperty("RequestType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RequestType { get; set; } [Newtonsoft.Json.JsonProperty("RelatedCause", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RelatedCause { get; set; } [Newtonsoft.Json.JsonProperty("StatusReason", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StatusReason { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Patient { [Newtonsoft.Json.JsonProperty("Identifiers", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] public System.Collections.Generic.ICollection<Identifiers> Identifiers { get; set; } = new System.Collections.ObjectModel.Collection<Identifiers>(); [Newtonsoft.Json.JsonProperty("Demographics", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Demographics Demographics { get; set; } [Newtonsoft.Json.JsonProperty("Notes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Notes { get; set; } [Newtonsoft.Json.JsonProperty("Contacts", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Contacts> Contacts { get; set; } [Newtonsoft.Json.JsonProperty("Guarantor", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Guarantor Guarantor { get; set; } [Newtonsoft.Json.JsonProperty("Insurances", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Insurances> Insurances { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Source { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Destinations { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Message { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public double? ID { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Transmission { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public double? ID { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Authorization { [Newtonsoft.Json.JsonProperty("Plan", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Plan Plan { get; set; } [Newtonsoft.Json.JsonProperty("Company", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Company Company { get; set; } [Newtonsoft.Json.JsonProperty("DateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DateTime { get; set; } [Newtonsoft.Json.JsonProperty("ExpirationDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExpirationDateTime { get; set; } [Newtonsoft.Json.JsonProperty("Number", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Number { get; set; } [Newtonsoft.Json.JsonProperty("ReimbursementLimit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ReimbursementLimit { get; set; } [Newtonsoft.Json.JsonProperty("RequestedTreatmentCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RequestedTreatmentCount { get; set; } [Newtonsoft.Json.JsonProperty("AuthorizedTreatmentCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string AuthorizedTreatmentCount { get; set; } [Newtonsoft.Json.JsonProperty("Notes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Notes { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Diagnoses { [Newtonsoft.Json.JsonProperty("Code", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Code { get; set; } [Newtonsoft.Json.JsonProperty("Codeset", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Codeset { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("DocumentedDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DocumentedDateTime { get; set; } [Newtonsoft.Json.JsonProperty("Notes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Notes { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Procedures { [Newtonsoft.Json.JsonProperty("Code", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Code { get; set; } [Newtonsoft.Json.JsonProperty("Codeset", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Codeset { get; set; } [Newtonsoft.Json.JsonProperty("Description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } [Newtonsoft.Json.JsonProperty("Notes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Notes { get; set; } [Newtonsoft.Json.JsonProperty("Quantity", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Quantity { get; set; } [Newtonsoft.Json.JsonProperty("Status", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Status { get; set; } [Newtonsoft.Json.JsonProperty("StatusReason", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StatusReason { get; set; } [Newtonsoft.Json.JsonProperty("Authorization", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Authorization2 Authorization { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Providers { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } [Newtonsoft.Json.JsonProperty("Credentials", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Credentials { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address Address { get; set; } [Newtonsoft.Json.JsonProperty("EmailAddresses", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> EmailAddresses { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public PhoneNumber PhoneNumber { get; set; } [Newtonsoft.Json.JsonProperty("Location", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Location Location { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Visit { [Newtonsoft.Json.JsonProperty("VisitNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string VisitNumber { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Identifiers { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string IDType { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Demographics { [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("MiddleName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MiddleName { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } [Newtonsoft.Json.JsonProperty("DOB", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DOB { get; set; } [Newtonsoft.Json.JsonProperty("SSN", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string SSN { get; set; } [Newtonsoft.Json.JsonProperty("Sex", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Sex { get; set; } [Newtonsoft.Json.JsonProperty("Race", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Race { get; set; } [Newtonsoft.Json.JsonProperty("IsHispanic", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool? IsHispanic { get; set; } [Newtonsoft.Json.JsonProperty("MaritalStatus", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MaritalStatus { get; set; } [Newtonsoft.Json.JsonProperty("IsDeceased", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool? IsDeceased { get; set; } [Newtonsoft.Json.JsonProperty("DeathDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DeathDateTime { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public PhoneNumber2 PhoneNumber { get; set; } [Newtonsoft.Json.JsonProperty("EmailAddresses", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> EmailAddresses { get; set; } [Newtonsoft.Json.JsonProperty("Language", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Language { get; set; } [Newtonsoft.Json.JsonProperty("Citizenship", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Citizenship { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address2 Address { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Contacts { [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("MiddleName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MiddleName { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address3 Address { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public PhoneNumber3 PhoneNumber { get; set; } [Newtonsoft.Json.JsonProperty("RelationToPatient", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RelationToPatient { get; set; } [Newtonsoft.Json.JsonProperty("EmailAddresses", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> EmailAddresses { get; set; } [Newtonsoft.Json.JsonProperty("Roles", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> Roles { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Guarantor { [Newtonsoft.Json.JsonProperty("Number", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Number { get; set; } [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("MiddleName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MiddleName { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } [Newtonsoft.Json.JsonProperty("SSN", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string SSN { get; set; } [Newtonsoft.Json.JsonProperty("DOB", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DOB { get; set; } [Newtonsoft.Json.JsonProperty("Sex", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Sex { get; set; } [Newtonsoft.Json.JsonProperty("Spouse", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Spouse Spouse { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address4 Address { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public PhoneNumber4 PhoneNumber { get; set; } [Newtonsoft.Json.JsonProperty("EmailAddresses", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<object> EmailAddresses { get; set; } [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("RelationToPatient", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RelationToPatient { get; set; } [Newtonsoft.Json.JsonProperty("Employer", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Employer Employer { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Insurances { [Newtonsoft.Json.JsonProperty("Plan", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Plan2 Plan { get; set; } [Newtonsoft.Json.JsonProperty("MemberNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MemberNumber { get; set; } [Newtonsoft.Json.JsonProperty("Company", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Company2 Company { get; set; } [Newtonsoft.Json.JsonProperty("GroupNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string GroupNumber { get; set; } [Newtonsoft.Json.JsonProperty("GroupName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string GroupName { get; set; } [Newtonsoft.Json.JsonProperty("EffectiveDate", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string EffectiveDate { get; set; } [Newtonsoft.Json.JsonProperty("ExpirationDate", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExpirationDate { get; set; } [Newtonsoft.Json.JsonProperty("PolicyNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string PolicyNumber { get; set; } [Newtonsoft.Json.JsonProperty("AgreementType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string AgreementType { get; set; } [Newtonsoft.Json.JsonProperty("CoverageType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string CoverageType { get; set; } [Newtonsoft.Json.JsonProperty("Insured", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Insured Insured { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Plan { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Company { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Authorization2 { [Newtonsoft.Json.JsonProperty("DateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DateTime { get; set; } [Newtonsoft.Json.JsonProperty("ExpirationDateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExpirationDateTime { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class PhoneNumber { [Newtonsoft.Json.JsonProperty("Office", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Office { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Location { [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("Facility", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Facility { get; set; } [Newtonsoft.Json.JsonProperty("Department", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Department { get; set; } [Newtonsoft.Json.JsonProperty("Room", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Room { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class PhoneNumber2 { [Newtonsoft.Json.JsonProperty("Home", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Home { get; set; } [Newtonsoft.Json.JsonProperty("Office", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Office { get; set; } [Newtonsoft.Json.JsonProperty("Mobile", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Mobile { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address2 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address3 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class PhoneNumber3 { [Newtonsoft.Json.JsonProperty("Home", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Home { get; set; } [Newtonsoft.Json.JsonProperty("Office", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Office { get; set; } [Newtonsoft.Json.JsonProperty("Mobile", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Mobile { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Spouse { [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address4 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class PhoneNumber4 { [Newtonsoft.Json.JsonProperty("Home", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Home { get; set; } [Newtonsoft.Json.JsonProperty("Business", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Business { get; set; } [Newtonsoft.Json.JsonProperty("Mobile", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Mobile { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Employer { [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address5 Address { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string PhoneNumber { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Plan2 { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("Type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Company2 { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address6 Address { get; set; } [Newtonsoft.Json.JsonProperty("PhoneNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string PhoneNumber { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Insured { [Newtonsoft.Json.JsonProperty("Identifiers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<Identifiers2> Identifiers { get; set; } [Newtonsoft.Json.JsonProperty("LastName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string LastName { get; set; } [Newtonsoft.Json.JsonProperty("MiddleName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string MiddleName { get; set; } [Newtonsoft.Json.JsonProperty("FirstName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty("SSN", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string SSN { get; set; } [Newtonsoft.Json.JsonProperty("Relationship", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Relationship { get; set; } [Newtonsoft.Json.JsonProperty("DOB", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DOB { get; set; } [Newtonsoft.Json.JsonProperty("Sex", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Sex { get; set; } [Newtonsoft.Json.JsonProperty("Address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public Address7 Address { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address5 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address6 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Identifiers2 { [Newtonsoft.Json.JsonProperty("ID", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ID { get; set; } [Newtonsoft.Json.JsonProperty("IDType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string IDType { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.2.0 (Newtonsoft.Json v12.0.0.0)")] public partial class Address7 { [Newtonsoft.Json.JsonProperty("StreetAddress", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string StreetAddress { get; set; } [Newtonsoft.Json.JsonProperty("City", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string City { get; set; } [Newtonsoft.Json.JsonProperty("State", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string State { get; set; } [Newtonsoft.Json.JsonProperty("ZIP", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ZIP { get; set; } [Newtonsoft.Json.JsonProperty("County", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string County { get; set; } [Newtonsoft.Json.JsonProperty("Country", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Country { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } }
55.379447
173
0.707201
[ "Apache-2.0" ]
matjazbravc/Redox.Ehr.OpenApi.Demo
src/Redox.Ehr.Contracts/Models/Redox/Referral/Authresponse.cs
70,055
C#
using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.Data; using Orchard.Environment; using Orchard.Security; using SoftIT.HouseParty.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SoftIT.HouseParty.Handlers { public class SupplyPartHandler : ContentHandler { public SupplyPartHandler(IRepository<SupplyPartRecord> repository, Work<IContentManager> contentManagerWork) { Filters.Add(StorageFilter.For(repository)); OnActivated<SupplyPart>((context, part) => { part.PartyField.Loader(() => contentManagerWork.Value.Get(part.PartyId).As<PartyPart>()); part.AssignedToField.Loader(() => contentManagerWork.Value.Get(part.AssignedToId).As<IUser>()); }); } } }
32.666667
116
0.683673
[ "BSD-3-Clause" ]
OrganicAdapter/HouseParty
src/Orchard.Web/Modules/SoftIT.HouseParty/Handlers/SupplyPartHandler.cs
884
C#
//using Microsoft.Extensions.DependencyInjection; //namespace WebVella.TagHelpers //{ // public static class WebVellaTagHelpersServiceCollectionExtensions // { // public static void AddWebVellaTagHelpers(this IServiceCollection services) // { // services.ConfigureOptions(typeof(WebVellaTagHelpersConfigurationOptions)); // } // } //}
26.307692
79
0.780702
[ "MIT" ]
5118234/TagHelpers
WebVella.TagHelpers/WebVellaTagHelpersServiceCollectionExtensions.cs
344
C#
using System; using System.Linq; using System.Reflection; using Microsoft.Extensions.Configuration; namespace aemarcoCommons.Toolbox.AppConfiguration.Transformations { public abstract class StringTransformerBase { /// <summary> /// /// </summary> /// <param name="currentValue">value which comes from previous transformation or from IConfiguration</param> /// <param name="propertyInfo"></param> /// <param name="configRoot"></param> /// <returns></returns> public abstract string PerformReadTransformation(string currentValue, PropertyInfo propertyInfo, IConfigurationRoot configRoot); /// <summary> /// /// </summary> /// <param name="currentValue">value which comes from previous transformation or from SettingsObject</param> /// <param name="propertyInfo"></param> /// <param name="configRoot"></param> /// <returns></returns> public abstract string PerformWriteTransformation(string currentValue, PropertyInfo propertyInfo, IConfigurationRoot configRoot); /// <summary> /// Performs string transformations on given objects string properties /// </summary> /// <param name="obj">object which needs transformation</param> /// <param name="configRoot"></param> /// <param name="transform">transformation which should be performed</param> internal static void TransformObject(object obj, IConfigurationRoot configRoot, Func<string, PropertyInfo, IConfigurationRoot, string> transform) { //handle foreach (var propInfo in obj.GetType().GetProperties() .Where(x => x.PropertyType == typeof(string)) .Where(x => x.CanRead && x.CanWrite)) { propInfo.SetValue(obj, transform((string)propInfo.GetValue(obj), propInfo, configRoot)); } //recurse foreach (var propInfo in obj.GetType().GetProperties() .Where(x => typeof(SettingsBase).IsAssignableFrom(x.PropertyType)) .Where(x => x.GetValue(obj) != null)) { TransformObject(propInfo.GetValue(obj), configRoot, transform); } } } }
42.314815
153
0.62407
[ "Unlicense" ]
Mahmoud-zino/aemarcoCommons
Toolbox/AppConfiguration/Transformations/StringTransformerBase.cs
2,287
C#
using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Web; using Tdlr.Models; namespace Tdlr.DAL { public class TasksDbHelper { public static List<Task> GetAllTasks(List<string> objectIds) { // Get all tasks that the user has created or has been authorized to view. TdlrContext db = new TdlrContext(); return db.Tasks.Where( t => t.SharedWith.Any( a => objectIds.Contains(a.AadObjectID))) .ToList(); } public static Task GetTask(int taskId) { // Get a specific Task from the db. TdlrContext db = new TdlrContext(); Task task = db.Tasks.Find(taskId); var captureSharedWith = task.SharedWith; return task; } public static Task AddTask(string taskText, string userObjectId, string userName) { // Add a new task to the db TdlrContext db = new TdlrContext(); Task newTask = new Task { Status = "NotStarted", TaskText = taskText, Creator = userObjectId, SharedWith = new List<AadObject>(), CreatorName = userName, }; // Get the AadObject representing from the user if it exists AadObject user = db.AadObjects.Find(userObjectId); if (user != null) { // Update the user's display name in case it has changed user.DisplayName = userName; } else { user = new AadObject { AadObjectID = userObjectId, DisplayName = userName, }; } newTask.SharedWith.Add(user); db.Tasks.Add(newTask); db.SaveChanges(); return newTask; } public static Task UpdateTask(int taskId, string status) { // Update an existing task in the db TdlrContext db = new TdlrContext(); Task task = db.Tasks.Find(taskId); var captureSharedWith = task.SharedWith; if (task == null) throw new Exception("Task Not Found in DB"); task.Status = status; db.SaveChanges(); return task; } public static void DeleteTask(int taskId) { //Delete a task in the db TdlrContext db = new TdlrContext(); Task task = db.Tasks.Find(taskId); db.Tasks.Remove(task); db.SaveChanges(); } public static void UpdateShares(int taskId, List<Share> shares) { //Share a task with a user or group TdlrContext db = new TdlrContext(); Task task = db.Tasks.Find(taskId); // Maintain that the task is shared with the owner AadObject user = task.SharedWith.Where(u => u.AadObjectID == task.Creator).FirstOrDefault(); task.SharedWith = new List<AadObject>(); task.SharedWith.Add(user); foreach (Share share in shares) { AadObject aadObject = db.AadObjects.Find(share.objectId); if (aadObject != null) { aadObject.DisplayName = share.displayName; } else { aadObject = new AadObject { AadObjectID = share.objectId, DisplayName = share.displayName, }; } task.SharedWith.Add(aadObject); } db.SaveChanges(); } } }
32.258333
104
0.500646
[ "MIT" ]
Azure-Samples/active-directory-dotnet-demo-tdlr
TDLR/DAL/TasksDbHelper.cs
3,873
C#
using Infusion.IO; namespace Infusion.Packets.Server { internal sealed class DrawGamePlayerPacket : MaterializedPacket { private Packet rawPacket; public DrawGamePlayerPacket() { } public DrawGamePlayerPacket(ObjectId playerId, ModelId bodyType, Location3D location, Direction direction, MovementType movementType, Color color) { PlayerId = playerId; BodyType = bodyType; Location = location; Color = color; Serialize(); } public Packet Serialize() { var payload = new byte[19]; var writer = new ArrayPacketWriter(payload); writer.WriteByte((byte)PacketDefinitions.DrawGamePlayer.Id); writer.WriteId(PlayerId); writer.WriteModelId(BodyType); writer.WriteByte(0); // unknown writer.WriteColor(Color); writer.WriteByte(0); // flag, alway 0 writer.WriteUShort((ushort)Location.X); writer.WriteUShort((ushort)Location.Y); writer.WriteUShort(0); // unknown writer.WriteMovement(Direction, MovementType); writer.WriteSByte((sbyte)Location.Z); rawPacket = new Packet(PacketDefinitions.DrawGamePlayer.Id, payload); return rawPacket; } public byte Flags { get; set; } public ObjectId PlayerId { get; set; } public ModelId BodyType { get; set; } public Location3D Location { get; set; } public override Packet RawPacket => rawPacket; public Direction Direction { get; set; } public MovementType MovementType { get; set; } public Color Color { get; set; } public override void Deserialize(Packet rawPacket) { this.rawPacket = rawPacket; var reader = new ArrayPacketReader(rawPacket.Payload); reader.Skip(1); PlayerId = reader.ReadObjectId(); BodyType = reader.ReadModelId(); reader.Skip(1); // unknown Color = reader.ReadColor(); Flags = reader.ReadByte(); var xloc = reader.ReadUShort(); var yloc = reader.ReadUShort(); reader.Skip(2); // unknown (Direction, MovementType) = reader.ReadDirection(); var zloc = reader.ReadSByte(); Location = new Location3D(xloc, yloc, zloc); } } }
30.231707
154
0.581686
[ "MIT" ]
3HMonkey/Infusion
Infusion/Packets/Server/DrawGamePlayerPacket.cs
2,481
C#
//--------------------------------------------------------------------------------------------------- // <auto-generated> // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit // </auto-generated> //--------------------------------------------------------------------------------------------------- using Microsoft.Xrm.Sdk; using System; using System.Diagnostics; namespace Dev.DevKit.Shared.Entities.SLAItemOptionSets { public enum ComponentState { /// <summary> /// Deleted = 2 /// </summary> Deleted = 2, /// <summary> /// Deleted_Unpublished = 3 /// </summary> Deleted_Unpublished = 3, /// <summary> /// Published = 0 /// </summary> Published = 0, /// <summary> /// Unpublished = 1 /// </summary> Unpublished = 1 } } namespace Dev.DevKit.Shared.Entities { public partial class SLAItem : EntityBase { public struct Fields { public const string actionflowuniquename = "actionflowuniquename"; public const string ActionURL = "actionurl"; public const string AllowPauseResume = "allowpauseresume"; public const string ApplicableEntity = "applicableentity"; public const string ApplicableWhenXml = "applicablewhenxml"; public const string BusinessHoursId = "businesshoursid"; public const string ChangedAttributeList = "changedattributelist"; public const string ComponentState = "componentstate"; public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string Description = "description"; public const string ExchangeRate = "exchangerate"; public const string FailureAfter = "failureafter"; public const string IsManaged = "ismanaged"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string msdyn_AdvancedPauseConfiguration = "msdyn_advancedpauseconfiguration"; public const string msdyn_PauseConfigurationXml = "msdyn_pauseconfigurationxml"; public const string msdyn_slakpiid = "msdyn_slakpiid"; public const string Name = "name"; public const string OverwriteTime = "overwritetime"; public const string OwnerId = "ownerid"; public const string OwningBusinessUnit = "owningbusinessunit"; public const string OwningUser = "owninguser"; public const string RelatedField = "relatedfield"; public const string SequenceNumber = "sequencenumber"; public const string SLAId = "slaid"; public const string SLAItemId = "slaitemid"; public const string SLAItemIdUnique = "slaitemidunique"; public const string SolutionId = "solutionid"; public const string SuccessConditionsXml = "successconditionsxml"; public const string SupportingSolutionId = "supportingsolutionid"; public const string TransactionCurrencyId = "transactioncurrencyid"; public const string VersionNumber = "versionnumber"; public const string WarnAfter = "warnafter"; public const string WorkflowId = "workflowid"; } public const string EntityLogicalName = "slaitem"; public const int EntityTypeCode = 9751; [DebuggerNonUserCode()] public SLAItem() { Entity = new Entity(EntityLogicalName); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SLAItem(Guid SLAItemId) { Entity = new Entity(EntityLogicalName, SLAItemId); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SLAItem(string keyName, object keyValue) { Entity = new Entity(EntityLogicalName, keyName, keyValue); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SLAItem(Entity entity) { Entity = entity; PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SLAItem(Entity entity, Entity merge) { Entity = entity; foreach (var property in merge?.Attributes) { var key = property.Key; var value = property.Value; Entity[key] = value; } PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SLAItem(KeyAttributeCollection keys) { Entity = new Entity(EntityLogicalName, keys); PreEntity = CloneThisEntity(Entity); } /// <summary> /// <para>String - MaxLength: 4000</para> /// <para>Action Flow Unique Name</para> /// </summary> [DebuggerNonUserCode()] public string actionflowuniquename { get { return Entity.GetAttributeValue<string>(Fields.actionflowuniquename); } set { Entity.Attributes[Fields.actionflowuniquename] = value; } } /// <summary> /// <para>Action URL</para> /// <para>String - MaxLength: 1024</para> /// <para>Action URL</para> /// </summary> [DebuggerNonUserCode()] public string ActionURL { get { return Entity.GetAttributeValue<string>(Fields.ActionURL); } set { Entity.Attributes[Fields.ActionURL] = value; } } /// <summary> /// <para>Select whether this SLA will allow pausing and resuming during the time calculation.</para> /// <para>Boolean</para> /// <para>Allow Pause and Resume</para> /// </summary> [DebuggerNonUserCode()] public bool? AllowPauseResume { get { return Entity.GetAttributeValue<bool?>(Fields.AllowPauseResume); } set { Entity.Attributes[Fields.AllowPauseResume] = value; } } /// <summary> /// <para>String - MaxLength: 100</para> /// <para>Applicable Entity</para> /// </summary> [DebuggerNonUserCode()] public string ApplicableEntity { get { return Entity.GetAttributeValue<string>(Fields.ApplicableEntity); } set { Entity.Attributes[Fields.ApplicableEntity] = value; } } /// <summary> /// <para>Condition for SLA item</para> /// <para>Required - Memo - MaxLength: 1073741823</para> /// <para>ApplicableWhenXml</para> /// </summary> [DebuggerNonUserCode()] public string ApplicableWhenXml { get { return Entity.GetAttributeValue<string>(Fields.ApplicableWhenXml); } set { Entity.Attributes[Fields.ApplicableWhenXml] = value; } } /// <summary> /// <para>Choose the business hours for calculating SLA item timelines.</para> /// <para>Lookup to calendar</para> /// <para>Business Hours</para> /// </summary> [DebuggerNonUserCode()] public EntityReference BusinessHoursId { get { return Entity.GetAttributeValue<EntityReference>(Fields.BusinessHoursId); } set { Entity.Attributes[Fields.BusinessHoursId] = value; } } /// <summary> /// <para>String - MaxLength: 4000</para> /// <para>Changed Attribute List</para> /// </summary> [DebuggerNonUserCode()] public string ChangedAttributeList { get { return Entity.GetAttributeValue<string>(Fields.ChangedAttributeList); } set { Entity.Attributes[Fields.ChangedAttributeList] = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Picklist</para> /// <para>Component State</para> /// </summary> [DebuggerNonUserCode()] public Dev.DevKit.Shared.Entities.SLAItemOptionSets.ComponentState? ComponentState { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ComponentState); if (value == null) return null; return (Dev.DevKit.Shared.Entities.SLAItemOptionSets.ComponentState)value.Value; } } /// <summary> /// <para>Shows who created the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Created By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedBy); } } /// <summary> /// <para>Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Created On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? CreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.CreatedOn); } } /// <summary> /// <para>Shows who created the record on behalf of another user.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Created By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedOnBehalfBy); } } /// <summary> /// <para>Type additional information to describe the SLA Item</para> /// <para>String - MaxLength: 100</para> /// <para>Description</para> /// </summary> [DebuggerNonUserCode()] public string Description { get { return Entity.GetAttributeValue<string>(Fields.Description); } set { Entity.Attributes[Fields.Description] = value; } } /// <summary> /// <para>Exchange rate between the currency associated with the SLA Item record and the base currency.</para> /// <para>ReadOnly - Decimal - MinValue: 0 - MaxValue: 100,000,000,000</para> /// <para>Exchange Rate</para> /// </summary> [DebuggerNonUserCode()] public decimal? ExchangeRate { get { return Entity.GetAttributeValue<decimal?>(Fields.ExchangeRate); } } /// <summary> /// <para>Select how soon the success criteria must be met until the SLA item is considered failed and failure actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record.</para> /// <para>Integer - MinValue: 0 - MaxValue: 2,147,483,647</para> /// <para>Failure After</para> /// </summary> [DebuggerNonUserCode()] public int? FailureAfter { get { return Entity.GetAttributeValue<int?>(Fields.FailureAfter); } set { Entity.Attributes[Fields.FailureAfter] = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Boolean</para> /// <para>Is Managed</para> /// </summary> [DebuggerNonUserCode()] public bool? IsManaged { get { return Entity.GetAttributeValue<bool?>(Fields.IsManaged); } } /// <summary> /// <para>Shows who last updated the record.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Modified By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedBy); } } /// <summary> /// <para>Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Modified On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? ModifiedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.ModifiedOn); } } /// <summary> /// <para>Shows who created the record on behalf of another user.</para> /// <para>ReadOnly - Lookup to systemuser</para> /// <para>Modified By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedOnBehalfBy); } } /// <summary> /// <para>Boolean</para> /// <para>Advanced Pause Configuration</para> /// </summary> [DebuggerNonUserCode()] public bool? msdyn_AdvancedPauseConfiguration { get { return Entity.GetAttributeValue<bool?>(Fields.msdyn_AdvancedPauseConfiguration); } set { Entity.Attributes[Fields.msdyn_AdvancedPauseConfiguration] = value; } } /// <summary> /// <para>Memo - MaxLength: 1048576</para> /// <para>PauseConfigurationXml</para> /// </summary> [DebuggerNonUserCode()] public string msdyn_PauseConfigurationXml { get { return Entity.GetAttributeValue<string>(Fields.msdyn_PauseConfigurationXml); } set { Entity.Attributes[Fields.msdyn_PauseConfigurationXml] = value; } } /// <summary> /// <para>Unique identifier for SLAKPI associated with SLA Item.</para> /// <para>Lookup to msdyn_slakpi</para> /// <para>SLA KPI</para> /// </summary> [DebuggerNonUserCode()] public EntityReference msdyn_slakpiid { get { return Entity.GetAttributeValue<EntityReference>(Fields.msdyn_slakpiid); } set { Entity.Attributes[Fields.msdyn_slakpiid] = value; } } /// <summary> /// <para>Type a descriptive name of the service level agreement (SLA) item.</para> /// <para>String - MaxLength: 100</para> /// <para>Name</para> /// </summary> [DebuggerNonUserCode()] public string Name { get { return Entity.GetAttributeValue<string>(Fields.Name); } set { Entity.Attributes[Fields.Name] = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para> /// <para>Record Overwrite Time</para> /// </summary> [DebuggerNonUserCode()] public DateTime? OverwriteTimeUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.OverwriteTime); } } /// <summary> /// <para>Enter the user or team who owns the SLA. This field is updated every time the item is assigned to a different user.</para> /// <para>Required - Owner</para> /// <para>Owner</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwnerId { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwnerId); } set { Entity.Attributes[Fields.OwnerId] = value; } } /// <summary> /// <para>Unique identifier for the business unit that owns the record</para> /// <para>ReadOnly - Lookup to businessunit</para> /// <para>Owning Business Unit</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwningBusinessUnit { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwningBusinessUnit); } } /// <summary> /// <para>Unique identifier of the user who owns the SLA Item record.</para> /// <para>Lookup to </para> /// <para>Owning User</para> /// </summary> [DebuggerNonUserCode()] public EntityReference OwningUser { get { return Entity.GetAttributeValue<EntityReference>(Fields.OwningUser); } set { Entity.Attributes[Fields.OwningUser] = value; } } /// <summary> /// <para>Select the service level agreement (SLA) key performance indicator (KPI) that this SLA Item is created for.</para> /// <para>String - MaxLength: 100</para> /// <para>Related Case Field</para> /// </summary> [DebuggerNonUserCode()] public string RelatedField { get { return Entity.GetAttributeValue<string>(Fields.RelatedField); } set { Entity.Attributes[Fields.RelatedField] = value; } } /// <summary> /// <para>Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address.</para> /// <para>Integer - MinValue: 0 - MaxValue: 1,500</para> /// <para>Sequence</para> /// </summary> [DebuggerNonUserCode()] public int? SequenceNumber { get { return Entity.GetAttributeValue<int?>(Fields.SequenceNumber); } set { Entity.Attributes[Fields.SequenceNumber] = value; } } /// <summary> /// <para>Unique identifier for SLA associated with SLA Item.</para> /// <para>Lookup to sla</para> /// <para>SLA</para> /// </summary> [DebuggerNonUserCode()] public EntityReference SLAId { get { return Entity.GetAttributeValue<EntityReference>(Fields.SLAId); } set { Entity.Attributes[Fields.SLAId] = value; } } /// <summary> /// <para>Unique identifier of the SLA Item.</para> /// <para>Primary Key - Uniqueidentifier</para> /// <para>SLA Item</para> /// </summary> [DebuggerNonUserCode()] public Guid SLAItemId { get { return Id; } set { Entity.Attributes[Fields.SLAItemId] = value; Entity.Id = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para>Unique Id</para> /// </summary> [DebuggerNonUserCode()] public Guid? SLAItemIdUnique { get { return Entity.GetAttributeValue<Guid?>(Fields.SLAItemIdUnique); } } /// <summary> /// <para>Unique identifier of the associated solution.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para>Solution</para> /// </summary> [DebuggerNonUserCode()] public Guid? SolutionId { get { return Entity.GetAttributeValue<Guid?>(Fields.SolutionId); } } /// <summary> /// <para>Condition for SLA item</para> /// <para>Required - Memo - MaxLength: 1073741823</para> /// <para>SuccessConditionsXml</para> /// </summary> [DebuggerNonUserCode()] public string SuccessConditionsXml { get { return Entity.GetAttributeValue<string>(Fields.SuccessConditionsXml); } set { Entity.Attributes[Fields.SuccessConditionsXml] = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para>Solution</para> /// </summary> [DebuggerNonUserCode()] public Guid? SupportingSolutionId { get { return Entity.GetAttributeValue<Guid?>(Fields.SupportingSolutionId); } } /// <summary> /// <para>Unique identifier of the currency associated with the SLA Item record.</para> /// <para>ReadOnly - Lookup to transactioncurrency</para> /// <para>Currency</para> /// </summary> [DebuggerNonUserCode()] public EntityReference TransactionCurrencyId { get { return Entity.GetAttributeValue<EntityReference>(Fields.TransactionCurrencyId); } } /// <summary> /// <para>Version number of the SLA Item.</para> /// <para>ReadOnly - BigInt</para> /// <para>Version Number</para> /// </summary> [DebuggerNonUserCode()] public long? VersionNumber { get { return Entity.GetAttributeValue<long?>(Fields.VersionNumber); } } /// <summary> /// <para>Select how soon the success criteria must be met before warning actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record.</para> /// <para>Integer - MinValue: 0 - MaxValue: 2,147,483,647</para> /// <para>Warn After</para> /// </summary> [DebuggerNonUserCode()] public int? WarnAfter { get { return Entity.GetAttributeValue<int?>(Fields.WarnAfter); } set { Entity.Attributes[Fields.WarnAfter] = value; } } /// <summary> /// <para>Workflow associated with the SLA Item.</para> /// <para>Lookup to workflow</para> /// <para>Workflow ID</para> /// </summary> [DebuggerNonUserCode()] public EntityReference WorkflowId { get { return Entity.GetAttributeValue<EntityReference>(Fields.WorkflowId); } set { Entity.Attributes[Fields.WorkflowId] = value; } } } }
32.45234
236
0.685768
[ "MIT" ]
Kayserheimer/Dynamics-Crm-DevKit
test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/SLAItem.generated.cs
18,727
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Pubs.CoreDomain.Entities; namespace Pubs.Infrastructure.Persistence.EntityConfigurations { public class RoyaltyConfiguration : BaseConfiguration, IEntityTypeConfiguration<Royalty> { public RoyaltyConfiguration(string schema) : base(schema) { } public void Configure(EntityTypeBuilder<Royalty> builder) { builder.ToTable("royalty", _schema); builder.HasKey(a => a.Id); builder.Property(a => a.Id).HasColumnName("royalty_id"); builder.Property(a => a.TitleId).HasColumnName("title_id"); builder.Property(a => a.TitleCode).HasColumnName("title_code"); builder.Property(a => a.LowRange).HasColumnName("lorange"); builder.Property(a => a.HighRange).HasColumnName("hirange"); builder.Property(a => a.RoyaltyAmount).HasColumnName("royalty"); builder.HasOne(a => a.Title) .WithMany(b => b.Royalties) .HasForeignKey(a => a.TitleId); } } }
31.108108
92
0.631625
[ "MIT" ]
theMickster/pubs
src/Pubs.Infrastructure.Persistence/EntityConfigurations/RoyaltyConfiguration.cs
1,153
C#
#if !ONPREMISES using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Framework.Provisioning.Connectors; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.Model.Configuration; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers; using OfficeDevPnP.Core.Framework.Provisioning.Providers; using PnP.PowerShell.CmdletHelpAttributes; using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using PnP.PowerShell.Commands.Model; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Threading.Tasks; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet("Apply", "PnPTenantTemplate", SupportsShouldProcess = true)] [CmdletHelp("Applies a tenant template to the current tenant. You must have the Office 365 Global Admin role to run this cmdlet successfully.", Category = CmdletHelpCategory.Provisioning, SupportedPlatform = CmdletSupportedPlatform.Online)] [CmdletExample( Code = @"PS:> Apply-PnPTenantTemplate -Path myfile.pnp", Remarks = "Will read the tenant template from the filesystem and will apply the sequences in the template", SortOrder = 1)] [CmdletExample( Code = @"PS:> Apply-PnPTenantTemplate -Path myfile.pnp -SequenceId ""mysequence""", Remarks = "Will read the tenant template from the filesystem and will apply the specified sequence in the template", SortOrder = 1)] [CmdletExample( Code = @"PS:> Apply-PnPTenantTemplate -Path myfile.pnp -Parameters @{""ListTitle""=""Projects"";""parameter2""=""a second value""}", Remarks = @"Applies a tenant template to the current tenant. It will populate the parameter in the template the values as specified and in the template you can refer to those values with the {parameter:<key>} token. For instance with the example above, specifying {parameter:ListTitle} in your template will translate to 'Projects' when applying the template. These tokens can be used in most string values in a template.", SortOrder = 3)] public class ApplyTenantTemplate : PnPAdminCmdlet { private const string ParameterSet_PATH = "By Path"; private const string ParameterSet_OBJECT = "By Object"; private ProgressRecord progressRecord = new ProgressRecord(0, "Activity", "Status"); private ProgressRecord subProgressRecord = new ProgressRecord(1, "Activity", "Status"); [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, HelpMessage = "Path to the xml or pnp file containing the tenant template.", ParameterSetName = ParameterSet_PATH)] public string Path; [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = ParameterSet_OBJECT)] public ProvisioningHierarchy Template; [Parameter(Mandatory = false)] public string SequenceId; [Parameter(Mandatory = false, HelpMessage = "Root folder where resources/files that are being referenced in the template are located. If not specified the same folder as where the tenant template is located will be used.", ParameterSetName = ParameterAttribute.AllParameterSets)] public string ResourceFolder; [Parameter(Mandatory = false, HelpMessage = "Allows you to only process a specific part of the template. Notice that this might fail, as some of the handlers require other artifacts in place if they are not part of what your applying.", ParameterSetName = ParameterAttribute.AllParameterSets)] public Handlers Handlers; [Parameter(Mandatory = false, HelpMessage = "Allows you to run all handlers, excluding the ones specified.", ParameterSetName = ParameterAttribute.AllParameterSets)] public Handlers ExcludeHandlers; [Parameter(Mandatory = false, HelpMessage = "Allows you to specify ExtensbilityHandlers to execute while applying a template", ParameterSetName = ParameterAttribute.AllParameterSets)] public ExtensibilityHandler[] ExtensibilityHandlers; [Parameter(Mandatory = false, HelpMessage = "Allows you to specify ITemplateProviderExtension to execute while applying a template.", ParameterSetName = ParameterAttribute.AllParameterSets)] public ITemplateProviderExtension[] TemplateProviderExtensions; [Parameter(Mandatory = false, HelpMessage = "Allows you to specify parameters that can be referred to in the tenant template by means of the {parameter:<Key>} token. See examples on how to use this parameter.", ParameterSetName = ParameterAttribute.AllParameterSets)] public Hashtable Parameters; [Parameter(Mandatory = false, HelpMessage = "Specify this parameter if you want to overwrite and/or create properties that are known to be system entries (starting with vti_, dlc_, etc.)", ParameterSetName = ParameterAttribute.AllParameterSets)] public SwitchParameter OverwriteSystemPropertyBagValues; [Parameter(Mandatory = false, HelpMessage = "Ignore duplicate data row errors when the data row in the template already exists.", ParameterSetName = ParameterAttribute.AllParameterSets)] public SwitchParameter IgnoreDuplicateDataRowErrors; [Parameter(Mandatory = false, HelpMessage = "If set content types will be provisioned if the target web is a subweb.")] public SwitchParameter ProvisionContentTypesToSubWebs; [Parameter(Mandatory = false, HelpMessage = "If set fields will be provisioned if the target web is a subweb.")] public SwitchParameter ProvisionFieldsToSubWebs; [Parameter(Mandatory = false, HelpMessage = "Override the RemoveExistingNodes attribute in the Navigation elements of the template. If you specify this value the navigation nodes will always be removed before adding the nodes in the template")] public SwitchParameter ClearNavigation; [Parameter(Mandatory = false, HelpMessage = "Specify a JSON configuration file to configure the extraction progress.", ParameterSetName = ParameterAttribute.AllParameterSets)] public ApplyConfigurationPipeBind Configuration; protected override void ExecuteCmdlet() { var sitesProvisioned = new List<ProvisionedSite>(); var configuration = new ApplyConfiguration(); if (ParameterSpecified(nameof(Configuration))) { configuration = Configuration.GetConfiguration(SessionState.Path.CurrentFileSystemLocation.Path); } configuration.SiteProvisionedDelegate = (title, url) => { if (sitesProvisioned.FirstOrDefault(s => s.Url == url) == null) { sitesProvisioned.Add(new ProvisionedSite() { Title = title, Url = url }); } }; if (ParameterSpecified(nameof(Handlers))) { if (!Handlers.Has(Handlers.All)) { foreach (var enumValue in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (Handlers.Has(enumValue)) { if (enumValue == Handlers.TermGroups) { configuration.Handlers.Add(ConfigurationHandler.Taxonomy); } else if (enumValue == Handlers.PageContents) { configuration.Handlers.Add(ConfigurationHandler.Pages); } else if (Enum.TryParse<ConfigurationHandler>(enumValue.ToString(), out ConfigurationHandler configHandler)) { configuration.Handlers.Add(configHandler); } } } } } if (ParameterSpecified(nameof(ExcludeHandlers))) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { if (handler == Handlers.TermGroups) { if (configuration.Handlers.Contains(ConfigurationHandler.Taxonomy)) { configuration.Handlers.Remove(ConfigurationHandler.Taxonomy); } else if (Enum.TryParse<ConfigurationHandler>(handler.ToString(), out ConfigurationHandler configHandler)) { if (configuration.Handlers.Contains(configHandler)) { configuration.Handlers.Remove(configHandler); } } } } } } if (ExtensibilityHandlers != null) { configuration.Extensibility.Handlers = ExtensibilityHandlers.ToList(); } configuration.ProgressDelegate = (message, step, total) => { if (message != null) { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); progressRecord.Activity = $"Applying template to tenant"; progressRecord.StatusDescription = message; progressRecord.PercentComplete = percentage; progressRecord.RecordType = ProgressRecordType.Processing; WriteProgress(progressRecord); } }; var warningsShown = new List<string>(); configuration.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { if (!warningsShown.Contains(message)) { WriteWarning(message); warningsShown.Add(message); } break; } case ProvisioningMessageType.Progress: { if (message != null) { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0]; subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; configuration.PropertyBag.OverwriteSystemValues = OverwriteSystemPropertyBagValues; configuration.Lists.IgnoreDuplicateDataRowErrors = IgnoreDuplicateDataRowErrors; configuration.Navigation.ClearNavigation = ClearNavigation; configuration.ContentTypes.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs; configuration.Fields.ProvisionFieldsToSubWebs = ProvisionFieldsToSubWebs; ProvisioningHierarchy hierarchyToApply = null; switch (ParameterSetName) { case ParameterSet_PATH: { hierarchyToApply = GetHierarchy(); break; } case ParameterSet_OBJECT: { hierarchyToApply = Template; if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); hierarchyToApply.Connector = fileSystemConnector; } else { if (Path != null) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } else { Path = SessionState.Path.CurrentFileSystemLocation.Path; } var fileInfo = new FileInfo(Path); var fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); hierarchyToApply.Connector = fileConnector; } break; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (hierarchyToApply.Parameters.ContainsKey(parameter.ToString())) { hierarchyToApply.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { hierarchyToApply.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } #if !ONPREMISES // check if consent is needed and in place var consentRequired = false; if (hierarchyToApply.Teams != null) { consentRequired = true; } if(hierarchyToApply.AzureActiveDirectory != null) { consentRequired = true; } if (consentRequired) { // try to retrieve an access token for the Microsoft Graph: var accessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph); if (accessToken == null) { if (PnPConnection.CurrentConnection.PSCredential != null) { // Using normal credentials accessToken = TokenHandler.AcquireToken("graph.microsoft.com", null); } if (accessToken == null) { throw new PSInvalidOperationException("Your template contains artifacts that require an access token. Please provide consent to the PnP Management Shell application first by executing: Connect-PnPOnline -Graph -LaunchBrowser"); } } } using (var provisioningContext = new PnPProvisioningContext((resource, scope) => { if(resource.ToLower().StartsWith("https://")) { var uri = new Uri(resource); resource = uri.Authority; } // Get Azure AD Token if (PnPConnection.CurrentConnection != null) { if (resource.Equals("graph.microsoft.com", StringComparison.OrdinalIgnoreCase)) { var graphAccessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph); if (graphAccessToken != null) { // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline return Task.FromResult(graphAccessToken); } } } if (PnPConnection.CurrentConnection.PSCredential != null) { // Using normal credentials return Task.FromResult(TokenHandler.AcquireToken(resource, null)); } else { // No token... throw new PSInvalidOperationException("Your template contains artifacts that require an access token. Please provide consent to the PnP Management Shell application first by executing: Connect-PnPOnline -Graph -LaunchBrowser"); } })) { #endif if (!string.IsNullOrEmpty(SequenceId)) { Tenant.ApplyTenantTemplate(hierarchyToApply, SequenceId, configuration); } else { if (hierarchyToApply.Sequences.Count > 0) { foreach (var sequence in hierarchyToApply.Sequences) { Tenant.ApplyTenantTemplate(hierarchyToApply, sequence.ID, configuration); } } else { Tenant.ApplyTenantTemplate(hierarchyToApply, null, configuration); } } #if !ONPREMISES } #endif WriteObject(sitesProvisioned, true); } private ProvisioningHierarchy GetHierarchy() { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (System.IO.File.Exists(Path)) { return ReadTenantTemplate.LoadProvisioningHierarchyFromFile(Path, TemplateProviderExtensions, (e) => { WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); }); } else { throw new FileNotFoundException($"File {Path} does not exist."); } } } } #endif
50.22549
301
0.542504
[ "MIT" ]
FPotrafky/PnP-PowerShell
Commands/Provisioning/Tenant/ApplyTenantTemplate.cs
20,494
C#
namespace Providers { public class EventsProvider : Provider { } }
17.5
46
0.728571
[ "MIT" ]
Croniks/ShootingMan
Assets/Scripts/Providers/EventsProvider.cs
70
C#
using System; using SSLapp.Models; using Newtonsoft.Json.Linq; using System.Diagnostics; namespace SSLapp.Utils.Files.Update { static class UpdateJSONFields { public static void UpdateCertificate(JObject jsonObj, ToscaConfigFilesModel config, string appsetting) { try { jsonObj["HttpServer"]["Endpoints"]["Https"]["Thumbprint"] = config.GetCertificate.GetCertificateThumbprint(); jsonObj["HttpServer"]["Endpoints"]["Https"]["StoreName"] = config.GetCertificate.GetCertificateStoreName(); jsonObj["HttpServer"]["Endpoints"]["Https"]["StoreLocation"] = config.GetCertificate.GetCertificateStoreLocation(); } catch (Exception) { Trace.WriteLine(appsetting + " file doesn't contain 'HttpServer/Endpoints/Https/(Thumbprint|StoreName|StoreLocation)'"); } } public static void UpdateTokenCertificate(JObject jsonObj, ToscaConfigFilesModel config) { try { jsonObj["TokenSignCertificate"]["Thumbprint"] = config.GetCertificate.GetCertificateThumbprint(); jsonObj["TokenSignCertificate"]["StoreName"] = config.GetCertificate.GetCertificateStoreName(); jsonObj["TokenSignCertificate"]["StoreLocation"] = config.GetCertificate.GetCertificateStoreLocation(); } catch (Exception) { throw; } } public static void UpdateServiceDiscovery(JObject jsonObj, ToscaConfigFilesModel config, string appsetting) { try { var value = (string)jsonObj["Discovery"]["ServiceDiscovery"]; string[] sd = value.Split(':'); var endpoint = @"https://" + config.Hostname + ":" + sd[2]; jsonObj["Discovery"]["ServiceDiscovery"] = endpoint; } catch (Exception) { Trace.WriteLine(appsetting + " file doesn't contain 'Discovery/ServiceDiscovery'"); } } public static void UpdateScheme(JObject jsonObj, string appsetting) { try { var endpointsArray = jsonObj["Discovery"]["Endpoints"]; foreach (var endpoint in endpointsArray) { endpoint["Scheme"] = "https"; } } catch (Exception) { Trace.WriteLine(appsetting+ " file doesn't contain Discovery/Endpoints"); } try { jsonObj["HttpServer"]["Endpoints"]["Https"]["Scheme"] = "https"; } catch (Exception) { Trace.WriteLine(appsetting + " doesn't contain 'HttpServer/Endpoints/Https/Scheme'"); } } public static void UpdateHost(JObject jsonObj, ToscaConfigFilesModel config, string appsetting) { try { var endpointsArray = jsonObj["Discovery"]["Endpoints"]; foreach (var endpoint in endpointsArray) { endpoint["Host"] = config.Hostname; } } catch (Exception) { Trace.WriteLine(appsetting + " doesn't contain 'Discovery/Endpoints'"); } } } }
34.929293
136
0.540486
[ "MIT" ]
benjithompson/DEXSSL
SSLapp/Utils/Files/Updates/Helpers/UpdateJSONFields.cs
3,460
C#
using System; using System.Net; using System.Net.Sockets; using LiteNetLib; namespace Playground.Client.WinForms { public class LiteNetLibClient : INetEventListener { private readonly NetManager client; private NetPeer peer; public event EventHadler MessageReceived; public event EmptyEventHadler Connected; public event EmptyEventHadler Disconected; public LiteNetLibClient() { client = new NetManager(this); client.UnsyncedEvents = true; client.AutoRecycle = true; client.Start(); } public void Connect() { peer = client.Connect("localhost", 9050, "qwe"); } public void PollEvents() { client.PollEvents(); } public void OnPeerConnected(NetPeer peer) { Connected?.Invoke(this, EventArgs.Empty); } public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { Disconected?.Invoke(this, EventArgs.Empty); } public void OnNetworkError(IPEndPoint endPoint, SocketError socketError) { } public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod) { var message = reader.GetString(); MessageReceived?.Invoke(this, message); } public void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType) { } public void OnNetworkLatencyUpdate(NetPeer peer, int latency) { } public void OnConnectionRequest(ConnectionRequest request) { request.Accept(); } } public delegate void EventHadler(object sender, string message); public delegate void EmptyEventHadler(object sender, EventArgs eventArgs); }
26.986111
134
0.625322
[ "MIT" ]
LevchenkovHeyworks/Networking
Playground/Playground.Client.WinForms/LiteNetLibClient.cs
1,945
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using EWSEditor.Common.Exports; using EWSEditor.Common; using EWSEditor.Common.Extensions; using EWSEditor.Resources; using Microsoft.Exchange.WebServices.Data; using System.Net; using System.Xml; namespace EWSEditor.Forms { public partial class FolderArchiveSettings : Form { private static ExtendedPropertyDefinition Prop_PR_ARCHIVE_TAG = new ExtendedPropertyDefinition(0x3018, MapiPropertyType.Binary); private static ExtendedPropertyDefinition Prop_PR_ARCHIVE_PERIOD = new ExtendedPropertyDefinition(0x301E, MapiPropertyType.Integer); private static ExtendedPropertyDefinition Prop_PR_RETENTION_FLAGS = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer); ExchangeService _ExchangeService = null; FolderId _FolderId = null; public FolderArchiveSettings() { InitializeComponent(); } public FolderArchiveSettings(ExchangeService oExchangeService, FolderId oFolderId) { InitializeComponent(); _ExchangeService = oExchangeService; _FolderId = oFolderId; } private void FolderArchiveSettings_Load(object sender, EventArgs e) { LoadForm(); // Compare: // https://blogs.msdn.microsoft.com/akashb/2012/12/07/stamping-archive-policy-tag-using-ews-managed-api-from-powershellexchange-2010/ // to // https://blogs.msdn.microsoft.com/akashb/2011/08/10/stamping-retention-policy-tag-using-ews-managed-api-1-1-from-powershellexchange-2010/ // And see: https://blogs.technet.microsoft.com/anya/2014/11/19/understanding-of-managed-folder-assistant-with-retention-policies/ } private void btnOK_Click(object sender, EventArgs e) { SaveForm(); this.Close(); } //public FolderArchiveSettings(ExchangeService oExchangeService, FolderId oFolderId) //{ // InitializeComponent(); // _ExchangeService = oExchangeService; // _FolderId = oFolderId; //} private PropertySet GetPropSet() { PropertySet oPropertySet = new PropertySet(BasePropertySet.IdOnly, Prop_PR_ARCHIVE_PERIOD, Prop_PR_RETENTION_FLAGS, Prop_PR_ARCHIVE_TAG ); return oPropertySet; } private void LoadForm() { PropertySet oPropertySet = GetPropSet(); _ExchangeService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. Folder oFolder = Folder.Bind(_ExchangeService, _FolderId, oPropertySet); string sFrom = EwsExtendedPropertyHelper.GetExtendedProp_Byte_AsString(oFolder, Prop_PR_ARCHIVE_TAG); if (sFrom != "") { byte[] oFromBytes = System.Convert.FromBase64String(sFrom); Guid guidTemp = new Guid(oFromBytes); string sPR_ARCHIVE_TAG = guidTemp.ToString(); string sPR_RETENTION_FLAGS = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_RETENTION_FLAGS); string sPR_ARCHIVE_PERIOD = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_ARCHIVE_PERIOD); txtPR_ARCHIVE_TAG.Text = sPR_ARCHIVE_TAG; txtPR_RETENTION_FLAGS.Text = sPR_RETENTION_FLAGS; txtPR_ARCHIVE_PERIOD.Text = sPR_ARCHIVE_PERIOD; } else { txtPR_ARCHIVE_TAG.Text = ""; txtPR_RETENTION_FLAGS.Text = ""; txtPR_ARCHIVE_PERIOD.Text = ""; } } private void SaveForm() { PropertySet oPropertySet = GetPropSet(); _ExchangeService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. Folder oFolder = Folder.Bind(_ExchangeService, _FolderId, oPropertySet); Guid guidPR_ARCHIVE_TAG = new Guid(txtPR_ARCHIVE_TAG.Text.Trim()); // Guid int intPR_RETENTION_FLAGS = Convert.ToInt32(txtPR_RETENTION_FLAGS.Text.Trim()); int intPR_ARCHIVE_PERIOD = Convert.ToInt32(txtPR_ARCHIVE_PERIOD.Text.Trim()); oFolder.SetExtendedProperty(Prop_PR_ARCHIVE_TAG, guidPR_ARCHIVE_TAG.ToByteArray()); oFolder.SetExtendedProperty(Prop_PR_RETENTION_FLAGS, intPR_RETENTION_FLAGS); oFolder.SetExtendedProperty(Prop_PR_ARCHIVE_PERIOD, intPR_ARCHIVE_PERIOD); oFolder.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oFolder.Update(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void txtPR_ARCHIVE_PERIOD_TextChanged(object sender, EventArgs e) { //string s = txtPR_RETENTION_FLAGS.Text.Trim(); //if (s != "") //{ // try // { // int i = Convert.ToInt32(s); // RetentionFlags c = (RetentionFlags)i; // lblInfo.Text = GetRetentionFlagSettingAsString(c); // } // catch (Exception ex) // { // lblInfo.Text = ""; // } //} } string GetRetentionFlagSettingAsString(RetentionFlags r) { string sRet = ""; int i = (int)r; sRet = "0x" + (i.ToString("X4")) + " = "; // https://msdn.microsoft.com/en-us/library/ee202166(v=exchg.80).aspx if (r == RetentionFlags.None) sRet += "None (0x000). "; else { if (r.HasFlag(RetentionFlags.ExplicitTag)) sRet += "ExplicitTag (0x001) + "; if (r.HasFlag(RetentionFlags.UserOverride)) sRet += "UserOverride (0x002) + "; if (r.HasFlag(RetentionFlags.Autotag)) sRet += "Autotag (0x004) + "; if (r.HasFlag(RetentionFlags.PersonalTag)) sRet += "PersonalTag (0x0008) + "; if (r.HasFlag(RetentionFlags.ExplictArchiveTag)) sRet += "ExplictArchiveTag (0x0010) + "; if (r.HasFlag(RetentionFlags.KeepInPlace)) sRet += "KeepInPlace. (0x0020) + "; if (r.HasFlag(RetentionFlags.SystemData)) sRet += "SystemData. (0x0040) + "; if (r.HasFlag(RetentionFlags.NeedsRescan)) sRet += "NeedsRescan. (0x0080) + "; if (r.HasFlag(RetentionFlags.PendingRescan)) sRet += "PendingRescan. (0x0100)"; } if (sRet.EndsWith(" + ")) { sRet = sRet.Remove(sRet.Length - 3, 3); sRet += "."; } return sRet; } //string GetRetentionFlagSettingAsString(RetentionFlags r) //{ // string sRet = ""; // https://msdn.microsoft.com/en-us/library/ee202166(v=exchg.80).aspx // if (r == RetentionFlags.None) // sRet += "None (0x000). "; // else // { // if (r.HasFlag(RetentionFlags.ExplicitTag)) sRet += "ExplicitTag (0x001) + "; // if (r.HasFlag(RetentionFlags.UserOverride)) sRet += "UserOverride (0x002) + "; // if (r.HasFlag(RetentionFlags.Autotag)) sRet += "Autotag (0x004) + "; // if (r.HasFlag(RetentionFlags.PersonalTag)) sRet += "PersonalTag (0x0008) + "; // if (r.HasFlag(RetentionFlags.ExplictArchiveTag)) sRet += "ExplictArchiveTag (0x0010) + "; // if (r.HasFlag(RetentionFlags.KeepInPlace)) sRet += "KeepInPlace. (0x0020) + "; // if (r.HasFlag(RetentionFlags.SystemData)) sRet += "SystemData. (0x0040) + "; // if (r.HasFlag(RetentionFlags.NeedsRescan)) sRet += "NeedsRescan. (0x0080) + "; // if (r.HasFlag(RetentionFlags.PendingRescan)) sRet += "PendingRescan. (0x0100)"; // } // if (sRet.EndsWith(" + ")) // { // sRet.Remove(sRet.Length - 4, 3); // sRet += ".". // } // return sRet; //} [Flags] private enum RetentionFlags { None = 0, ExplicitTag = 1, UserOverride = 2, Autotag = 4, PersonalTag = 8, ExplictArchiveTag = 16, KeepInPlace = 32, SystemData = 64, NeedsRescan = 128, PendingRescan = 256, } private void txtPR_RETENTION_FLAGS_TextChanged(object sender, EventArgs e) { string s = txtPR_RETENTION_FLAGS.Text.Trim(); if (s != "") { try { int i = Convert.ToInt32(s); RetentionFlags c = (RetentionFlags)i; lblInfo.Text = GetRetentionFlagSettingAsString(c); } catch (Exception ex) { string x = ex.Message.ToString(); lblInfo.Text = ""; } } } } }
38.218623
151
0.568008
[ "MIT" ]
manoj75/o365-EWS-Editor
EWSEditor/Forms/Archive/FolderArchiveSettings.cs
9,442
C#
using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Alpaca.Markets { /// <summary> /// Conditions map type for <see cref="PolygonDataClient.GetConditionMapAsync"/> call form Polygon REST API. /// </summary> [JsonConverter(typeof(StringEnumConverter))] [SuppressMessage("ReSharper", "UnusedMember.Global")] public enum TickType { /// <summary> /// Method <see cref="PolygonDataClient.GetConditionMapAsync"/> returns trades conditions. /// </summary> [EnumMember(Value = "trades")] Trades, /// <summary> /// Method <see cref="PolygonDataClient.GetConditionMapAsync"/> returns quotes conditions. /// </summary> [EnumMember(Value = "quotes")] Quotes } }
30.535714
112
0.65614
[ "Apache-2.0" ]
darocha/alpaca-trade-api-csharp
Alpaca.Markets/Enums/TickType.cs
857
C#
using AzureStorageProvider.Azure; using AzureStorageProvider.Collections; using AzureStorageProvider.Helpers; using AzureStorageProvider.Models; using CMS.Core; using CMS.Scheduler; using System; using System.Linq; namespace AzureStorageProvider.Tasks { public class CacheClearingTask : ITask { private IBlobCacheService _blobCacheService = Service.Resolve<IBlobCacheService>(); public string Execute(TaskInfo task) { if (_blobCacheService.CacheType != BlobCacheType.FileSystem) return "Caching of Azure data is disabled or is set to memory. No need to run this task."; var blobCacheService = Service.Resolve<IBlobCacheService>(); var minutes = AccountInfo.Instance.BlobCacheMinutes; var dateThreshold = DateTime.UtcNow.AddMinutes(-minutes); var blobsToDelete = BlobCollection.Instance.GetOutdatedBlobPaths(dateThreshold); var blobsDeleted = 0; var directoriesUninitialized = 0; foreach (var path in blobsToDelete) { // remove the blob blobCacheService.Discard(path); blobsDeleted++; } // clear empty folders in file system if (blobsDeleted > 0) { var folders = System.IO.Directory.GetDirectories(AzurePathHelper.GetTempBlobPath(string.Empty), "*", System.IO.SearchOption.AllDirectories).OrderByDescending(p => p.Length); foreach (var subFolder in folders) { if (System.IO.Directory.Exists(subFolder) && !System.IO.Directory.GetFiles(subFolder).Any() && !System.IO.Directory.EnumerateDirectories(subFolder).Any()) { System.IO.Directory.Delete(subFolder, false); } } } return "OK, discarded metadata of " + blobsDeleted + " blobs, " + directoriesUninitialized + " dirs"; } } }
36.526316
189
0.601825
[ "MIT" ]
Kentico/AzureStorageProvider
k12/src/AzureStorageProvider/Tasks/CacheClearingTask.cs
2,084
C#
// // KinoFog - Deferred fog effect // // Copyright (C) 2015 Keijiro Takahashi // // 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 UnityEngine; using UnityEditor; namespace Kino { [CanEditMultipleObjects] [CustomEditor(typeof(Fog))] public class FogEditor : Editor { SerializedProperty _startDistance; SerializedProperty _useRadialDistance; SerializedProperty _fadeToSkybox; void OnEnable() { _startDistance = serializedObject.FindProperty("_startDistance"); _useRadialDistance = serializedObject.FindProperty("_useRadialDistance"); _fadeToSkybox = serializedObject.FindProperty("_fadeToSkybox"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(_startDistance); EditorGUILayout.PropertyField(_useRadialDistance); EditorGUILayout.PropertyField(_fadeToSkybox); serializedObject.ApplyModifiedProperties(); } } }
37.854545
85
0.720941
[ "MIT" ]
Hifoz/TGAG
Assets/Kino/Fog/Editor/FogEditor.cs
2,082
C#
/* Copyright (c) 2017, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using MatterHackers.MatterControl.Library; using MatterHackers.MatterControl.PartPreviewWindow; using MatterHackers.MatterControl.SlicerConfiguration; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class MatterControlTests { [Test] public async Task ThumbnailGenerationMode() { await MatterControlUtilities.RunTest(async (testRunner) => { // Automation tests should initialize with orthographic thumbnails var item = new FileSystemFileItem(MatterControlUtilities.GetTestItemPath("Rook.amf")); var provider = ApplicationController.Instance.Library.GetContentProvider(item); // Generate thumbnail var stopWatch = Stopwatch.StartNew(); await provider.GetThumbnail(item, 400, 400); Assert.Less(stopWatch.ElapsedMilliseconds, 2000, "Elapsed thumbnail generation for Rook.amf should be less than 2 seconds for expected orthographic mode"); }); } [Test] public async Task View3DOverflowMenus() { await MatterControlUtilities.RunTest(testRunner => { testRunner.WaitForFirstDraw(); testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); testRunner.ClickByName("Model View Button"); testRunner.ClickByName("View3D Overflow Menu"); return Task.CompletedTask; }); } [Test] public async Task PrinterTabRemainsAfterReloadAll() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.WaitForFirstDraw(); // Add Guest printers testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); Assert.AreEqual( 1, ApplicationController.Instance.ActivePrinters.Count(), "One printer should exist after Airwolf add"); testRunner.SwitchToSliceSettings(); // Move to Adhesion tab testRunner.SelectSliceSettingsField(PrinterSettings.Layout.SliceSettings, "skirts"); // Click Brim toggle field forcing ReloadAll testRunner.WaitForReloadAll(() => testRunner.ClickByName("Create Brim Field")); // Ensure tabs remain Assert.AreEqual( 1, ApplicationController.Instance.ActivePrinters.Count(), "One printer should exist after Airwolf add"); testRunner.Delay(2); Assert.AreEqual( 1, ApplicationController.Instance.MainView.TabControl.AllTabs.Select(t => t.TabContent).OfType<PrinterTabPage>().Count(), "One printer tab should exist after ReloadAll"); return Task.CompletedTask; }, maxTimeToRun: 120); } } }
35.965517
159
0.768696
[ "BSD-2-Clause" ]
jingliang2005/MatterControl
Tests/MatterControl.AutomationTests/MatterControlTests.cs
4,174
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Compute.V20171201 { public static class GetLogAnalyticExportRequestRateByInterval { public static Task<GetLogAnalyticExportRequestRateByIntervalResult> InvokeAsync(GetLogAnalyticExportRequestRateByIntervalArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetLogAnalyticExportRequestRateByIntervalResult>("azure-nextgen:compute/v20171201:getLogAnalyticExportRequestRateByInterval", args ?? new GetLogAnalyticExportRequestRateByIntervalArgs(), options.WithVersion()); } public sealed class GetLogAnalyticExportRequestRateByIntervalArgs : Pulumi.InvokeArgs { /// <summary> /// SAS Uri of the logging blob container to which LogAnalytics Api writes output logs to. /// </summary> [Input("blobContainerSasUri", required: true)] public string BlobContainerSasUri { get; set; } = null!; /// <summary> /// From time of the query /// </summary> [Input("fromTime", required: true)] public string FromTime { get; set; } = null!; /// <summary> /// Group query result by Operation Name. /// </summary> [Input("groupByOperationName")] public bool? GroupByOperationName { get; set; } /// <summary> /// Group query result by Resource Name. /// </summary> [Input("groupByResourceName")] public bool? GroupByResourceName { get; set; } /// <summary> /// Group query result by Throttle Policy applied. /// </summary> [Input("groupByThrottlePolicy")] public bool? GroupByThrottlePolicy { get; set; } /// <summary> /// Interval value in minutes used to create LogAnalytics call rate logs. /// </summary> [Input("intervalLength", required: true)] public string IntervalLength { get; set; } = null!; /// <summary> /// The location upon which virtual-machine-sizes is queried. /// </summary> [Input("location", required: true)] public string Location { get; set; } = null!; /// <summary> /// To time of the query /// </summary> [Input("toTime", required: true)] public string ToTime { get; set; } = null!; public GetLogAnalyticExportRequestRateByIntervalArgs() { } } [OutputType] public sealed class GetLogAnalyticExportRequestRateByIntervalResult { /// <summary> /// End time of the operation /// </summary> public readonly string EndTime; /// <summary> /// Api error /// </summary> public readonly Outputs.ApiErrorResponseResult Error; /// <summary> /// Operation ID /// </summary> public readonly string Name; /// <summary> /// LogAnalyticsOutput /// </summary> public readonly Outputs.LogAnalyticsOutputResponseResult Properties; /// <summary> /// Start time of the operation /// </summary> public readonly string StartTime; /// <summary> /// Operation status /// </summary> public readonly string Status; [OutputConstructor] private GetLogAnalyticExportRequestRateByIntervalResult( string endTime, Outputs.ApiErrorResponseResult error, string name, Outputs.LogAnalyticsOutputResponseResult properties, string startTime, string status) { EndTime = endTime; Error = error; Name = name; Properties = properties; StartTime = startTime; Status = status; } } }
32.444444
264
0.609344
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Compute/V20171201/GetLogAnalyticExportRequestRateByInterval.cs
4,088
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CitySimulator.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { var temp = new global::System.Resources.ResourceManager("CitySimulator.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
42.31746
142
0.617779
[ "MIT" ]
wokste/SilverStreetSimulator
CitySimulator/Properties/Resources.Designer.cs
2,668
C#
#region File Description //----------------------------------------------------------------------------- // CpuVertex.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using Microsoft.Xna.Framework; namespace CpuSkinningDataTypes { /// <summary> /// A struct that contains the vertex information we need on the CPU. /// This type is not used for a GPU vertex. /// </summary> public struct CpuVertex { public Vector3 Position; public Vector3 Normal; public Vector2 TextureCoordinate; public Vector4 BlendWeights; public Vector4 BlendIndices; } }
28.333333
79
0.541176
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/CPUSkinningSample_4_0/CpuSkinningDataTypes/CpuVertex.cs
767
C#
/************************************************************************ AvalonDock Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at https://opensource.org/licenses/MS-PL ************************************************************************/ namespace WinIO.AvalonDock.Layout { /// <summary> /// Defines an API to layout model that can manipluate its child entries by moving /// them from one index to the other or by removing a particular child from its child collection. /// </summary> public interface ILayoutPane : ILayoutContainer, ILayoutElementWithVisibility { /// <summary>Move a child entry from the <paramref name="oldIndex"/> to the <paramref name="newIndex"/>.</summary> /// <param name="oldIndex"></param> /// <param name="newIndex"></param> void MoveChild(int oldIndex, int newIndex); /// <summary>Remove a child entry from the collection of children at the <paramref name="childIndex"/>.</summary> /// <param name="childIndex"></param> void RemoveChildAt(int childIndex); } }
41.888889
116
0.628647
[ "Apache-2.0" ]
sak9188/WinIO2
WinIO/WinIO/AvalonDock/Layout/ILayoutPane.cs
1,131
C#
using Microsoft.AspNet.Mvc.Rendering; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace IdentitySample.Models { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
28.867347
110
0.59597
[ "Apache-2.0" ]
stuartleeks/Identity
samples/IdentitySample.Mvc/Models/AccountViewModels.cs
2,831
C#
//----------------------------------------------------------------------- // <copyright file="KPURegistration.cs" company="Breanos GmbH"> // Copyright Notice: // DAIPAN - This file, program or part of a program is considered part of the DAIPAN framework by Breanos GmbH for Industrie 4.0 // Published in 2018 by Gerhard Eder gerhard.eder@breanos.com and Achim Bernhard achim.bernhard@breanos.com // To the extent possible under law, the publishers have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. // You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // <date>Monday, December 3, 2018 3:34:35 PM</date> // </copyright> //----------------------------------------------------------------------- using BreanosConnectors; using BreanosConnectors.ActiveMqConnector; using BreanosConnectors.Interface; using BreanosConnectors.Kpu.Communication.Common; using NLog; using System; using System.Collections.Generic; using System.IO.Compression; using System.Xml.Serialization; using System.IO; using CWF.Interfaces; using Microsoft.ServiceFabric.Services.Remoting.Client; using System.Threading.Tasks; using Microsoft.ServiceFabric.Actors.Client; using Microsoft.ServiceFabric.Actors; namespace CWFStateless { public class KpuStateEventArg : EventArgs { public KpuStateEventArg(string KpuId, string Commando) { this.KpuId = KpuId; this.Commando = Commando; } public string KpuId { get; set; } public string Commando { get; set; } } public class KPURegistration //: INotifyPropertyChanged { private NLog.Logger logger = LogManager.GetCurrentClassLogger(); public string ConnectionString { get; set; } = "activemq:tcp://192.168.50.1:61616"; public string User { get; set; } = "admin"; public string Password { get; set; } = "admin"; public static readonly string QueueString = "queue://LineTopic_1"; public readonly string KpuQueueString = "queue://KpuQueue"; public readonly string ManagementQueueString = "queue://ManagementQueue"; public readonly string AssistantQueueString = "queue://AssistantQueue"; string KpuDir { get; set; } string TempDir { get; set; } string ActivitiesDir { get; set; } string FsmDir { get; set; } string WorkflowsDir { get; set; } string XsdDir { get; set; } static public readonly string ZipFileName = "out.zip"; static public readonly string FileDelimiter = "\\"; private Connector receiveConnector; public delegate void KpuStateEventHandler(object sender, KpuStateEventArg e); public KpuStateEventHandler PropertyChanged; // public event PropertyChangedEventHandler PropertyChanged; public KPURegistration(string kpuPath, string tempDir, string endpoint, string user, string password, string activitiesDir, string fsmDir, string workflowsDir, string xsdDir) { KpuDir = kpuPath; TempDir = tempDir; ActivitiesDir = activitiesDir; FsmDir = fsmDir; WorkflowsDir = workflowsDir; XsdDir = xsdDir; ConnectionString = endpoint; User = user; Password = password; //Init receive queue RegisterKpuQueue(); InitConfigureRoutes(); } public async void InitConfigureRoutes() { logger.Debug($"InitConfigureRoutes."); var registerForMessagesAtBlackboardRequest = new RoutingRequest() { Id = "ToHActor", Path = KpuQueueString, ContentTypes = new string[] { BrokerCommands.EXECUTE_REQUEST, BrokerCommands.PACKAGE_REQUEST, BrokerCommands.KPU_DEPLOYMENT, }, }; var registerPackage = BreanosConnectors.SerializationHelper.Pack(registerForMessagesAtBlackboardRequest); await receiveConnector.SendAsync(registerPackage, QueueString, BrokerCommands.CONFIGURE_ROUTES); logger.Trace($"Registration with Blackboard for {QueueString} complete."); var registerForMessagesAtBlackboardRequest2 = new RoutingRequest() { Id = "ToHActor", Path = AssistantQueueString, ContentTypes = new string[] { //BrokerCommands.KPU_DEPLOYMENT, BrokerCommands.REQUESTKPUID, //BrokerCommands.TELLKPUID }, }; var registerPackage2 = BreanosConnectors.SerializationHelper.Pack(registerForMessagesAtBlackboardRequest2); await receiveConnector.SendAsync(registerPackage2, QueueString, BrokerCommands.CONFIGURE_ROUTES); var registerForMessagesAtBlackboardRequest3 = new RoutingRequest() { Id = "ToHActor", Path = ManagementQueueString, ContentTypes = new string[] { //BrokerCommands.KPU_DEPLOYMENT, //BrokerCommands.REQUESTKPUID, BrokerCommands.TELLKPUID }, }; var registerPackage3 = BreanosConnectors.SerializationHelper.Pack(registerForMessagesAtBlackboardRequest2); await receiveConnector.SendAsync(registerPackage3, QueueString, BrokerCommands.CONFIGURE_ROUTES); logger.Trace($"Registration with Blackboard for {QueueString} complete."); } public async void RegisterKpuQueue() { receiveConnector = new Connector(); bool connectOk = await receiveConnector.ConnectAsync(ConnectionString, User, Password); receiveConnector.Message += KpuMessageHandlingMethod; receiveConnector.ListenAsync(KpuQueueString).Wait(); } private void KpuMessageHandlingMethod(object sender, OnMessageEventArgs e) { if (e.Properties["ContentType"] == null) return; string s = e.Content; IDictionary<string, object> obj = e.Properties; if ((e.Properties["ContentType"] as string).CompareTo(BrokerCommands.PACKAGE_REQUEST) == 0) { WriteManifest(KpuDir, "HanoiLibrary.HanoiWorkflowState"); GenerateZipFile(KpuDir, TempDir); PublishToServiceBus(TempDir + KPURegistration.FileDelimiter + KPURegistration.ZipFileName, ConnectionString, QueueString); } else if ((e.Properties["ContentType"] as string).CompareTo(BrokerCommands.EXECUTE_REQUEST) == 0) { if (SerializationHelper.TryUnpack(e.Content, out ExecuteRequest executeRequestDto)) { logger.Debug($"ExecuteRequest {executeRequestDto}"); PropertyChanged?.Invoke(this, new KpuStateEventArg(executeRequestDto.KpuId, executeRequestDto.Action)); } } else if ((e.Properties["ContentType"] as string).CompareTo(BrokerCommands.KPU_DEPLOYMENT) == 0) { logger.Debug($"In KpuMessageHandlingMethod KPU_DEPLOYMENT branch"); KpuDeployment(e); StartActor(e); } } /// <summary> /// /// </summary> /// <param name="e"></param> private void StartActor(OnMessageEventArgs e) { IToHActor actorClient2 = ActorProxy.Create<IToHActor>(ActorId.CreateRandom(), new Uri("fabric:/CWF.Fabric.Services/ToHActorService")); Task<int> ii = actorClient2.StartKpuActor(e.Properties["KpuId"] as string, WorkflowsDir, XsdDir, ActivitiesDir, FsmDir, KpuDir, ConnectionString, User, Password); int i = ii.Result; } static void CopyFiles(DirectoryInfo source, DirectoryInfo destination, bool overwrite, string searchPattern) { FileInfo[] files = source.GetFiles(searchPattern); //this section is what's really important for your application. foreach (FileInfo file in files) { file.CopyTo(destination.FullName + "\\" + file.Name, overwrite); } } private void KpuDeployment(OnMessageEventArgs e) { var isUnpackSuccessful = BreanosConnectors.SerializationHelper.TryUnpack(e.Content, out byte[] zipData); string filePath = TempDir + "\\" + e.Properties["KpuId"] + ".zip"; System.IO.File.WriteAllBytes(filePath, zipData); string extension = System.IO.Path.GetExtension(filePath); string zipFilePath = filePath.Substring(0, filePath.Length - extension.Length); System.IO.Compression.ZipFile.ExtractToDirectory(filePath, zipFilePath, true); //Copy Activites DirectoryInfo src = new DirectoryInfo(zipFilePath + "\\Activities"); DirectoryInfo dst = new DirectoryInfo(ActivitiesDir); CopyFiles(src, dst, true, "*.*"); //Copy FSM src = new DirectoryInfo(zipFilePath + "\\FSM"); dst = new DirectoryInfo(FsmDir); CopyFiles(src, dst, true, "*.*"); //Copy KPU src = new DirectoryInfo(zipFilePath + "\\KPU"); dst = new DirectoryInfo(KpuDir); CopyFiles(src, dst, true, "*.*"); //Copy Workflows src = new DirectoryInfo(zipFilePath + "\\Workflows"); dst = new DirectoryInfo(WorkflowsDir); CopyFiles(src, dst, true, "*.*"); } public void WriteManifest(string FileName, string initializationClassName) { using (var writer = new System.IO.StreamWriter(FileName + "\\" + "Manifest.ini")) { var serializer = new XmlSerializer(typeof(Manifest)); Manifest manifest = new Manifest() { ModelClass = initializationClassName, Assemblies = new List<Assembly> { new Assembly { Value = "HanoiLibraryStandard.dll" } }, Views = new List<View> { new View { Value = "Hanoi.xaml" } }, Files = new List<BreanosConnectors.Kpu.Communication.Common.File> { new BreanosConnectors.Kpu.Communication.Common.File { Value = "Hanoi.gif" } }, }; serializer.Serialize(writer, manifest); writer.Flush(); } } public void GenerateZipFile(string SourceFilesPath, string TempFilesPath) { string startPath = SourceFilesPath; string zipPath = TempFilesPath + FileDelimiter + ZipFileName; if (System.IO.File.Exists(zipPath) == true) { System.IO.File.Delete(zipPath); } ZipFile.CreateFromDirectory(startPath, zipPath); } /// <summary> /// /// </summary> /// <returns></returns> private static string GetMenuString() { var someString = String.Join( Environment.NewLine, @"<?xml version=""1.0"" encoding=""utf-8""?>", @"<MenuGroup xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" GroupPriority=""1"" PositionAnchor=""1"">", @" <MenuItem ItemIdentifier=""HanoiMaster"" TextResourceId=""txt.HanoiMaster"" IconXamlGeometry=""icon.HanoiMaster"" PermissionIdentifier=""Hanoi.view"">", " <Children>", @" <MenuItem ItemIdentifier = ""HanoiRestart"" TextResourceId = ""kpu.Hanoi.RestartHanoi"" Command = ""RestartKpu"" IconXamlGeometry = ""icon.HanoiRestart"" PermissionIdentifier = ""Hanoi.restart"" />", @" <MenuItem ItemIdentifier = ""HanoiStop"" TextResourceId = ""kpu.Hanoi.StopHanoi"" Command = ""StopKpu"" IconXamlGeometry = ""icon.HanoiStop"" PermissionIdentifier = ""Hanoi.stop"" />", @" <MenuItem ItemIdentifier = ""HanoiStart"" TextResourceId = ""kpu.Hanoi.StartHanoi"" Command = ""StartKpu"" IconXamlGeometry = ""icon.HanoiStart"" PermissionIdentifier = ""Hanoi.start"" />", @" <MenuItem ItemIdentifier = ""Management"" TextResourceId = ""Administer"" PermissionIdentifier = ""Hanoi.manage"" >", " <Children>", @" <MenuItem ItemIdentifier=""Uptime"" Command=""ViewUptime"" IconXamlGeometry=""B32 T9 L12 20"" PermissionIdentifier=""Hanoi.manage.uptime.view"" />", @" <MenuItem ItemIdentifier = ""Downtimes"" PermissionIdentifier = ""Hanoi.manage.downtime"" >", @" <Children>", @" <MenuItem ItemIdentifier = ""PlannedDowntimes"" TextResourceId = ""x.PlannedDowntimes"" Command = ""nav.Downtimes"" CommandParameter = ""t=planned"" IconXamlGeometry = ""L20 10 B30 30"" PermissionIdentifier = ""Hanoi.manage.downtimes.view"" />", @" <MenuItem ItemIdentifier = ""UnplannedDowntimes"" TextResourceId = ""x.UnplannedDowntimes"" Command = ""nav.Downtimes"" CommandParameter = ""t=unplanned"" IconXamlGeometry = ""L20 10 B30 30"" PermissionIdentifier = ""Hanoi.manage.downtimes.view"" />", @" <MenuItem ItemIdentifier = ""AllDowntimes"" TextResourceId = ""x.AllDowntimes"" Command = ""nav.Downtimes"" CommandParameter = ""t=all"" IconXamlGeometry = ""L20 10 B30 30"" PermissionIdentifier = ""Hanoi.manage.downtimes.view"" />", @" </Children>", @" </MenuItem>", @" </Children>", @" </MenuItem>", @" </Children>", @" </MenuItem>", @" <MenuItem ItemIdentifier = ""HanoiStop2"" TextResourceId = ""kpu.Hanoi.StopHanoi"" Command = ""StopKpu"" IconXamlGeometry = ""B32 T9 L12 20"" PermissionIdentifier = ""Hanoi.stop"" />", @" <MenuItem ItemIdentifier = ""HanoiStart2"" TextResourceId = ""kpu.Hanoi.StartHanoi"" Command = ""StartKpu"" IconXamlGeometry = ""B32 T9 L12 20"" PermissionIdentifier = ""Hanoi.start"" />", @"</MenuGroup>"); return someString; } public void RegisterKPU(string kpuId, string connectionString, string queueString) { logger.Debug($"In RegisterKPU Parameters ConnectionString:{connectionString}, QueueString:{queueString}"); var connector = new Connector(); connector.ConnectAsync(connectionString, User, Password).Wait(); KpuRegistrationRequest kpuRegistration = new KpuRegistrationRequest(); kpuRegistration.KpuId = kpuId;// ToHActor.KPU_ID; KpuPermissionRequest[] request = new KpuPermissionRequest[2]; request[0] = new KpuPermissionRequest() { PermissionIdentifier = "view" }; request[1] = new KpuPermissionRequest() { PermissionIdentifier = "subscribe" }; kpuRegistration.PermissionRequests = request; kpuRegistration.MenuXmlString = GetMenuString(); string packedStr = SerializationHelper.Pack(kpuRegistration); connector.SendAsync(packedStr, queueString, BrokerCommands.KPU_REGISTRATION, null).Wait(); } public async void PublishToServiceBus(string ZipFilePath, string connectionString, string queueString) { byte[] array = System.IO.File.ReadAllBytes(ZipFilePath); string packedSerialized = SerializationHelper.Pack(array); var connector = new Connector(); bool b = await connector.ConnectAsync(connectionString, User, Password); connector.SendAsync(packedSerialized, queueString, BrokerCommands.PACKAGE, new (string, object)[]{ ("KpuId", "Hanoi") }).Wait(); } } }
46.2493
291
0.598147
[ "CC0-1.0" ]
BREANOS-ABE/daipan
Towers of Hanoi Demo/CWF Fabric Services/CWFStateless/KPURegistration.cs
16,513
C#
namespace EA.Prsd.Email { public interface ITemplateLoader { string LoadTemplate(string name); } }
17
41
0.655462
[ "Unlicense" ]
DEFRA/prsd-iws
src/EA.Prsd.Email/ITemplateLoader.cs
121
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Filters; namespace BTCPayServer.Filters { public class XXSSProtectionAttribute : Attribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { context.HttpContext.Response.SetHeaderOnStarting("X-XSS-Protection", "1; mode=block"); } } }
24.227273
98
0.707317
[ "MIT" ]
dergigi/btcpayserver
BTCPayServer/Filters/XXSSProtectionAttribute.cs
535
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dp6")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Dp6")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("68a27fe1-bbc0-4f2f-a814-3961f914aae7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.135135
84
0.744541
[ "Apache-2.0" ]
kellybirr/dp6
Dp6/Properties/AssemblyInfo.cs
1,377
C#
using System.Collections; using System.Collections.Generic; using Unity.Entities; using UnityEngine; public class TimeSystem : ComponentSystem { public struct TimeEntities { public TimeComponent timeComponent; } public float time; public float timeScale = 1f; protected override void OnUpdate() { time += Time.deltaTime; } protected override void OnStartRunning() { time = 0f; } }
22
46
0.684091
[ "MIT" ]
rzmarcin/ecs-out-of-space
Assets/Scripts/Time/TimeSystem.cs
442
C#
// <copyright file="PreSharedKey.cs" company="Arm"> // Copyright (c) Arm. All rights reserved. // </copyright> namespace MbedCloudSDK.Bootstrap.Model { using System; using Mbed.Cloud.Common; using MbedCloudSDK.Common; using MbedCloudSDK.Common.Extensions; using Newtonsoft.Json; /// <summary> /// PreSharedKey /// </summary> /// <para> /// For more information about such keys, have a look at <a href="https://cloud.mbed.com/docs/latest/connecting/mbed-client-lite-security-considerations.html"/> /// </para> public class PreSharedKey : Entity { /// <summary> /// Gets or sets the EndpointName /// </summary> /// <para> /// Note: It has to be 16-64 <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters">printable</a> (non-control) ASCII characters. It also must be globally unique. Consider using vendor-MAC-ID-device-model. /// </para> /// <example> /// "myEndpoint.host.com" /// </example> /// <returns>The Endpoint Name</returns> public string EndpointName { get; set; } /// <summary> /// Gets or sets the secret hex /// </summary> /// <para> /// Note: It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits. /// </para> /// <example> /// "4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a" /// </example> /// <returns>The Secret hex</returns> public string SecretHex { get; set; } /// <summary> /// Gets created at /// </summary> /// <value> /// The created at. /// </value> [JsonProperty] public DateTime? CreatedAt { get; private set; } /// <summary> /// Create a CreateRequest /// </summary> /// <param name="key">The PreSharedKey</param> /// <returns>Generated PSK</returns> public static connector_bootstrap.Model.PreSharedKey CreateRequest(PreSharedKey key) { return new connector_bootstrap.Model.PreSharedKey(EndpointName: key.EndpointName, SecretHex: key.SecretHex); } /// <summary> /// Map generated PSK to PSK /// </summary> /// <param name="key">The key to map</param> /// <returns>PSK</returns> public static PreSharedKey Map(connector_bootstrap.Model.PreSharedKeyWithoutSecret key) { return new PreSharedKey { EndpointName = key.EndpointName, CreatedAt = key.CreatedAt, }; } /// <summary> /// Returns the string presentation of the object. /// </summary> /// <returns>String presentation of the object.</returns> public override string ToString() => this.DebugDump(); } }
34.8
225
0.576065
[ "Apache-2.0" ]
ARMmbed/mbed-cloud-sdk-dotnet
src/Legacy/Bootstrap/Model/PreSharedKey.cs
2,958
C#
using System; using System.Runtime.InteropServices; namespace hds { public class AttributeClass2513 :GameObject { public Attribute Orientation = new Attribute(16, "Orientation"); public Attribute Position = new Attribute(24, "Position"); public Attribute HalfExtents = new Attribute(12, "HalfExtents"); public AttributeClass2513(string name,UInt16 _goid) : base(3, 0, name, _goid, 0xFFFFFFFF) { AddAttribute(ref Orientation, 0, -1); AddAttribute(ref Position, 1, -1); AddAttribute(ref HalfExtents, 2, -1); } } }
24.166667
68
0.677586
[ "MIT" ]
hdneo/mxo-hd
hds/resources/gameobjects/definitions/AttributeClasses/AttributeClass2513.cs
580
C#
namespace Abstractions.Commands { public interface IUnitCommand { public CommandType CommandType { get; } } public enum CommandType { None = 0, Attack = 1, Move = 2, Stop = 3, Patrol =43, } }
16.5625
47
0.520755
[ "Apache-2.0" ]
DSvinka/StrategyGame
Assets/Code/Abstractions/Commands/IUnitCommand.cs
267
C#
using Gif.Service.Attributes; using Gif.Service.Const; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Gif.Service.Models { [CrmEntity("cc_capabilities")] [DataContract] public class Capability : EntityBase { [DataMember] [CrmIdField] [CrmFieldName("cc_capabilityid")] public override Guid Id { get; set; } [DataMember] [CrmFieldName("cc_name")] public string Name { get; set; } [DataMember] [CrmFieldName("cc_description")] public string Description { get; set; } [DataMember] [CrmFieldName("cc_url")] public string Url { get; set; } [DataMember] [CrmFieldName("cc_type")] public string Type { get; set; } [CrmEntityRelationAttribute(RelationshipNames.CapabilityFramework)] public IList<Framework> Frameworks { get; set; } public Capability() { } public Capability(JToken token) : base(token) { } } }
23.042553
75
0.618652
[ "MIT" ]
TrevorDArcyEvans/NHSBuyingCatalogue
beta-private/api/NHSD.GPITF.BuyingCatalog/crm/Gif.Datastore.CRM/Models/Capability.cs
1,085
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; using DotNetTemplatesCreator.Models; namespace DotNetTemplatesCreator.Utils { public class CreateProjectsUtility { private readonly string _basePath; public CreateProjectsUtility() { var currentPath = AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin", StringComparison.Ordinal)) .Split("\\"); // remove last empty index of array currentPath = currentPath.Take(currentPath.Length - 1).ToArray(); _basePath = string.Join(Path.DirectorySeparatorChar, currentPath.Take(currentPath.Length - 1).Append("Templates").ToArray()); if(!Directory.Exists(_basePath)) Directory.CreateDirectory(_basePath); } private void RemoveCurrentProjects() { try { var baseDirs = new DirectoryInfo(_basePath).GetDirectories(); foreach(var directory in baseDirs) { Directory.Delete(directory.FullName, true); } var baseFiles = new DirectoryInfo(_basePath).GetFiles(); foreach(var file in baseFiles) { File.Delete(file.FullName); } Console.WriteLine(" old projects removed"); } catch(Exception e) { Console.WriteLine(e); throw; } } private void CreateProject(string projectName, string createProjectCommandName) { try { using var powerShell = PowerShell.Create(); var projName = projectName; var projPath = $"{_basePath}\\{projName}"; powerShell.AddScript($"cd \"{_basePath}\""); powerShell.AddScript($"mkdir \"{projName}\""); powerShell.AddScript($"cd \"{projPath}\""); powerShell.AddScript("dotnet new sln"); powerShell.AddScript($"dotnet new {createProjectCommandName}"); powerShell.AddScript($"dotnet sln \"{projName}.sln\" add \"{projName}.csproj\""); powerShell.Invoke(); Console.WriteLine(" {0} created", projName); } catch(Exception e) { Console.WriteLine(e); throw; } } private List<ProjectTemplateModel> TemplatesList() { try { var templates = new List<ProjectTemplateModel>(); using PowerShell power = PowerShell.Create(); power.AddScript("dotnet new --list --type project"); var result = power.Invoke(); for(int i = 2; i < result.Count; i++) { var template = (string)result[i].BaseObject; var splitTemplate = template.Split(" ") .Distinct() .Where(x => !string.IsNullOrEmpty(x)).ToArray(); if(splitTemplate.Any(c => c.Contains("C#")) || splitTemplate.Any(c => c.Contains("F#"))) { templates.Add(new ProjectTemplateModel() { TemplateName = splitTemplate[0], ShortName = splitTemplate[1].Trim(), Langs = splitTemplate[2], Tags = splitTemplate[3] }); } } return templates; } catch(Exception e) { Console.WriteLine(e); throw; } } private List<FileInfo> FindAllProjectFiles() { try { var projects = new List<FileInfo>(); var directories = new DirectoryInfo(_basePath).GetDirectories("*", new EnumerationOptions { AttributesToSkip = FileAttributes.Hidden }); foreach(var directory in directories) { projects.AddRange(directory.GetFiles().Where(f => f.Extension == ".csproj")); } return projects; } catch(Exception e) { Console.WriteLine(e); throw; } } public void AddLicenseInformation() { try { var str = new StringBuilder(); var projects = FindAllProjectFiles(); foreach(var proj in projects) { str.Append( "<!-- This Project Is Auto Generated By dotnet-cli -->\n<!-- Source Code: https://github.com/srezasm/DotNet-Core-Projects-Template -->\n\n" ); str.Append(File.ReadAllText(proj.FullName)); File.WriteAllText(proj.FullName, str.ToString()); str.Clear(); } Console.WriteLine(" license information added to projects"); } catch(Exception e) { Console.WriteLine(e); throw; } } public void Execute() { RemoveCurrentProjects(); var tasks = new List<Task>(); foreach(var item in TemplatesList()) { tasks.Add(Task.Run(() => CreateProject(item.TemplateName, item.ShortName))); } Task.WaitAll(tasks.ToArray()); AddLicenseInformation(); } } }
31.278107
157
0.539728
[ "MIT" ]
srezasm/DotNet-Core-Projects-Template
src/Utils/CreateProjectsUtility.cs
5,288
C#
#region License // Copyright (c) 2021 Peter Šulek / ScaleHQ Solutions s.r.o. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Linq; using LHQ.App.Code; using LHQ.App.Localization; using LHQ.App.Model; using LHQ.App.Services.Interfaces; using LHQ.Data; using LHQ.Utils.Extensions; namespace LHQ.App.ViewModels { public class ProjectSettingsViewModel : ShellViewModelBase { private bool _resourcesUnderRoot; private bool _categories; private bool _resources; private string _layoutImage; public ProjectSettingsViewModel(IShellViewContext shellViewContext) : base(shellViewContext, false) { ModelOptions modelOptions = shellViewContext.ShellViewModel.ModelOptions; Categories = modelOptions.Categories; Resources = !modelOptions.Categories; ResourcesUnderRoot = modelOptions.Resources == ModelOptionsResources.All; } private ITreeViewService TreeViewService => ShellViewContext.TreeViewService; public string LayoutImage { get => _layoutImage; set => SetProperty(ref _layoutImage, value); } public bool Resources { get => _resources; set { _resources = value; if (value != _resources) { _resources = value; RaisePropertyChanged(); if (value && Categories) { Categories = false; } } } } public bool Categories { get => _categories; set { if (value != _categories) { _categories = value; RaisePropertyChanged(); if (value && Resources) { Resources = false; } } } } public bool ResourcesUnderRoot { get => _resourcesUnderRoot; set => SetProperty(ref _resourcesUnderRoot, value); } public bool Validate() { var valid = true; var dialogCaption = Strings.Operations.ProjectSettings.ValidationErrorCaption; if (Categories) { if (!ResourcesUnderRoot) { bool hasAnyResource = TreeViewService.RootModel.Children.Any(x => x.ElementType == TreeElementType.Resource); if (hasAnyResource) { DialogService.ShowError(dialogCaption, Strings.Operations.ProjectSettings.ValidationError1, null); valid = false; } } } else { bool hasAnyCategory = TreeViewService.FindAllElements(x => x.ElementType == TreeElementType.Category).Any(); if (hasAnyCategory) { DialogService.ShowError(dialogCaption, Strings.Operations.ProjectSettings.ValidationError2, null); valid = false; } } return valid; } public void Save(ModelOptions modelOptions) { if (modelOptions == null) { throw new ArgumentNullException(nameof(modelOptions)); } modelOptions.Categories = Categories; modelOptions.Resources = ResourcesUnderRoot ? ModelOptionsResources.All : ModelOptionsResources.Categories; if (!Categories) { modelOptions.Resources = ModelOptionsResources.All; } } protected internal override void RaisePropertyChanged(string propertyName = "") { base.RaisePropertyChanged(propertyName); if (propertyName == nameof(Categories) || propertyName == nameof(Resources) || propertyName == nameof(ResourcesUnderRoot) || propertyName == string.Empty) { var theme = (VisualManager.Instance.Theme == AppVisualTheme.Automatic ? AppVisualTheme.Light : VisualManager.Instance.Theme).ToLowerInvariant(); int imageNo = 3; if (Categories) { imageNo = ResourcesUnderRoot ? 1 : 2; } var image = $"/images/layout0{imageNo}-{theme}.png"; LayoutImage = ResourceHelper.GetImageComponentUri(image); } } } }
32.926554
136
0.56383
[ "MIT" ]
psulek/lhqeditor
src/App/ViewModels/ProjectSettingsViewModel.cs
5,831
C#
// Copyright (c) Converter Systems LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Workstation.ServiceModel.Ua { public interface IServiceRequest : IEncodable { RequestHeader RequestHeader { get; set; } } }
31.8
101
0.732704
[ "MIT" ]
dojo90/opc-ua-client
UaClient/ServiceModel/Ua/IServiceRequest.cs
320
C#
// MbUnit Test Framework // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // MbUnit HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace MbUnit.Core.Framework { using System; using MbUnit.Core.Invokers; using System.Reflection; /// <summary> /// This is the base class for attributes that can decorate tests. /// </summary> /// <include file="MbUnit.Framework.Doc.xml" path="doc/remarkss/remarks[@name='DecoratorPatternAttribute']"/> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public abstract class DecoratorPatternAttribute : PatternAttribute { protected DecoratorPatternAttribute() {} protected DecoratorPatternAttribute(string description) :base(description) {} public static IRunInvoker DecoreInvoker(MethodInfo mi, IRunInvoker invoker) { // looking for decoring attributes foreach(DecoratorPatternAttribute deco in mi.GetCustomAttributes(typeof(DecoratorPatternAttribute),true)) { invoker = deco.GetInvoker(invoker); } return invoker; } public abstract IRunInvoker GetInvoker(IRunInvoker wrapper); } }
33.634921
112
0.71496
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v2
src/mbunit/MbUnit.Framework/Core/Framework/DecoratorPatternAttribute.cs
2,119
C#
using System; using System.Collections.Generic; using System.Linq; namespace Ademund.Utils.TypeExtensions { public static class TypeExtensionMethods { // Queries a type for a list of all attributes of a specific type. public static IEnumerable<T> GetAttributes<T>(this Type typeWithAttributes) where T : Attribute { // Try to find the configuration attribute for the default logger if it exists Attribute[] configAttributes = Attribute.GetCustomAttributes(typeWithAttributes, typeof (T), false); // get just the first one if (configAttributes.Length > 0) { foreach (T attribute in configAttributes) { yield return attribute; } } } // Queries a type for the first attribute of a specific type. public static T GetAttribute<T>(this Type typeWithAttributes) where T : Attribute { return GetAttributes<T>(typeWithAttributes).FirstOrDefault(); } } }
34.677419
112
0.619535
[ "MIT" ]
netclectic/Ademund.Utils
source/Ademund.Utils.General/TypeExtensions/TypeExtensions.cs
1,075
C#
using Microsoft.AspNetCore.Mvc; namespace StoreBuilder.Web.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
28.030303
106
0.652973
[ "Apache-2.0" ]
ahammadfaishal/sallascraper
src/StoreBuilder.Web/Controllers/WeatherForecastController.cs
925
C#
using Vulkan; using static Vulkan.VulkanNative; namespace Veldrid.Vk { internal unsafe class VkTextureView : TextureView { private readonly VkGraphicsDevice _gd; private readonly VkImageView _imageView; private bool _destroyed; private string? _name; public VkImageView ImageView => _imageView; public new VkTexture Target => (VkTexture)base.Target; public ResourceRefCount RefCount { get; } public override bool IsDisposed => _destroyed; public VkTextureView(VkGraphicsDevice gd, in TextureViewDescription description) : base(description) { _gd = gd; VkImageViewCreateInfo imageViewCI = VkImageViewCreateInfo.New(); VkTexture tex = Util.AssertSubtype<Texture, VkTexture>(description.Target); imageViewCI.image = tex.OptimalDeviceImage; imageViewCI.format = VkFormats.VdToVkPixelFormat(Format, (Target.Usage & TextureUsage.DepthStencil) != 0); VkImageAspectFlags aspectFlags; if ((description.Target.Usage & TextureUsage.DepthStencil) == TextureUsage.DepthStencil) { aspectFlags = VkImageAspectFlags.Depth; } else { aspectFlags = VkImageAspectFlags.Color; } imageViewCI.subresourceRange = new VkImageSubresourceRange( aspectFlags, description.BaseMipLevel, description.MipLevels, description.BaseArrayLayer, description.ArrayLayers); if ((tex.Usage & TextureUsage.Cubemap) == TextureUsage.Cubemap) { imageViewCI.viewType = description.ArrayLayers == 1 ? VkImageViewType.ImageCube : VkImageViewType.ImageCubeArray; imageViewCI.subresourceRange.layerCount *= 6; } else { switch (tex.Type) { case TextureType.Texture1D: imageViewCI.viewType = description.ArrayLayers == 1 ? VkImageViewType.Image1D : VkImageViewType.Image1DArray; break; case TextureType.Texture2D: imageViewCI.viewType = description.ArrayLayers == 1 ? VkImageViewType.Image2D : VkImageViewType.Image2DArray; break; case TextureType.Texture3D: imageViewCI.viewType = VkImageViewType.Image3D; break; } } vkCreateImageView(_gd.Device, ref imageViewCI, null, out _imageView); RefCount = new ResourceRefCount(DisposeCore); } public override string? Name { get => _name; set { _name = value; _gd.SetResourceName(this, value); } } public override void Dispose() { RefCount.Decrement(); } private void DisposeCore() { if (!_destroyed) { _destroyed = true; vkDestroyImageView(_gd.Device, ImageView, null); } } } }
33.534653
129
0.53853
[ "MIT" ]
TechnologicalPizza/veldrid
src/Veldrid/Vk/VkTextureView.cs
3,389
C#
namespace SadConsole.Themes { using System.Runtime.Serialization; /// <summary> /// A theme for a Window object. /// </summary> [DataContract] public class ControlsConsoleTheme { /// <summary> /// The style of of the console surface. /// </summary> [DataMember] public Cell FillStyle; /// <summary> /// Creates a new controls console theme with the specified colors. /// </summary> /// <param name="themeColors">The colors used with this theme.</param> public ControlsConsoleTheme(Colors themeColors) => RefreshTheme(themeColors); /// <summary> /// Creates a new theme without specifying the colors. /// </summary> protected ControlsConsoleTheme() { } /// <summary> /// Returns a clone of this object. /// </summary> /// <returns>The cloned object.</returns> public ControlsConsoleTheme Clone() { var newItem = new ControlsConsoleTheme { FillStyle = FillStyle.Clone() }; return newItem; } /// <summary> /// Draws the theme to the console. /// </summary> /// <param name="console">Console associated with the theme.</param> /// <param name="hostSurface">Surface used for drawing.</param> public virtual void Draw(ControlsConsole console, CellSurface hostSurface) { hostSurface.DefaultForeground = FillStyle.Foreground; hostSurface.DefaultBackground = FillStyle.Background; hostSurface.Fill(hostSurface.DefaultForeground, hostSurface.DefaultBackground, FillStyle.Glyph, null); } /// <summary> /// Updates the theme with a color scheme. /// </summary> /// <param name="themeColors">The colors to update with.</param> public virtual void RefreshTheme(Colors themeColors) => FillStyle = new Cell(themeColors.ControlHostFore, themeColors.ControlHostBack); } }
34.416667
143
0.59661
[ "MIT" ]
Coleoid/SadConsole
src/SadConsole/Themes/ControlsConsoleTheme.cs
2,067
C#
using System; using System.Collections.Generic; using MongoDragons.Managers; using MongoDragons.Types; namespace MongoDragons { class Program { static void Main(string[] args) { string keyword = ""; // Initialize our database provider. Setup.Initialize(); while (true) { // Search for dragons. List<Dragon> dragons = DragonManager.Find(keyword); // Display the dragons. DisplayDragons(dragons); // Get input from the user. Console.Write("Enter text to search by or Q to quit:>"); keyword = Console.ReadLine(); // Check the input. if (keyword.ToUpper() == "Q") break; } Setup.Close(); } #region Helpers private static List<Dragon> DisplayDragons(List<Dragon> dragons) { Console.WriteLine(String.Format("{0,3} | {1,-17} | {2,3} | {3,4} | {4,3} | {5,10} | {6,8} | {7,5}", "Id", "Name", "Age", "Gold", "HP", "Breath", "Born", "Realm")); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"); int count = 0; foreach (Dragon dragon in dragons) { Console.WriteLine(String.Format("{0, 3} | {1}", ++count, dragon)); } return dragons; } #endregion } }
27.25
175
0.452818
[ "Unlicense" ]
primaryobjects/MongoDragons
MongoDragons/Program.cs
1,528
C#
using ReturnTrue.QueryBuilder.Elements; using ReturnTrue.QueryBuilder.Renderers; namespace ReturnTrue.QueryBuilder.Modifiers { public class NotModifier : IQueryElement { public string Render(IRenderer renderer) { return renderer.Render(this); } } }
22.923077
48
0.687919
[ "MIT" ]
aleripe/QueryBuilder
QueryBuilder/Modifiers/NotModifier.cs
300
C#
using UnityEngine; namespace Diablerie.Engine { public class IsoInput : MonoBehaviour { public static Vector2 mousePosition; public static Vector3 mouseTile; void Update() { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mousePosition = Iso.MapToIso(mousePos); mouseTile = Iso.Snap(mousePosition); } } }
23.333333
83
0.628571
[ "MIT" ]
Bia10/Diablerie
Assets/Scripts/Diablerie/Engine/IsoInput.cs
422
C#
namespace Common.Notifications { public class ValidationNotification : INotificationMessage { public ValidationNotification(string message, string property) { Message = message; Property = property; } public string Message { get; private set; } public string Property { get; private set; } } }
23.3125
70
0.619303
[ "MIT" ]
otaviojulianons/DynamicRestApi
src/Common/Notifications/ValidationNotification.cs
375
C#
using System; namespace FluentSpecification.Integration.Tests.Data { public class CreditCard : IEquatable<CreditCard> { public int CustomerId { get; set; } public string CardNumber { get; set; } public DateTime ValidityDate { get; set; } public virtual Customer Customer { get; set; } public bool Equals(CreditCard other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return CustomerId == other.CustomerId; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((CreditCard) obj); } public override int GetHashCode() { // ReSharper disable once NonReadonlyMemberInGetHashCode return CustomerId; } public static bool operator ==(CreditCard left, CreditCard right) { return Equals(left, right); } public static bool operator !=(CreditCard left, CreditCard right) { return !Equals(left, right); } } }
29.363636
73
0.583591
[ "Apache-2.0" ]
michalkowal/FluentSpecification
src/FluentSpecification.Integration.Tests/Data/CreditCard.cs
1,294
C#
using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace TestBlocklyHtml.Authorization { public class AuthorizationToken { private readonly IConfiguration configuration; public AuthorizationToken(IConfiguration configuration) { this.configuration = configuration; } public string GenerateFrom(string secretCode) { var tokenHandler = new JwtSecurityTokenHandler(); //var key = Encoding.ASCII.GetBytes(configuration["ApplicationSecret"]); var key = Encoding.ASCII.GetBytes("mySecretKeyThatShouldBeStoredInConfiguration"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[]{ new Claim(ClaimTypes.Sid, secretCode) }), Expires = DateTime.Today.AddYears(100), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature) }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } }
32.690476
94
0.638019
[ "MIT" ]
BigHam/NETCoreBlockly
src/NetCore2Blockly/TestBlocklyHtml/Authorization/AuthorizationToken.cs
1,375
C#
using System; using System.Collections.Generic; using Couchbase.Lite; using Xamarin.Forms; using CouchbaseConnect2014.Services; using CouchbaseConnect2014.Views; using TinyIoC; namespace CouchbaseConnect2014 { public class App { public async static void Initialize () { TinyIoCContainer.Current.Register<QrCodeScannerView> (); TinyIoCContainer.Current.Register<ITwitterService> (new TwitterService ()); TinyIoCContainer.Current.Register<ITimeService> (new TimeService ()); TinyIoCContainer.Current.Register<ICouchbaseUserService> (new CouchbaseUserService()); var couchbaseService = new CouchbaseService (); TinyIoCContainer.Current.Register<ICouchbaseService> (couchbaseService); TinyIoCContainer.Current.Register<IRepository>(new Repository (couchbaseService)); await couchbaseService.InitializeDatabase(); } public static Dictionary<string, TrackColorScheme> TrackColor = new Dictionary<string, TrackColorScheme> () { //;Development;Enterprise;Internals;Mobile;Operations;Customer {"Mobile",Colors.Track.Mobile}, {"Enterprise",Colors.Track.Enterprise}, {"Developer",Colors.Track.Developer}, {"Operations",Colors.Track.Operations}, {"Architecture",Colors.Track.Architecture}, {"Customer",Colors.Track.Customer}, // Non-track Tracks.... used for colors of cells {"Registration", Colors.Track.Registration}, {"MealBreak",Colors.Track.MealBreak}, {"NoTrack", Colors.Track.NoTrack}, }; public static Page GetMainPage () { return new RootView (); } public static TinyIoCContainer Container { get { return TinyIoCContainer.Current; } } } }
30.678571
110
0.718277
[ "MIT" ]
Vineymahendru/Conference-app-module
src/Shared.Front/App.cs
1,720
C#
using System.Collections.Generic; using System.Threading; using LanguageExt; namespace SJP.Schematic.Core.Comments; /// <summary> /// Defines an object which retrieves comments for database tables. /// </summary> /// <seealso cref="IRelationalDatabaseTable"/> public interface IRelationalDatabaseTableCommentProvider { /// <summary> /// Retrieves comments for a particular database table. /// </summary> /// <param name="tableName">The name of a database table.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An <see cref="OptionAsync{A}"/> instance which holds the value of the table's comments, if available.</returns> OptionAsync<IRelationalDatabaseTableComments> GetTableComments(Identifier tableName, CancellationToken cancellationToken = default); /// <summary> /// Retrieves all database table comments defined within a database. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of table comments.</returns> IAsyncEnumerable<IRelationalDatabaseTableComments> GetAllTableComments(CancellationToken cancellationToken = default); }
45.148148
137
0.728466
[ "MIT" ]
sjp/SJP.Schema
src/SJP.Schematic.Core/Comments/IRelationalDatabaseTableCommentProvider.cs
1,195
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine.Events; using MyNamespace.databridge; using MyNamespace.rayMapPathFinding.myQueue; // 用于Drama Script的回调函数 public delegate void WalkTaskCallback(); // 角色控制器 public class Chara : MonoBehaviour { private class _OutMousePositionBuilder : DefaultBridgeTaskBuilder { public _OutMousePositionBuilder(Component component) { _product = new BridgeTask(); _destnaionComponent = component; } public BridgeTask BuildProduct(Component originComponent,Vector2 parament) { DefineBridgeParamentType(BridgeParamentType.Chara_MousePosition_RayMapPathFinding); BuildOrigin(originComponent); BuildParament(parament); BuildDestnation(_destnaionComponent); return _product; } private Component _destnaionComponent; } private class _RegisterCharacters : DefaultBridgeTaskBuilder { } public TDataBridge dataBridge; public GameObject adjustableTrigger; //public Vector2 outmPos; // 行走参数 public float speed = 0.06f; public const float step = 0.48f; private float xRemain = 0,yRemain = 0; private bool firstFreeMove = false; private float freeTouchTick = 0,targetRotation = 0; private Vector2 srcPadPos,srcClickPos; private Transform Pad; // 朝向枚举 public enum walkDir{ Down,Left,Right,Up } // 行走任务 public class walkTask{ public float x,y; // 实际的任务坐标 public float xBuff,yBuff; // 步数坐标(Drama Script) private bool useStep = false; public bool isCalculated{ get{ return (xBuff == 0 && yBuff == 0); } } public void Caculate(Vector3 pos){ x = pos.x + (useStep ? Chara.step : 1.0f) * xBuff; y = pos.y + (useStep ? Chara.step : 1.0f) * yBuff; xBuff = 0; yBuff = 0; Debug.Log("Walktask: relative position cale: " + x + "," + y); } public static walkTask fromRaw(float x,float y){ return new walkTask{ x = x,y = y,xBuff = 0,yBuff = 0,useStep = false }; } public static walkTask fromStep(float x,float y){ return new walkTask{ x = 0,y = 0,xBuff = x,yBuff = y,useStep = true }; } public static walkTask fromRelative(float x,float y){ return new walkTask{ x = 0,y = 0,xBuff = x,yBuff = y,useStep = false }; } } // 当列表长度为0时表示行走完毕 public MyQueueWithIndex<walkTask> walkTasks = new MyQueueWithIndex<walkTask>(); private Sprite[] Animation; // 行走图图像集 public string Character; // 对应的人物 public bool Controller = false; // 是否为玩家 private SpriteRenderer image; // 图形显示容器 public walkDir dir; // 当前朝向 private bool walking; // 是否正在行走 private int walkBuff = 1; // 行走图系列帧序数 private float walkspan; // 行走图动画间隔控制缓冲 private float sx,sy,ex,ey; // 地图边界x,y - x,y public GameObject MoveArrow; // 点击移动反馈 private bool tMode = false; // 点击移动模式(TouchMode) private Vector2 lpos; private int lposCount; public WalkTaskCallback walkTaskCallback; // 行走人物回调 private _OutMousePositionBuilder bridgeTaskbuilderOMP; private void Start() { // 载入行走图图像集,并初始化相关设置 Animation = Resources.LoadAll<Sprite>("Players\\" + Character); image = this.GetComponent<SpriteRenderer>(); // dir = walkDir.Down; UploadWalk(); // 获取地图边界并处理 Vector3 size = new Vector3(0.25f,0.25f,0f); Vector3 pos = GameObject.Find("startDot").transform.localPosition; sx = pos.x + size.x; sy = pos.y - size.y; pos = GameObject.Find("endDot").transform.localPosition; ex = pos.x - size.x; ey = pos.y + size.y * 1.7f; // 如果是玩家则绑定至MapCamera if(Controller) { MapCamera.Player = this; MapCamera.PlayerCollider = this.transform.Find("Pathfinding").gameObject; Pad = GameObject.Find("MapCamera").transform.Find("MovePad").Find("ball"); srcClickPos = MapCamera.mcamera.GetComponent<Camera>().WorldToScreenPoint( GameObject.Find("MapCamera").transform.Find("MovePad").Find("tipPad").position ); srcPadPos = Pad.localPosition; } if(Controller) // only controller can havve a pathfinding movement bridgeTaskbuilderOMP = new _OutMousePositionBuilder(dataBridge.defaultRayMapPathFindingScript); // 如果是玩家并且传送数据不为空,则按照传送设置初始化 if(Controller && MapCamera.initTp != -1){ dir = MapCamera.initDir; UploadWalk(); // 取得传送位置坐标 this.transform.localPosition = GameObject.Find("tp" + MapCamera.initTp).transform.localPosition; } } // 更新行走图图形 public void UploadWalk(){ if(walking){ // 行走时的图像 walkspan += Time.deltaTime; if(walkspan > 0.1f){ walkBuff ++; if(walkBuff > 2) walkBuff = 0; walkspan = 0; } walking = false; }else{ // 未行走时 walkspan = 0; walkBuff = 1; } // 设定帧 image.sprite = Animation[(int)dir * 3 + walkBuff]; } // ⚠警告:x和y的取值只能为-1,0,1 float Move(int x,int y){ Vector3 pos = transform.localPosition; float buff = speed * Time.deltaTime * 60f * (Input.GetKey(KeyCode.X) ? 2 : 1); pos.x += buff * x ; pos.y += buff * y ; if(pos.x < sx) pos.x = sx; if(pos.x > ex) pos.x = ex; if(pos.y > sy) pos.y = sy; if(pos.y < ey) pos.y = ey; transform.localPosition = pos; walking = true; if(x != 0) dir = x < 0 ? walkDir.Left : walkDir.Right; if(y != 0) dir = y < 0 ? walkDir.Down : walkDir.Up; return y == 0 ? buff * x : buff * y; } private void _SpriteRenderer_AutoSortOrder() { } void FixPos(){ Vector3 mpos = transform.localPosition; mpos.x = Mathf.Round((mpos.x - 0.48f) / 0.96f) * 0.96f + 0.48f; mpos.y = Mathf.Round((mpos.y + 0.48f) / 0.96f) * 0.96f - 0.48f; transform.localPosition = mpos; } void FixedUpdate() { // 如果剧本正在进行则退出 if (MapCamera.SuspensionDrama && walkTasks.Count == 0 && Controller) { adjustableTrigger.GetComponent<Collider2D>().isTrigger = true; return; } // 是否正在执行行走任务? bool isWalkTask = (walkTasks.Count > 0); Vector3 pos = transform.localPosition; // 如果有行走任务 if(isWalkTask){ walkTask wt = walkTasks.referencePeek; // 如果坐标尚未初始化 if(!wt.isCalculated) wt.Caculate(pos); // 决定是否修正行走坐标(完成行走) bool isFix = false; if(wt.x < pos.x){ Move(-1,0); if(wt.x >= transform.localPosition.x) isFix = true; }else if(wt.x > pos.x){ Move(1,0); if(wt.x <= transform.localPosition.x) isFix = true; }else if(wt.y < pos.y){ Move(0,-1); if(wt.y >= transform.localPosition.y) isFix = true; }else if(wt.y > pos.y){ Move(0,1); if(wt.y <= transform.localPosition.y) isFix = true; } if(!Controller) UploadWalk(); // 修正坐标 if(isFix){ Debug.Log("Walktask: " + (walkTasks.Count - 1) + " remaining..."); FixPos(); //transform.localPosition = new Vector3(wt.x,wt.y,pos.z); walkTasks.Dequeue(); if(walkTasks.Count == 0){ if(tMode){ Debug.Log("Walktask: tasks for Pathfinding is done."); tMode = false; MoveArrow.SetActive(false); }else{ Debug.Log("Walktask: tasks for Drama Script is done."); walkTaskCallback(); } walking = false; UploadWalk(); } } } // 如果不是玩家 if(!Controller) return; bool isKeyboard = false; // 判定调查 Vector2 spyRay = new Vector2(pos.x,pos.y); if(dir == walkDir.Left){ spyRay.x -= 0.96f; }else if(dir == walkDir.Right){ spyRay.x += 0.96f; }else if(dir == walkDir.Up){ spyRay.y += 0.96f; }else{ spyRay.y -= 0.96f; } CheckObj checkObj = null; foreach(RaycastHit2D crash in Physics2D.RaycastAll(spyRay,new Vector2(0,0))){ if(crash.collider.gameObject.TryGetComponent<CheckObj>(out checkObj)){ if(MapCamera.HitCheck != checkObj.gameObject){ checkObj.CheckEncounter(); } break; } } if(checkObj == null && MapCamera.HitCheck != null){ MapCamera.HitCheck.GetComponent<CheckObj>().CheckGoodbye(); } // 如果屏幕被点击 if (Input.GetMouseButton(0)){ if(freeTouchTick < 0.5f){ if(freeTouchTick < 0.2f && (!isWalkTask || tMode)){ Vector3 mpos = MapCamera.mcamera.GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition); foreach(RaycastHit2D hit in Physics2D.RaycastAll(new Vector2(mpos.x,mpos.y),new Vector2(0,0))){ if(hit.collider.gameObject.name == "MovePad"){ Animator padAni = Pad.transform.parent.GetComponent<Animator>(); padAni.SetFloat("speed",1.0f); padAni.Play("MovePad",0,0f); Debug.Log("Freemove OK!:" + this.gameObject.name); freeTouchTick = 1f; } } if(freeTouchTick < 0.2f){ Debug.Log("Freemove Failed!:" + this.gameObject.name); freeTouchTick = 0.3f; } } } else { // 从屏幕坐标换算到世界坐标 Vector3 mpos = Input.mousePosition; // 测算 float xp = mpos.x - srcClickPos.x,yp = mpos.y - srcClickPos.y; float xpro = Mathf.Abs(xp) / 30,ypro = Mathf.Abs(yp) / 30; if(xpro > 1) xpro = 1; if(ypro > 1) ypro = 1; if(xRemain == 0 && yRemain == 0 && (xpro == 1 || ypro == 1)){ if(Mathf.Abs(xp) > Mathf.Abs(yp)){ xRemain = 1.02f * (xp > 0 ? 1 : -1); firstFreeMove = true; isKeyboard = true; targetRotation = (xp > 0 ? 270f : 90f); }else { yRemain = 1.02f * (yp > 0 ? 1 : -1); firstFreeMove = true; isKeyboard = true; targetRotation = (yp > 0 ? 0f : 180f); } } float ro = Pad.eulerAngles.z + (targetRotation - Pad.eulerAngles.z) / 5; Pad.eulerAngles = new Vector3(0,0,ro); } } if (Input.GetMouseButtonUp(0)) { if(!isWalkTask && freeTouchTick < 0.5f && xRemain == 0 && yRemain == 0){ Debug.Log("Occured pathfinding:" + this.gameObject.name); // 必要:开启tMode,将寻路WalkTask与DramaScript的WalkTask区别开来 tMode = true; walkTasks.Clear(); // 从屏幕坐标换算到世界坐标 Vector3 mpos = MapCamera.mcamera.GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition); mpos.z = 0; // 检查是否点击的是UI而不是地板 if (EventSystem.current.IsPointerOverGameObject()) return; // 格式化坐标 mpos.x = Mathf.Floor(mpos.x / 0.96f) * 0.96f + 0.48f - 0.06f; mpos.y = Mathf.Ceil(mpos.y / 0.96f) * 0.96f - 0.48f; // 设置点击反馈 MoveArrow.transform.localPosition = mpos; MoveArrow.SetActive(true); // 设置walkTask保险 lpos = new Vector2(0,0); lposCount = 3; //prepare for Event to TRayMapBuilder dataBridge.EnqueueTask(bridgeTaskbuilderOMP.BuildProduct(this, mpos)); freeTouchTick = 0; Pad.localPosition = srcPadPos; goto skipKeyboard; } Animator padAni = Pad.transform.parent.GetComponent<Animator>(); padAni.SetFloat("speed",-2.0f); padAni.Play("MovePad",0,1f); freeTouchTick = 0; Pad.localPosition = srcPadPos; } // 检测键盘输入 if((!isWalkTask || tMode) && xRemain == 0 && yRemain == 0){ if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)){ xRemain = -1.02f; firstFreeMove = true; isKeyboard = true; }else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)){ xRemain = 1.02f; firstFreeMove = true; isKeyboard = true; }else if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)){ yRemain = 1.02f; firstFreeMove = true; isKeyboard = true; }else if(Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)){ yRemain = -1.02f; firstFreeMove = true; isKeyboard = true; } } // 自由移动 if(xRemain != 0 || yRemain != 0){ int xDir = xRemain < 0 ? -1 : 1,yDir = yRemain < 0 ? -1 : 1; if(xRemain == 0) xDir = 0; if(yRemain == 0) yDir = 0; if(firstFreeMove){ Collider2D crash = Physics2D.Raycast(new Vector2(pos.x + xDir,pos.y + yDir),new Vector2(0,0)).collider; if(crash != null){ if(!crash.isTrigger){ if(xDir != 0) dir = xDir < 0 ? walkDir.Left : walkDir.Right; if(yDir != 0) dir = yDir < 0 ? walkDir.Down : walkDir.Up; walking = true; xRemain = 0;yRemain = 0; } } firstFreeMove = false; } if(xRemain != 0) { xRemain -= Move(xDir,0); if((xRemain < 0 ? -1 : 1) != xDir){ FixPos(); walking = true; if(freeTouchTick == 0) MoveArrow.SetActive(false); xRemain = 0; } } if(yRemain != 0) { yRemain -= Move(0,yDir); if((yRemain < 0 ? -1 : 1) != yDir){ FixPos(); walking = true; if(freeTouchTick == 0) MoveArrow.SetActive(false); yRemain = 0; } } } skipKeyboard: if (Controller && adjustableTrigger!=null) adjustableTrigger.GetComponent<Collider2D>().isTrigger = !isKeyboard; // 仅打断寻路task(tMode),不打断DramaScript的task if (lpos.x == pos.x && lpos.y == pos.y && isWalkTask && tMode) lposCount--; if(lposCount == 0 && isWalkTask && tMode){ Debug.Log("Walktask: tasks for Pathfinding is broke."); walking = false; UploadWalk(); walkTasks.Clear(); tMode = false; MoveArrow.SetActive(false); } lpos = pos; // 更新图片 UploadWalk(); } }
38.252381
119
0.503921
[ "MIT" ]
MorizeroDev/Morizero
code/Morizero/Assets/Map/Chara.cs
16,858
C#
using CodingLibrary.JSS.IO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JSS.IO { public class JDirectories { /// <summary> /// Takes the given directory, moves the files and subdirectories up one, and deletes the given directory. /// </summary> /// <param name="directory">The directory to move from and delete.</param> /// <exception cref="ArgumentException">Throws this when the directory is invalid.</exception> public static void MoveFolderUpAndReplace(string directory) { if (!Directory.Exists(directory)) { throw new ArgumentException("Supplied directory doesn't exist!"); } string[] folders = Directory.GetDirectories(directory, "*", SearchOption.TopDirectoryOnly); string[] files = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly); string[] combined = new string[folders.Length + files.Length]; foreach (string file in files) { //move up one directory string newDirectory = Directory.GetParent(Directory.GetParent(file).ToString()).ToString(); string newName = newDirectory + "\\" + Path.GetFileName(file); //delete the new file name if it already exists if (File.Exists(newName)) { File.Delete(newName); } Directory.Move(file, newName); } foreach (string folder in folders) { //move up one directory string newDirectory = Directory.GetParent(Directory.GetParent(folder).ToString()).ToString(); string newMoveURL = newDirectory + "\\" + JPath.GetLastFolderName(folder); if (Directory.Exists(newMoveURL)) { Directory.Delete(newMoveURL, true); } Directory.Move(folder, newMoveURL); } Directory.Delete(directory); } } }
35.048387
114
0.577543
[ "MIT" ]
HomerGaidarski/Gunter-Hans-Transaction-Reports
GH_DataImporter/GH_DataImporter/GH_DataImporter/IO/JDirectories.cs
2,175
C#