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
using System.Threading; using System.Threading.Tasks; using MercadoPagoCore.Error; using MercadoPagoCore.Http; using MercadoPagoCore.Resource; using MercadoPagoCore.Resource.Payment; using MercadoPagoCore.Serialization; namespace MercadoPagoCore.Client.Payment { /// <summary> /// Client that use the Payment Refunds APIs. /// </summary> public class PaymentRefundClient : MercadoPagoClient<PaymentRefund> { /// <summary> /// Initializes a new instance of the <see cref="PaymentRefundClient"/> class. /// </summary> /// <param name="httpClient">The http client that will be used in HTTP requests.</param> /// <param name="serializer"> /// The serializer that will be used to serialize the HTTP requests content /// and to deserialize the HTTP response content. /// </param> public PaymentRefundClient(IHttpClient httpClient, ISerializer serializer) : base(httpClient, serializer) { } /// <summary> /// Initializes a new instance of the <see cref="PaymentRefundClient"/> class. /// </summary> /// <param name="httpClient">The http client that will be used in HTTP requests.</param> public PaymentRefundClient(IHttpClient httpClient) : base(httpClient, null) { } /// <summary> /// Initializes a new instance of the <see cref="PaymentRefundClient"/> class. /// </summary> /// <param name="serializer"> /// The serializer that will be used to serialize the HTTP requests content /// and to deserialize the HTTP response content. /// </param> public PaymentRefundClient(ISerializer serializer) : base(null, serializer) { } /// <summary> /// Initializes a new instance of the <see cref="PaymentRefundClient"/> class. /// </summary> public PaymentRefundClient() : base(null, null) { } /// <summary> /// Creates async a refund for payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="amount">The amount to refund.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>A task whose the result is the refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public Task<PaymentRefund> RefundAsync( long paymentId, decimal? amount, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { var request = new PaymentRefundCreateRequest { Amount = amount, }; return SendAsync( $"/v1/payments/{paymentId}/refunds", HttpMethod.Post, request, requestOptions, cancellationToken); } /// <summary> /// Creates a refund for payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="amount">The amount to refund.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <returns>The refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public PaymentRefund Refund( long paymentId, decimal? amount, RequestOptions requestOptions = null) { var request = new PaymentRefundCreateRequest { Amount = amount, }; return Send( $"/v1/payments/{paymentId}/refunds", HttpMethod.Post, request, requestOptions); } /// <summary> /// Creates async a total refund for payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>A task whose the result is the refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public Task<PaymentRefund> RefundAsync( long paymentId, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return RefundAsync(paymentId, null, requestOptions, cancellationToken); } /// <summary> /// Creates a total refund for payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <returns>The refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public PaymentRefund Refund( long paymentId, RequestOptions requestOptions = null) { return Refund(paymentId, null, requestOptions); } /// <summary> /// Gets async a refund by id from the payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="id">The refund ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>A task whose the result is the refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public Task<PaymentRefund> GetAsync( long paymentId, long id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return SendAsync( $"/v1/payments/{paymentId}/refunds/{id}", HttpMethod.Get, null, requestOptions, cancellationToken); } /// <summary> /// Gets a refund by id from the payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="id">The refund ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <returns>A task whose the result is the refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public PaymentRefund Get( long paymentId, long id, RequestOptions requestOptions = null) { return Send( $"/v1/payments/{paymentId}/refunds/{id}", HttpMethod.Get, null, requestOptions); } /// <summary> /// Lists async the refunds of the payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>A task whose the result is the list of refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public Task<ResourcesList<PaymentRefund>> ListAsync( long paymentId, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return ListAsync( $"/v1/payments/{paymentId}/refunds", HttpMethod.Get, null, requestOptions, cancellationToken); } /// <summary> /// Lists the refunds of the payment. /// </summary> /// <param name="paymentId">The payment ID.</param> /// <param name="requestOptions"><see cref="RequestOptions"/></param> /// <returns>A task whose the result is the list of refund.</returns> /// <exception cref="MercadoPagoException">If a unexpected exception occurs.</exception> /// <exception cref="MercadoPagoApiException">If the API returns a error.</exception> public ResourcesList<PaymentRefund> List( long paymentId, RequestOptions requestOptions = null) { return List( $"/v1/payments/{paymentId}/refunds", HttpMethod.Get, null, requestOptions); } } }
41.610619
113
0.585389
[ "MIT" ]
cantte/MercadoPagoCore
MercadoPagoCore/Client/Payment/PaymentRefundClient.cs
9,404
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. #nullable enable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Execution; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Remote { internal partial class RemoteHostClientServiceFactory { public sealed class RemoteHostClientService : ForegroundThreadAffinitizedObject, IRemoteHostClientService { /// <summary> /// this hold onto last remoteHostClient to make debugging easier /// </summary> private static Task<RemoteHostClient?>? s_lastRemoteClientTask; private readonly IAsynchronousOperationListener _listener; private readonly Workspace _workspace; private readonly object _gate; private SolutionChecksumUpdater? _checksumUpdater; private CancellationTokenSource? _shutdownCancellationTokenSource; private Task<RemoteHostClient?>? _remoteClientTask; public RemoteHostClientService( IThreadingContext threadingContext, IAsynchronousOperationListener listener, Workspace workspace) : base(threadingContext) { _gate = new object(); _listener = listener; _workspace = workspace; } public Workspace Workspace => _workspace; public IAsynchronousOperationListener Listener => _listener; public void Enable() { lock (_gate) { if (_remoteClientTask != null) { // already enabled return; } // We enable the remote host if either RemoteHostTest or RemoteHost are on. if (!_workspace.Options.GetOption(RemoteHostOptions.RemoteHostTest) && !_workspace.Options.GetOption(RemoteHostOptions.RemoteHost)) { // not turned on return; } // log that remote host is enabled Logger.Log(FunctionId.RemoteHostClientService_Enabled, KeyValueLogMessage.NoProperty); var remoteHostClientFactory = _workspace.Services.GetService<IRemoteHostClientFactory>(); if (remoteHostClientFactory == null) { // dev14 doesn't have remote host client factory return; } // set bitness SetRemoteHostBitness(); // make sure we run it on background thread _shutdownCancellationTokenSource = new CancellationTokenSource(); var token = _shutdownCancellationTokenSource.Token; // create solution checksum updater _checksumUpdater = new SolutionChecksumUpdater(this, token); _remoteClientTask = Task.Run(() => EnableAsync(token), token); } } public void Disable() { RemoteHostClient? client = null; lock (_gate) { var remoteClientTask = _remoteClientTask; if (remoteClientTask == null) { // already disabled return; } _remoteClientTask = null; Contract.ThrowIfNull(_shutdownCancellationTokenSource); Contract.ThrowIfNull(_checksumUpdater); _shutdownCancellationTokenSource.Cancel(); _checksumUpdater.Shutdown(); _checksumUpdater = null; try { remoteClientTask.Wait(_shutdownCancellationTokenSource.Token); // result can be null if service hub failed to launch client = remoteClientTask.Result; } catch (OperationCanceledException) { // remoteClientTask wasn't finished running yet. } } if (client != null) { client.StatusChanged -= OnStatusChanged; // shut it down outside of lock so that // we don't call into different component while // holding onto a lock client.Dispose(); } } bool IRemoteHostClientService.IsEnabled() { // We enable the remote host if either RemoteHostTest or RemoteHost are on. if (!_workspace.Options.GetOption(RemoteHostOptions.RemoteHostTest) && !_workspace.Options.GetOption(RemoteHostOptions.RemoteHost)) { // not turned on return false; } var remoteHostClientFactory = _workspace.Services.GetService<IRemoteHostClientFactory>(); if (remoteHostClientFactory is null) { // not available return false; } return true; } public Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Task<RemoteHostClient?>? remoteClientTask; lock (_gate) { remoteClientTask = _remoteClientTask; } if (remoteClientTask == null) { // service is in shutdown mode or not enabled return SpecializedTasks.Null<RemoteHostClient>(); } return remoteClientTask; } private void SetRemoteHostBitness() { bool x64 = RemoteHostOptions.IsServiceHubProcess64Bit(_workspace); // log OOP bitness Logger.Log(FunctionId.RemoteHost_Bitness, KeyValueLogMessage.Create(LogType.Trace, m => m["64bit"] = x64)); // set service bitness WellKnownRemoteHostServices.Set64bit(x64); WellKnownServiceHubServices.Set64bit(x64); } private async Task<RemoteHostClient?> EnableAsync(CancellationToken cancellationToken) { // if we reached here, IRemoteHostClientFactory must exist. // this will make VS.Next dll to be loaded var client = await _workspace.Services.GetRequiredService<IRemoteHostClientFactory>().CreateAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client != null) { client.StatusChanged += OnStatusChanged; return client; } return null; } private void OnStatusChanged(object sender, bool started) { if (started) { return; } Contract.ThrowIfNull(_shutdownCancellationTokenSource); if (_shutdownCancellationTokenSource.IsCancellationRequested) { lock (_gate) { // RemoteHost has been disabled _remoteClientTask = null; } } else { lock (_gate) { // save last remoteHostClient s_lastRemoteClientTask = _remoteClientTask; // save NoOpRemoteHostClient to remoteClient so that all RemoteHost call becomes // No Op. this basically have same effect as disabling all RemoteHost features _remoteClientTask = Task.FromResult<RemoteHostClient?>(new RemoteHostClient.NoOpClient(_workspace)); } // s_lastRemoteClientTask info should be saved in the dump // report NFW when connection is closed unless it is proper shutdown FatalError.ReportWithoutCrash(new InvalidOperationException("Connection to remote host closed")); RemoteHostCrashInfoBar.ShowInfoBar(_workspace); } } public async Task RequestNewRemoteHostAsync(CancellationToken cancellationToken) { var existingClient = await TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); if (existingClient == null) { return; } Contract.ThrowIfNull(_shutdownCancellationTokenSource); // log that remote host is restarted Logger.Log(FunctionId.RemoteHostClientService_Restarted, KeyValueLogMessage.NoProperty); // we are going to kill the existing remote host, connection change is expected existingClient.StatusChanged -= OnStatusChanged; lock (_gate) { // create new remote host client var token = _shutdownCancellationTokenSource.Token; _remoteClientTask = Task.Run(() => EnableAsync(token), token); } // shutdown existingClient.Dispose(); } } } }
37.573477
167
0.540876
[ "MIT" ]
Santi-lab/roslyn
src/VisualStudio/Core/Def/Implementation/Remote/RemoteHostClientServiceFactory.RemoteHostClientService.cs
10,485
C#
namespace IRunes.ViewModels.Home { public class IndexViewModel { public string Username { get; set; } } }
15.875
44
0.629921
[ "MIT" ]
TihomirIvanovIvanov/SoftUni
C#WebDevelopment/C#-Web-Basics/SISArchitecture2020/src/Apps/IRunes/ViewModels/Home/IndexViewModel.cs
129
C#
// MIT License // Copyright (c) 2020 vasvl123 // https://github.com/vasvl123/useyourmind using System; namespace onesharp.lib { class Функции : Onesharp { public Функции() : base("Функции") { } public object УзелСвойство(Структура Узел, string Свойство) { object УзелСвойство = null; if (!(Узел == Неопределено)) { Узел.Свойство(Свойство, out УзелСвойство); } return УзелСвойство; } // УзелСвойство(Узел) public object НоваяВкладка(pagedata Данные, Структура Параметры) { Параметры.Вставить("cmd", "newtab"); Данные.Процесс.НоваяЗадача(Параметры, "Служебный"); return Неопределено; } // НоваяВкладка() public object НоваяБаза(pagedata Данные, Структура Параметры) { var БазаДанных = Параметры.с.БазаДанных; var Запрос = Структура.Новый("Данные, БазаДанных, cmd", Данные, БазаДанных, "НоваяБаза"); Данные.Процесс.НоваяЗадача(Запрос, "Служебный"); return Неопределено; } } }
26.395349
101
0.585022
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
vasvl123/OneScriptDB
src/showdata/lib/Функции.cs
1,573
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/xaudio2fx.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.InteropServices; namespace TerraFX.Interop.DirectX; [StructLayout(LayoutKind.Sequential, Pack = 1)] public unsafe partial struct XAUDIO2FX_VOLUMEMETER_LEVELS { public float* pPeakLevels; public float* pRMSLevels; [NativeTypeName("UINT32")] public uint ChannelCount; }
29.85
145
0.770519
[ "MIT" ]
JeremyKuhne/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/xaudio2fx/XAUDIO2FX_VOLUMEMETER_LEVELS.cs
599
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. namespace Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.Tests.SqlCommandExtensionsScenarios.given_failing_execute_xml_reader_command { using System; using System.Data; using System.Data.SqlClient; using Common.TestSupport.ContextBase; using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.TestSupport; using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling; using VisualStudio.TestTools.UnitTesting; public abstract class Context : ArrangeActAssert { protected TestRetryStrategy connectionStrategy; protected TestRetryStrategy commandStrategy; protected SqlCommand command; protected RetryPolicy connectionPolicy; protected RetryPolicy commandPolicy; protected override void Arrange() { this.command = new SqlCommand(TestSqlSupport.InvalidSqlText); this.connectionStrategy = new TestRetryStrategy(); this.commandStrategy = new TestRetryStrategy(); this.connectionPolicy = new RetryPolicy<AlwaysTransientErrorDetectionStrategy>(this.connectionStrategy); this.commandPolicy = new RetryPolicy<AlwaysTransientErrorDetectionStrategy>(this.commandStrategy); } } [TestClass] public class when_executing_command_with_closed_connection : Context { protected override void Act() { try { this.command.Connection = new SqlConnection(TestSqlSupport.SqlDatabaseConnectionString); this.command.ExecuteXmlReaderWithRetry(this.commandPolicy, this.connectionPolicy); Assert.Fail(); } catch (SqlException) { } } [TestMethod] public void then_connection_is_closed() { Assert.IsNotNull(this.command.Connection); Assert.IsTrue(this.command.Connection.State == ConnectionState.Closed); } [TestMethod] public void then_retried() { Assert.AreEqual(0, this.connectionStrategy.ShouldRetryCount); Assert.AreEqual(1, this.commandStrategy.ShouldRetryCount); } } [TestClass] public class when_executing_command_with_opened_connection : Context { protected override void Act() { try { this.command.Connection = new SqlConnection(TestSqlSupport.SqlDatabaseConnectionString); this.command.Connection.Open(); this.command.ExecuteXmlReaderWithRetry(this.commandPolicy, this.connectionPolicy); Assert.Fail(); } catch (SqlException) { } } [TestMethod] public void then_connection_is_opened() { Assert.IsNotNull(this.command.Connection); Assert.IsTrue(this.command.Connection.State == ConnectionState.Open); } [TestMethod] public void then_retried() { Assert.AreEqual(0, this.connectionStrategy.ShouldRetryCount); Assert.AreEqual(1, this.commandStrategy.ShouldRetryCount); } } }
33.42
147
0.652902
[ "Apache-2.0" ]
Microsoft/transient-fault-handling-application-block
source/Tests/TransientFaultHandling.Tests/SqlCommandExtensionsScenarios/given_failing_execute_xml_reader_command.cs
3,344
C#
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace StackOverflowData.Models.Mapping { public class CommentMap : EntityTypeConfiguration<Comment> { public CommentMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); this.Property(t => t.Text) .IsRequired() .HasMaxLength(700); // Table & Column Mappings this.ToTable("Comments"); this.Property(t => t.Id).HasColumnName("Id"); this.Property(t => t.CreationDate).HasColumnName("CreationDate"); this.Property(t => t.PostId).HasColumnName("PostId"); this.Property(t => t.Score).HasColumnName("Score"); this.Property(t => t.Text).HasColumnName("Text"); this.Property(t => t.UserId).HasColumnName("UserId"); } } }
32.75
77
0.579198
[ "MIT" ]
Jorriss/Demo.EFDataProfessionals
StackOverflow/StackOverflowObjects/Models/Mapping/CommentMap.cs
1,048
C#
namespace Microsoft.Research.DataOnboarding.DomainModel { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; public partial class FileAttribute { public FileAttribute() { this.File = new File(); } public int FileAttributeId { get; set; } public int FileId { get; set; } public string Key { get; set; } public string Value { get; set; } [ForeignKey("FileId")] public virtual File File { get; set; } } }
23.434783
56
0.630798
[ "MIT" ]
CDLUC3/dataup2
Models/DomainModel/FileAttribute.cs
539
C#
using System; using UnityEditor.Graphing; using UnityEngine; using Object = UnityEngine.Object; using UnityEditor.UIElements; using UnityEngine.UIElements; namespace UnityEditor.ShaderGraph.Drawing.Slots { class Texture3DSlotControlView : VisualElement { Texture3DInputMaterialSlot m_Slot; public Texture3DSlotControlView(Texture3DInputMaterialSlot slot) { m_Slot = slot; styleSheets.Add(Resources.Load<StyleSheet>("Styles/Controls/Texture3DSlotControlView")); var objectField = new ObjectField { objectType = typeof(Texture3D), value = m_Slot.texture }; objectField.RegisterValueChangedCallback(OnValueChanged); Add(objectField); } void OnValueChanged(ChangeEvent<Object> evt) { var texture = evt.newValue as Texture3D; if (texture != m_Slot.texture) { m_Slot.owner.owner.owner.RegisterCompleteObjectUndo("Change Texture"); m_Slot.texture = texture; m_Slot.owner.Dirty(ModificationScope.Node); } } } }
33.257143
106
0.635739
[ "MIT" ]
AlePPisa/GameJamPractice1
Cellular/Library/PackageCache/com.unity.shadergraph@8.2.0/Editor/Drawing/Views/Slots/Texture3DSlotControlView.cs
1,164
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace CsWpfCtrl { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { } }
17.055556
42
0.693811
[ "MIT" ]
liuwake/CSharpPractice
CSharp/CsWpf/CsWpfCtrl/App.xaml.cs
319
C#
using System; using DynamicData.Tests.Domain; using FluentAssertions; using Microsoft.Reactive.Testing; using Xunit; namespace DynamicData.Tests.Cache { public class BatchFixture : IDisposable { private readonly ChangeSetAggregator<Person, string> _results; private readonly TestScheduler _scheduler; private readonly ISourceCache<Person, string> _source; public BatchFixture() { _scheduler = new TestScheduler(); _source = new SourceCache<Person, string>(p => p.Key); _results = _source.Connect().Batch(TimeSpan.FromMinutes(1), _scheduler).AsAggregator(); } public void Dispose() { _results.Dispose(); _source.Dispose(); } [Fact] public void NoResultsWillBeReceivedBeforeClosingBuffer() { _source.AddOrUpdate(new Person("A", 1)); _results.Messages.Count.Should().Be(0, "There should be no messages"); } [Fact] public void ResultsWillBeReceivedAfterClosingBuffer() { _source.AddOrUpdate(new Person("A", 1)); //go forward an arbitary amount of time _scheduler.AdvanceBy(TimeSpan.FromSeconds(61).Ticks); _results.Messages.Count.Should().Be(1, "Should be 1 update"); } } }
26.686275
99
0.615724
[ "MIT" ]
1R053/DynamicData
src/DynamicData.Tests/Cache/BatchFixture.cs
1,361
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class ArrayListTests { [Fact] public static void Ctor_Empty() { var arrList = new ArrayList(); Assert.Equal(0, arrList.Count); Assert.Equal(0, arrList.Capacity); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Theory] [InlineData(16)] [InlineData(0)] public static void Ctor_Int(int capacity) { var arrList = new ArrayList(capacity); Assert.Equal(capacity, arrList.Capacity); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new ArrayList(-1)); // Capacity < 0 } [Fact] public static void Ctor_ICollection() { ArrayList sourceList = Helpers.CreateIntArrayList(100); var arrList = new ArrayList(sourceList); Assert.Equal(sourceList.Count, arrList.Count); for (int i = 0; i < arrList.Count; i++) { Assert.Equal(sourceList[i], arrList[i]); } Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Ctor_ICollection_Empty() { ICollection arrListCollection = new ArrayList(); ArrayList arrList = new ArrayList(arrListCollection); Assert.Equal(0, arrList.Count); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("c", () => new ArrayList(null)); // Collection is null } [Fact] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ArrayList()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ArrayList() { "a", 1, "b", 2 }); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ArrayList), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public static void Adapter_ArrayList() { ArrayList arrList = ArrayList.Adapter(new ArrayList()); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Adapter_FixedSizeArrayList() { ArrayList arrList = ArrayList.Adapter(ArrayList.FixedSize(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Adapter_ReadOnlyArrayList() { ArrayList arrList = ArrayList.Adapter(ArrayList.ReadOnly(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.True(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void Adapter_SynchronizedArrayList() { ArrayList arrList = ArrayList.Adapter(ArrayList.Synchronized(new ArrayList())); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void Adapter_PopulateChangesToList() { const string FromBefore = " from before"; // Make sure changes through listAdapter show up in list ArrayList arrList = Helpers.CreateStringArrayList(count: 10, optionalString: FromBefore); ArrayList adapter = ArrayList.Adapter(arrList); adapter.Reverse(0, adapter.Count); int j = 9; for (int i = 0; i < adapter.Count; i++) { Assert.Equal(j.ToString() + FromBefore, adapter[i]); j--; } } [Fact] public static void Adapter_ClearList() { // Make sure changes through list show up in listAdapter ArrayList arrList = Helpers.CreateIntArrayList(100); ArrayList adapter = ArrayList.Adapter(arrList); arrList.Clear(); Assert.Equal(0, adapter.Count); } [Fact] public static void Adapter_Enumerators() { // Test to see if enumerators are correctly enumerate through elements ArrayList arrList = Helpers.CreateIntArrayList(10); IEnumerator enumeratorBasic = arrList.GetEnumerator(); ArrayList adapter = ArrayList.Adapter(arrList); IEnumerator enumeratorWrapped = arrList.GetEnumerator(); int j = 0; while (enumeratorBasic.MoveNext()) { Assert.Equal(j, enumeratorBasic.Current); j++; } j = 0; while (enumeratorWrapped.MoveNext()) { Assert.Equal(j, enumeratorWrapped.Current); j++; } } [Fact] public static void Adapter_EnumeratorsModifiedList() { // Test to see if enumerators are correctly getting invalidated with list modified through list ArrayList arrList = Helpers.CreateIntArrayList(10); IEnumerator enumeratorBasic = arrList.GetEnumerator(); ArrayList adapter = ArrayList.Adapter(arrList); IEnumerator numeratorWrapped = arrList.GetEnumerator(); enumeratorBasic.MoveNext(); numeratorWrapped.MoveNext(); // Now modify list through arrList arrList.Add(100); // Make sure accessing enumeratorBasic and enuemratorWrapped throws Assert.Throws<InvalidOperationException>(() => enumeratorBasic.MoveNext()); Assert.Throws<InvalidOperationException>(() => numeratorWrapped.MoveNext()); } [Fact] public static void Adapter_EnumeratorsModifiedAdapter() { // Test to see if enumerators are correctly getting invalidated with list modified through listAdapter ArrayList arrList = Helpers.CreateStringArrayList(10); IEnumerator enumeratorBasic = arrList.GetEnumerator(); ArrayList adapter = ArrayList.Adapter(arrList); IEnumerator enumeratorWrapped = arrList.GetEnumerator(); enumeratorBasic.MoveNext(); enumeratorWrapped.MoveNext(); // Now modify list through adapter adapter.Add("Hey this is new element"); // Make sure accessing enumeratorBasic and enuemratorWrapped throws Assert.Throws<InvalidOperationException>(() => enumeratorBasic.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumeratorWrapped.MoveNext()); } [Fact] public static void Adapter_InsertRange() { // Test to see if listAdaptor modified using InsertRange works // Populate the list ArrayList arrList = Helpers.CreateIntArrayList(10); ArrayList adapter = ArrayList.Adapter(arrList); // Now add a few more elements using InsertRange ArrayList arrListSecond = Helpers.CreateIntArrayList(10); adapter.InsertRange(adapter.Count, arrListSecond); Assert.Equal(20, adapter.Count); } [Fact] public static void Adapter_Capacity_Set() { ArrayList arrList = Helpers.CreateIntArrayList(10); ArrayList adapter = ArrayList.Adapter(arrList); adapter.Capacity = 10; Assert.Equal(10, adapter.Capacity); } [Fact] public static void Adapter_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.Adapter(null)); // List is null } [Fact] public static void AddRange_Basic() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); ArrayList arrList2 = Helpers.CreateIntArrayList(20, 10); VerifyAddRange(arrList1, arrList2); } [Fact] public static void AddRange_DifferentCollection() { ArrayList arrList = Helpers.CreateIntArrayList(10); Queue queue = new Queue(); for (int i = 10; i < 20; i++) { queue.Enqueue(i); } VerifyAddRange(arrList, queue); } [Fact] public static void AddRange_Self() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.AddRange(arrList2); for (int i = 0; i < arrList2.Count / 2; i++) { Assert.Equal(i, arrList2[i]); } for (int i = arrList2.Count / 2; i < arrList2.Count; i++) { Assert.Equal(i - arrList2.Count / 2, arrList2[i]); } }); } private static void VerifyAddRange(ArrayList arrList1, ICollection c) { Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } int expectedCount = arrList2.Count + c.Count; arrList2.AddRange(c); Assert.Equal(expectedCount, arrList2.Count); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(i, arrList2[i]); } // Assumes that the array list and collection contain integer types // and the first item in the collection is the count of the array list for (int i = arrList2.Count; i < c.Count; i++) { Assert.Equal(i, arrList2[i]); } }); } [Fact] public static void AddRange_DifferentObjectTypes() { // Add an ICollection with different type objects ArrayList arrList1 = Helpers.CreateIntArrayList(10); // Array list contains only integers currently var queue = new Queue(); // Queue contains strings for (int i = 10; i < 20; i++) queue.Enqueue("String_" + i); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.AddRange(queue); for (int i = 0; i < 10; i++) { Assert.Equal(i, arrList2[i]); } for (int i = 10; i < 20; i++) { Assert.Equal("String_" + i, arrList2[i]); } }); } [Fact] public static void AddRange_EmptyCollection() { var emptyCollection = new Queue(); ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.AddRange(emptyCollection); Assert.Equal(100, arrList2.Count); }); } [Fact] public static void AddRange_NullCollection_ThrowsArgumentNullException() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } AssertExtensions.Throws<ArgumentNullException>("c", () => arrList2.AddRange(null)); // Collection is null }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Add_SmallCapacity(int count) { ArrayList arrList1 = new ArrayList(1); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } for (int i = 0; i < count; i++) { arrList2.Add(i); Assert.Equal(i, arrList2[i]); Assert.Equal(i + 1, arrList2.Count); Assert.True(arrList2.Capacity >= arrList2.Count); } Assert.Equal(count, arrList2.Count); for (int i = 0; i < count; i++) { arrList2.RemoveAt(0); } Assert.Equal(0, arrList2.Count); }); } [Fact] public static void BinarySearch_Basic() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { int ndx = arrList2.BinarySearch(value); Assert.Equal(arrList2[ndx], value); } }); } [Fact] public static void BinarySearch_Basic_NotFoundReturnsNextElementIndex() { // The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number, // which is the bitwise complement of the index of the next element. ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(100, ~arrList2.BinarySearch(150)); // Searching for null items should return -1. Assert.Equal(-1, arrList2.BinarySearch(null)); }); } [Fact] public static void BinarySearch_Basic_NullObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(100); arrList1.Add(null); arrList1.Sort(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(0, arrList2.BinarySearch(null)); }); } [Fact] public static void BinarySearch_Basic_DuplicateResults() { // If we have duplicate results, return the first. var arrList1 = new ArrayList(); for (int i = 0; i < 100; i++) arrList1.Add(5); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { // Remember, this is BinarySearch. Assert.Equal(49, arrList2.BinarySearch(5)); }); } [Fact] public static void BinarySearch_IComparer() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList1) { int ndx = arrList2.BinarySearch(value, new BinarySearchComparer()); Assert.Equal(arrList2[ndx], value); } }); } [Fact] public static void BinarySearch_IComparer_NotFoundReturnsNextElementIndex() { ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(100, ~arrList2.BinarySearch(150, new BinarySearchComparer())); // Searching for null items should return -1. Assert.Equal(-1, arrList2.BinarySearch(null, new BinarySearchComparer())); }); } [Fact] public static void BinarySearch_IComparer_NullObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(100); arrList1.Add(null); arrList1.Sort(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(0, arrList2.BinarySearch(null)); }); } [Fact] public static void BinarySearch_IComparer_DuplicateResults() { // If we have duplicate results, return the first. var arrList1 = new ArrayList(); for (int i = 0; i < 100; i++) arrList1.Add(5); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { // Remember, this is BinarySearch. Assert.Equal(49, arrList2.BinarySearch(5, new BinarySearchComparer())); }); } [Fact] public static void BinarySearch_Int_Int_IComparer() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { int ndx = arrList2.BinarySearch(0, arrList2.Count, value, new BinarySearchComparer()); Assert.Equal(arrList2[ndx], value); } }); } [Fact] public static void BinarySearch_Int_Int_IComparer_ObjectOutsideIndex() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { // Index > list.IndexOf(object) int ndx = arrList2.BinarySearch(1, arrList2.Count - 1, 0, new BinarySearchComparer()); Assert.Equal(-2, ndx); // Index + count < list.IndexOf(object) ndx = arrList2.BinarySearch(0, arrList2.Count - 2, 9, new BinarySearchComparer()); Assert.Equal(-9, ndx); }); } [Fact] public static void BinarySearch_Int_Int_IComparer_NullComparer() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { // Locating item in list using a null comparer uses default comparer. int ndx1 = arrList2.BinarySearch(0, arrList2.Count, 5, null); int ndx2 = arrList2.BinarySearch(5, null); int ndx3 = arrList2.BinarySearch(5); Assert.Equal(ndx1, ndx2); Assert.Equal(ndx1, ndx3); Assert.Equal(5, ndx1); }); } [Fact] public static void BinarySearch_Int_Int_IComparer_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { IComparer comparer = new BinarySearchComparer(); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.BinarySearch(-1, 1000, arrList2.Count, comparer)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.BinarySearch(-1, 1000, 1, comparer)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.BinarySearch(-1, arrList2.Count, 1, comparer)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.BinarySearch(0, -1, 1, comparer)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.BinarySearch(1, arrList2.Count, 1, comparer)); // Index + Count >= list.Count AssertExtensions.Throws<ArgumentException>(null, () => arrList2.BinarySearch(3, arrList2.Count - 2, 1, comparer)); // Index + Count >= list.Count }); } [Fact] public static void Capacity_Get() { var arrList = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList, arrList2 => { Assert.True(arrList2.Capacity >= arrList2.Count); }); } [Fact] public static void Capacity_Set() { var arrList = Helpers.CreateIntArrayList(10); int nCapacity = 2 * arrList.Capacity; arrList.Capacity = nCapacity; Assert.Equal(nCapacity, arrList.Capacity); // Synchronized arrList = ArrayList.Synchronized(new ArrayList(Helpers.CreateIntArray(10))); arrList.Capacity = 1000; Assert.Equal(1000, arrList.Capacity); // Range ignores setter arrList = new ArrayList(Helpers.CreateIntArray(10)).GetRange(0, arrList.Count); arrList.Capacity = 1000; Assert.NotEqual(1000, arrList.Capacity); } [Fact] public static void Capacity_Set_Zero() { var arrList = new ArrayList(1); arrList.Capacity = 0; Assert.Equal(4, arrList.Capacity); for (int i = 0; i < 32; i++) arrList.Add(i); for (int i = 0; i < 32; i++) Assert.Equal(i, arrList[i]); } [Fact] public static void Capacity_Set_One() { var arrList = new ArrayList(4); arrList.Capacity = 1; Assert.Equal(1, arrList.Capacity); for (int i = 0; i < 32; i++) arrList.Add(i); for (int i = 0; i < 32; i++) Assert.Equal(i, arrList[i]); } [Fact] public static void Capacity_Set_InvalidValue_ThrowsArgumentOutOfRangeException() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => arrList2.Capacity = -1); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => arrList2.Capacity = arrList1.Count - 1); // Capacity < list.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Clone(int count) { // Clone should exactly replicate a collection to another object reference // afterwards these 2 should not hold the same object references ArrayList arrList1 = Helpers.CreateIntArrayList(count); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { ArrayList clone = (ArrayList)arrList2.Clone(); Assert.Equal(arrList2.Count, clone.Count); Assert.Equal(arrList2.IsReadOnly, clone.IsReadOnly); Assert.Equal(arrList2.IsSynchronized, clone.IsSynchronized); Assert.Equal(arrList2.IsFixedSize, clone.IsFixedSize); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(arrList2[i], clone[i]); } }); } [Fact] public static void Clone_IsShallowCopy() { var arrList = new ArrayList(); for (int i = 0; i < 10; i++) { arrList.Add(new Foo()); } ArrayList clone = (ArrayList)arrList.Clone(); string stringValue = "Hello World"; for (int i = 0; i < 10; i++) { Assert.Equal(stringValue, ((Foo)clone[i]).StringValue); } // Now we remove an object from the original list, but this should still be present in the clone arrList.RemoveAt(9); Assert.Equal(stringValue, ((Foo)clone[9]).StringValue); stringValue = "Good Bye"; ((Foo)arrList[0]).StringValue = stringValue; Assert.Equal(stringValue, ((Foo)arrList[0]).StringValue); Assert.Equal(stringValue, ((Foo)clone[0]).StringValue); // If we change the object, of course, the previous should not happen clone[0] = new Foo(); stringValue = "Good Bye"; Assert.Equal(stringValue, ((Foo)arrList[0]).StringValue); stringValue = "Hello World"; Assert.Equal(stringValue, ((Foo)clone[0]).StringValue); } [Fact] public static void CopyTo_Int() { int index = 1; ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new int[arrList2.Count + index]; arrCopy.SetValue(400, 0); arrList2.CopyTo(arrCopy, index); Assert.Equal(arrList2.Count + index, arrCopy.Length); for (int i = 0; i < arrCopy.Length; i++) { if (i == 0) { Assert.Equal(400, arrCopy.GetValue(i)); } else { Assert.Equal(arrList2[i - 1], arrCopy.GetValue(i)); } } }); } [Fact] public static void CopyTo_Int_EqualToLength() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new string[2]; arrList2.CopyTo(arrCopy, arrCopy.Length); // Should not throw }); } [Fact] public static void CopyTo_Int_EmptyArrayListToFilledArray() { var arrList1 = new ArrayList(); var arrCopy = new string[10]; for (int i = 0; i < arrCopy.Length; i++) { arrCopy[i] = "a"; } Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { arrList2.CopyTo(arrCopy, 3); // Make sure sentinels stay the same for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal("a", arrCopy[i]); } }); } [Fact] public static void CopyTo_Int_EmptyArray() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new string[0]; arrList2.CopyTo(arrCopy, 0); Assert.Equal(0, arrCopy.Length); }); } [Fact] public static void CopyTo_Int_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new int[arrList2.Count]; Assert.Throws<ArgumentNullException>(() => arrList2.CopyTo(null)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => arrList2.CopyTo(new object[10, 10])); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>(() => arrList2.CopyTo(arrCopy, -1)); // Index < 0 bool hasParamName = arrList2.GetType().Name != "Range"; AssertExtensions.Throws<ArgumentException>(hasParamName ? "destinationArray" : null, hasParamName ? "" : null, () => arrList2.CopyTo(new object[11], 2)); // Invalid index and length }); } [Fact] public static void CopyTo_Int_Int() { int index = 3; int count = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new int[100]; arrList2.CopyTo(index, arrCopy, index, count); Assert.Equal(100, arrCopy.Length); for (int i = index; i < index + count; i++) { Assert.Equal(arrList2[i], arrCopy[i]); } }); } [Fact] public static void CopyTo_Int_Int_EmptyArrayListToFilledArray() { var arrList1 = new ArrayList(); var arrCopy = new string[10]; for (int i = 0; i < arrCopy.Length; i++) { arrCopy[i] = "a"; } Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { arrList2.CopyTo(0, arrCopy, 3, 0); // Make sure sentinels stay the same for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal("a", arrCopy[i]); } }); } [Fact] public static void CopyTo_Int_Int_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { var arrCopy = new string[10]; Assert.ThrowsAny<ArgumentException>(() => arrList2.CopyTo(0, arrCopy, -1, 1000)); // Array index < 0 (should throw ArgumentOutOfRangeException) Assert.Throws<ArgumentOutOfRangeException>(() => arrList2.CopyTo(-1, arrCopy, 0, 1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>(() => arrList2.CopyTo(0, arrCopy, 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => { arrCopy = new string[100]; arrList2.CopyTo(arrList2.Count - 1, arrCopy, 0, 24); }); Assert.Throws<ArgumentNullException>(() => arrList2.CopyTo(0, null, 3, 3)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => arrList2.CopyTo(0, new object[arrList2.Count, arrList2.Count], 0, arrList2.Count)); // Array is multidimensional // Array index and count is out of bounds AssertExtensions.Throws<ArgumentException>(null, () => { arrCopy = new string[1]; arrList2.CopyTo(0, arrCopy, 3, 15); }); Assert.ThrowsAny<ArgumentException>(() => arrList2.CopyTo(0, new object[arrList2.Count, arrList2.Count], 0, -1)); // Should throw ArgumentOutOfRangeException }); } [Fact] public static void FixedSize_ArrayList() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); ArrayList arrList2 = ArrayList.FixedSize(arrList1); Assert.True(arrList2.IsFixedSize); Assert.False(arrList2.IsReadOnly); Assert.False(arrList2.IsSynchronized); Assert.Equal(arrList1.Count, arrList2.Count); for (int i = 0; i < arrList1.Count; i++) { Assert.Equal(arrList1[i], arrList2[i]); } // Remove an object from the original list and verify the object underneath has been cut arrList1.RemoveAt(9); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2[9]); // We cant remove or add to the fixed list Assert.Throws<NotSupportedException>(() => arrList2.RemoveRange(0, 1)); Assert.Throws<NotSupportedException>(() => arrList2.AddRange(new ArrayList())); Assert.Throws<NotSupportedException>(() => arrList2.InsertRange(0, new ArrayList())); Assert.Throws<NotSupportedException>(() => arrList2.TrimToSize()); Assert.Throws<NotSupportedException>(() => arrList2.Capacity = 10); } [Fact] public static void FixedSize_ReadOnlyArrayList() { ArrayList arrList = ArrayList.FixedSize(ArrayList.ReadOnly(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.True(arrList.IsReadOnly); Assert.False(arrList.IsSynchronized); } [Fact] public static void FixedSize_SynchronizedArrayList() { ArrayList arrList = ArrayList.FixedSize(ArrayList.Synchronized(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void FixedSize_RangeArrayList() { ArrayList arrList = ArrayList.FixedSize(new ArrayList()).GetRange(0, 0); Assert.True(arrList.IsFixedSize); } [Fact] public static void FixedSize_ArrayList_CanChangeExistingItems() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); ArrayList arrList2 = ArrayList.FixedSize(arrList1); arrList2[0] = 10; Assert.Equal(10, arrList2[0]); } [Fact] public static void FixedSize_ArrayList_NullCollection_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.FixedSize(null)); // List is null } [Fact] public static void FixedSize_IList() { ArrayList arrList = Helpers.CreateIntArrayList(10); IList iList = ArrayList.FixedSize((IList)arrList); Assert.True(iList.IsFixedSize); Assert.False(iList.IsReadOnly); Assert.False(iList.IsSynchronized); Assert.Equal(arrList.Count, iList.Count); for (int i = 0; i < arrList.Count; i++) { Assert.Equal(arrList[i], iList[i]); } } [Fact] public static void FixedSize_SynchronizedIList() { IList iList = ArrayList.FixedSize((IList)ArrayList.Synchronized(new ArrayList())); Assert.True(iList.IsFixedSize); Assert.False(iList.IsReadOnly); Assert.True(iList.IsSynchronized); } [Fact] public static void FixedSize_IList_ModifyingUnderlyingCollection_CutsFacade() { ArrayList arrList = Helpers.CreateIntArrayList(10); IList iList = ArrayList.FixedSize((IList)arrList); // Remove an object from the original list. Verify the object underneath has been cut arrList.RemoveAt(9); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => iList[9]); } [Fact] public static void FixedSize_IList_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.FixedSize((IList)null)); // List is null } [Fact] public static void GetEnumerator_Basic_ArrayListContainingItself() { // Verify the enumerator works correctly when the ArrayList itself is in the ArrayList ArrayList arrList1 = Helpers.CreateIntArrayList(10); arrList1.Add(arrList1); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { IEnumerator enumerator = arrList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int index = 0; while (enumerator.MoveNext()) { Assert.StrictEqual(enumerator.Current, arrList2[index]); index++; } enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_Basic_DerivedArrayList() { // The enumerator for a derived (subclassed) ArrayList is different to a normal ArrayList as it does not run an optimized MoveNext() function var arrList = new DerivedArrayList(Helpers.CreateIntArrayList(10)); IEnumerator enumerator = arrList.GetEnumerator(); for (int i = 0; i < 2; i++) { int index = 0; while (enumerator.MoveNext()) { Assert.StrictEqual(enumerator.Current, arrList[index]); index++; } enumerator.Reset(); } } [Fact] public static void GetEnumerator_Int_Int() { int index = 3; int count = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { IEnumerator enumerator = arrList2.GetEnumerator(index, count); Assert.NotNull(enumerator); for (int i = index; i < index + count; i++) { Assert.True(enumerator.MoveNext()); Assert.Equal(arrList2[i], enumerator.Current); } Assert.False(enumerator.MoveNext()); }); } [Fact] public static void GetEnumerator_Int_Int_ArrayListContainingItself() { // Verify the enumerator works correctly when the ArrayList itself is in the ArrayList int[] data = Helpers.CreateIntArray(10); ArrayList arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.Insert(0, arrList2); arrList2.Insert(arrList2.Count, arrList2); arrList2.Insert(arrList2.Count / 2, arrList2); var tempArray = new object[data.Length + 3]; tempArray[0] = arrList2; tempArray[tempArray.Length / 2] = arrList2; tempArray[tempArray.Length - 1] = arrList2; Array.Copy(data, 0, tempArray, 1, data.Length / 2); Array.Copy(data, data.Length / 2, tempArray, (tempArray.Length / 2) + 1, data.Length - (data.Length / 2)); // Enumerate the entire collection IEnumerator enumerator = arrList2.GetEnumerator(0, tempArray.Length); for (int loop = 0; loop < 2; ++loop) { for (int i = 0; i < tempArray.Length; i++) { enumerator.MoveNext(); Assert.StrictEqual(tempArray[i], enumerator.Current); } Assert.False(enumerator.MoveNext()); enumerator.Reset(); } // Enumerate only part of the collection enumerator = arrList2.GetEnumerator(1, tempArray.Length - 2); for (int loop = 0; loop < 2; ++loop) { for (int i = 1; i < tempArray.Length - 1; i++) { enumerator.MoveNext(); Assert.StrictEqual(tempArray[i], enumerator.Current); } Assert.False(enumerator.MoveNext()); enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_Int_Int_ZeroCount() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { IEnumerator enumerator = arrList2.GetEnumerator(0, 0); Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); }); } [Fact] public static void GetEnumerator_Int_Int_Invalid() { int index = 3; int count = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { IEnumerator enumerator = arrList2.GetEnumerator(index, count); // If the underlying collection is modified, MoveNext and Reset throw, but Current doesn't if (!arrList2.IsReadOnly) { enumerator.MoveNext(); object originalValue = arrList2[0]; arrList2[0] = 10; object temp = enumerator.Current; Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); arrList2[0] = originalValue; } // Current throws after resetting enumerator = arrList2.GetEnumerator(index, count); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throws if the current index is < 0 or >= count enumerator = arrList2.GetEnumerator(index, count); Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Invalid parameters AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.GetEnumerator(-1, arrList2.Count)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.GetEnumerator(0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.GetEnumerator(0, arrList2.Count + 1)); // Count + list.Count AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.GetEnumerator(-1, arrList2.Count + 1)); // Index < 0 and count > list.Count }); } [Fact] public static void GetRange() { int index = 10; int count = 50; ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { ArrayList range = arrList2.GetRange(index, count); Assert.Equal(count, range.Count); for (int i = 0; i < range.Count; i++) { Assert.Equal(arrList2[i + index], range[i]); } Assert.Equal(arrList2.IsFixedSize, range.IsFixedSize); Assert.Equal(arrList2.IsReadOnly, range.IsReadOnly); Assert.False(range.IsSynchronized); Assert.Throws<NotSupportedException>(() => range.TrimToSize()); }); } [Fact] public static void GetRange_ChangeUnderlyingCollection() { int index = 10; int count = 50; ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { ArrayList range = arrList2.GetRange(index, count);// We can change the underlying collection through the range and this[int index] if (!range.IsReadOnly) { for (int i = 0; i < 50; i++) range[i] = (int)range[i] + 1; for (int i = 0; i < 50; i++) { Assert.Equal(i + 10 + 1, range[i]); } for (int i = 0; i < 50; i++) range[i] = (int)range[i] - 1; } // We can change the underlying collection through the range and Add if (!range.IsFixedSize) { for (int i = 0; i < 100; i++) range.Add(i + 1000); Assert.Equal(150, range.Count); Assert.Equal(200, arrList2.Count); for (int i = 0; i < 50; i++) { Assert.Equal(i + 10, range[i]); } for (int i = 0; i < 100; i++) { Assert.Equal(i + 1000, range[50 + i]); } } }); } [Fact] public static void GetRange_ChangeUnderlyingCollection_Invalid() { int index = 10; int count = 50; ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { ArrayList range = arrList2.GetRange(index, count); // If we change the underlying collection through set this[int index] range will start to throw if (arrList2.IsReadOnly) { Assert.Throws<NotSupportedException>(() => arrList2[arrList2.Count - 1] = -1); int iTemp = range.Count; } else { arrList2[arrList2.Count - 1] = -1; Assert.Throws<InvalidOperationException>(() => range.Count); } // If we change the underlying collection through add range will start to throw range = arrList2.GetRange(10, 50); if (arrList2.IsFixedSize) { Assert.Throws<NotSupportedException>(() => arrList2.Add(arrList2.Count + 1000)); int iTemp = range.Count; } else { arrList2.Add(arrList2.Count + 1000); Assert.Throws<InvalidOperationException>(() => range.Count); } }); } [Fact] public static void GetRange_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.GetRange(-1, 50)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.GetRange(0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.GetRange(0, 500)); // Index + count > list.count AssertExtensions.Throws<ArgumentException>(null, () => arrList2.GetRange(arrList2.Count, 1)); // Index >= list.count }); } [Fact] public static void GetRange_Empty() { // We should be able to get a range of 0 var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { ArrayList range = arrList2.GetRange(0, 0); Assert.Equal(0, range.Count); }); } [Fact] public static void SetRange() { int index = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); IList setRange = Helpers.CreateIntArrayList(5); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.SetRange(index, setRange); // Verify set for (int i = 0; i < setRange.Count; i++) { Assert.Equal(setRange[i], arrList2[index + i]); } }); } [Fact] public static void SetRange_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.SetRange(3, arrList2)); // Index + collection.Count > list.Count AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.SetRange(-1, new object[1])); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.SetRange(arrList2.Count, new object[1])); // Index > list.Count AssertExtensions.Throws<ArgumentNullException>("c", () => arrList2.SetRange(0, null)); // Collection is null }); } [Fact] public static void SetRange_EmptyCollection() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); ICollection emptyCollection = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } // No change arrList2.SetRange(0, emptyCollection); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(i, arrList2[i]); } }); } [Fact] public static void IndexOf_Basic_DuplicateItems() { var arrList1 = new ArrayList(); arrList1.Add(null); arrList1.Add(arrList1); arrList1.Add(null); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(0, arrList2.IndexOf(null)); }); } [Fact] public static void IndexOf_Int() { int startIndex = 3; var data = new string[21]; for (int i = 0; i < 10; i++) { data[i] = i.ToString(); } for (int i = 10; i < 20; i++) { data[i] = (i - 10).ToString(); } data[20] = null; var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in data) { Assert.Equal(Array.IndexOf(data, value, startIndex), arrList2.IndexOf(value, startIndex)); } }); } [Fact] public static void IndexOf_Int_NonExistentObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(null, 0)); Assert.Equal(-1, arrList2.IndexOf("hello", 1)); Assert.Equal(-1, arrList2.IndexOf(10, 2)); }); } [Fact] public static void IndexOf_Int_ExistentObjectNotInRange() { // Find an existing object before the index (expects -1) ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(0, 1)); }); } [Fact] public static void IndexOf_Int_InvalidStartIndex_ThrowsArgumentOutOfRangeException() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.IndexOf("Batman", -1)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.IndexOf("Batman", arrList2.Count + 1)); // Start index > list.Count Assert.Equal(-1, arrList2.IndexOf("Batman", arrList2.Count, 0)); // Index = list.Count }); } [Fact] public static void IndexOf_Int_Int() { int startIndex = 0; int count = 5; var data = new string[21]; for (int i = 0; i < 10; i++) { data[i] = i.ToString(); } for (int i = 10; i < 20; i++) { data[i] = (i - 10).ToString(); } data[20] = null; var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { Assert.Equal(Array.IndexOf(data, value, startIndex, count), arrList2.IndexOf(value, startIndex, count)); } }); } [Fact] public static void IndexOf_Int_Int_NonExistentObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(null, 0, arrList2.Count)); Assert.Equal(-1, arrList2.IndexOf("hello", 1, arrList2.Count - 1)); Assert.Equal(-1, arrList2.IndexOf(10, 2, arrList2.Count - 2)); }); } [Fact] public static void IndexOf_Int_Int_ExistentObjectNotInRange() { // Find an existing object before the startIndex or after startIndex + count (expects -1) ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(0, 1, arrList2.Count - 1)); Assert.Equal(-1, arrList2.IndexOf(10, 0, 5)); }); } [Fact] public static void IndexOf_Int_Int_InvalidIndexCount_ThrowsArgumentOutOfRangeException() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.IndexOf("Batman", -1, arrList2.Count)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.IndexOf("Batman", arrList2.Count + 1, arrList2.Count)); // Start index > Count AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.IndexOf("Batman", 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.IndexOf("Batman", 3, arrList2.Count + 1)); // Count > list.Count Assert.Equal(-1, arrList2.IndexOf("Batman", arrList2.Count, 0)); // Index = list.Count }); } [Fact] public static void InsertRange() { int index = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); IList arrInsert = Helpers.CreateIntArrayList(10, 10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } // Insert collection into array list and verify. arrList2.InsertRange(index, arrInsert); for (int i = 0; i < arrInsert.Count; i++) { Assert.Equal(arrInsert[i], arrList2[i + index]); } }); } [Fact] public static void InsertRange_LargeCapacity() { // Add a range large enough to increase the capacity of the arrayList by more than a factor of two var arrList1 = new ArrayList(); ArrayList arrInsert = Helpers.CreateIntArrayList(128); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.InsertRange(0, arrInsert); for (int i = 0; i < arrInsert.Count; i++) { Assert.Equal(i, arrList2[i]); } }); } [Fact] public static void InsertRange_EmptyCollection() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); var emptyCollection = new Queue(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.InsertRange(0, emptyCollection); Assert.Equal(arrList1.Count, arrList2.Count); }); } [Fact] public static void InsertRange_WrappedNonArrayList() { // Create an array list by wrapping a non-ArrayList object (e.g. List<T>) var list = new List<int>(Helpers.CreateIntArray(10)); ArrayList arrList = ArrayList.Adapter(list); IList arrInsert = Helpers.CreateIntArrayList(10); arrList.InsertRange(3, arrInsert); for (int i = 0; i < arrInsert.Count; i++) { Assert.Equal(arrInsert[i], arrList[i + 3]); } } [Fact] public static void InsertRange_Itself() { int[] data = Helpers.CreateIntArray(10); var arrList1 = new ArrayList(data); int start = 3; Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.InsertRange(start, arrList2); for (int i = 0; i < arrList2.Count; i++) { int expectedItem; if (i < start) { expectedItem = data[i]; } else if (start <= i && i - start < data.Length) { expectedItem = data[i - start]; } else { expectedItem = data[i - data.Length]; } Assert.Equal(expectedItem, arrList2[i]); } // Verify that ArrayList does not pass the internal array to CopyTo arrList2.Clear(); for (int i = 0; i < 64; i++) { arrList2.Add(i); } ArrayList arrInsert = Helpers.CreateIntArrayList(4); MyCollection myCollection = new MyCollection(arrInsert); arrList2.InsertRange(4, myCollection); Assert.Equal(0, myCollection.StartIndex); Assert.Equal(4, myCollection.Array.Length); }); } [Fact] public static void InsertRange_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.InsertRange(-1, new object[1])); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.InsertRange(1000, new object[1])); // Index > count AssertExtensions.Throws<ArgumentNullException>("c", () => arrList2.InsertRange(3, null)); // Collection is null }); } [Fact] public static void LastIndexOf_Basic() { var data = new string[20]; for (int i = 0; i < 10; i++) { data[i] = i.ToString(); } for (int i = 10; i < data.Length; i++) { data[i] = (i - 10).ToString(); } var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { Assert.Equal(Array.LastIndexOf(data, value), arrList2.LastIndexOf(value)); } Assert.Equal(-1, arrList2.LastIndexOf(null)); }); } [Fact] public static void LastIndexOf_Basic_EmptyArrayList() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf("Batman")); }); } [Fact] public static void LastIndexOf_Basic_NonExistentObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf("hello")); Assert.Equal(-1, arrList2.IndexOf(10)); Assert.Equal(-1, arrList2.IndexOf(null)); }); } [Fact] public static void LastIndexOf_Int() { int startIndex = 3; var data = new string[21]; for (int i = 0; i < 10; i++) { data[i] = i.ToString(); } for (int i = 10; i < 20; i++) { data[i] = (i - 10).ToString(); } data[20] = null; var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { Assert.Equal(Array.LastIndexOf(data, value, startIndex), arrList2.LastIndexOf(value, startIndex)); } Assert.Equal(20, arrList2.LastIndexOf(null, data.Length - 1)); }); } [Fact] public static void LastIndexOf_Int_NonExistentObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(11, 0)); Assert.Equal(-1, arrList2.IndexOf("8", 0)); Assert.Equal(-1, arrList2.IndexOf(null, 0)); }); } [Fact] public static void LastIndexOf_Int_ObjectOutOfRange() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { int ndx = arrList1.IndexOf(0, 1); Assert.Equal(-1, ndx); }); } [Fact] public static void LastIndexOf_Int_InvalidStartIndex_ThrowsArgumentOutOfRangeException() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.LastIndexOf(0, -1)); // StartIndex < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.LastIndexOf(0, arrList2.Count)); // StartIndex >= list.Count }); } [Fact] public static void LastIndexOf_Int_Int() { int startIndex = 15; int count = 10; var data = new string[21]; for (int i = 0; i < 10; i++) { data[i] = i.ToString(); } for (int i = 10; i < 20; i++) { data[i] = (i - 10).ToString(); } data[20] = null; var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { foreach (object value in arrList2) { Assert.Equal(Array.LastIndexOf(data, value, startIndex, count), arrList2.LastIndexOf(value, startIndex, count)); } Assert.Equal(20, arrList2.LastIndexOf(null, data.Length - 1, 2)); }); } [Fact] public static void LastIndexOf_Int_Int_EmptyArrayList() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.LastIndexOf("hello", 0, 0)); }); } [Fact] public static void LastIndexOf_Int_Int_NonExistentObject() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { Assert.Equal(-1, arrList2.IndexOf(100, 0, arrList2.Count)); }); } [Fact] public static void LastIndexOf_Int_Int_ObjectOutOfRange() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { int ndx = arrList2.IndexOf(0, 1, arrList2.Count - 1); // Start index > object's index Assert.Equal(-1, ndx); ndx = arrList2.IndexOf(10, 0, arrList2.Count - 2); // Start index + count < object's index Assert.Equal(-1, ndx); }); } [Fact] public static void LastIndexOf_Int_Int_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.LastIndexOf(0, -1, 2)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => arrList2.LastIndexOf(0, arrList2.Count, 2)); // Index >= list.Count AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.LastIndexOf(0, 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.LastIndexOf(0, 0, arrList2.Count + 1)); // Count > list.Count AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.LastIndexOf(0, 4, arrList2.Count - 4)); // Index + count > list.Count }); } [Fact] public static void ReadOnly_ArrayList() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); ArrayList arrList2 = ArrayList.ReadOnly(arrList1); Assert.True(arrList2.IsFixedSize); Assert.True(arrList2.IsReadOnly); Assert.False(arrList2.IsSynchronized); Assert.Equal(arrList1.Count, arrList2.Count); for (int i = 0; i < arrList1.Count; i++) { Assert.Equal(arrList1[i], arrList2[i]); } // Remove an object from the original list and verify the object underneath has been cut arrList1.RemoveAt(9); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2[9]); // We cant remove, change or add to the readonly list Assert.Throws<NotSupportedException>(() => arrList2.RemoveRange(0, 1)); Assert.Throws<NotSupportedException>(() => arrList2.AddRange(new ArrayList())); Assert.Throws<NotSupportedException>(() => arrList2.InsertRange(0, new ArrayList())); Assert.Throws<NotSupportedException>(() => arrList2.Reverse()); Assert.Throws<NotSupportedException>(() => arrList2.Sort()); Assert.Throws<NotSupportedException>(() => arrList2.TrimToSize()); Assert.Throws<NotSupportedException>(() => arrList2.Capacity = 10); Assert.Throws<NotSupportedException>(() => arrList2[2] = 5); Assert.Throws<NotSupportedException>(() => arrList2.SetRange(0, new ArrayList())); // We can get a readonly from this readonly ArrayList arrList3 = ArrayList.ReadOnly(arrList2); Assert.True(arrList2.IsReadOnly); Assert.True(arrList3.IsReadOnly); // Verify we cant access remove, change or add to the readonly list Assert.Throws<NotSupportedException>(() => arrList2.RemoveAt(0)); } [Fact] public static void ReadOnly_SynchronizedArrayList() { ArrayList arrList = ArrayList.ReadOnly(ArrayList.Synchronized(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.True(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void ReadOnly_ArrayList_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.ReadOnly(null)); // List is null } [Fact] public static void ReadOnly_IList() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); IList iList = ArrayList.ReadOnly((IList)arrList1); Assert.True(iList.IsFixedSize); Assert.True(iList.IsReadOnly); Assert.False(iList.IsSynchronized); Assert.Equal(arrList1.Count, iList.Count); for (int i = 0; i < iList.Count; i++) { Assert.Equal(arrList1[i], iList[i]); } } [Fact] public static void ReadOnly_SynchronizedIList() { IList iList = ArrayList.ReadOnly((IList)ArrayList.Synchronized(new ArrayList())); Assert.True(iList.IsFixedSize); Assert.True(iList.IsReadOnly); Assert.True(iList.IsSynchronized); } [Fact] public static void ReadOnly_IList_ModifiyingUnderlyingCollection_CutsFacade() { ArrayList arrList = Helpers.CreateIntArrayList(10); IList iList = ArrayList.ReadOnly((IList)arrList); // Remove an object from the original list. Verify the object underneath has been cut arrList.RemoveAt(9); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => iList[9]); } [Fact] public static void ReadOnly_IList_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.ReadOnly((IList)null)); // List is null } [Fact] public static void RemoveRange() { int index = 3; int count = 3; ArrayList arrList1 = Helpers.CreateIntArrayList(10); var expected = new int[] { 0, 1, 2, 6, 7, 8, 9 }; Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.RemoveRange(index, count); // Verify remove for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(expected[i], arrList2[i]); } }); } [Fact] public static void RemoveRange_ZeroCount() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } arrList2.RemoveRange(3, 0); Assert.Equal(arrList1.Count, arrList2.Count); // No change for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(i, arrList2[i]); } }); } [Fact] public static void RemoveRange_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsFixedSize) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.RemoveRange(-1, 1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.RemoveRange(1, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.RemoveRange(arrList2.Count, 1)); // Index > list.Count AssertExtensions.Throws<ArgumentException>(null, () => arrList2.RemoveRange(0, arrList2.Count + 1)); // Count > list.Count AssertExtensions.Throws<ArgumentException>(null, () => arrList2.RemoveRange(5, arrList2.Count - 1)); // Index + count > list.Count }); } [Fact] public static void Remove_Null() { var arrList = new ArrayList(); arrList.Add(null); arrList.Add(arrList); arrList.Add(null); arrList.Remove(arrList); arrList.Remove(null); arrList.Remove(null); Assert.Equal(0, arrList.Count); } [Fact] public static void Repeat() { ArrayList arrList = ArrayList.Repeat(5, 100); for (int i = 0; i < arrList.Count; i++) { Assert.Equal(5, arrList[i]); } } [Fact] public static void Repeat_Null() { ArrayList arrList = ArrayList.Repeat(null, 100); for (int i = 0; i < arrList.Count; i++) { Assert.Null(arrList[i]); } } [Fact] public static void Repeat_ZeroCount() { ArrayList arrList = ArrayList.Repeat(5, 0); Assert.Equal(0, arrList.Count); } [Fact] public static void Repeat_NegativeCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => ArrayList.Repeat(5, -1)); // Count < 0 } [Fact] public static void Reverse_Basic() { int[] expected = Helpers.CreateIntArray(10); var arrList1 = new ArrayList(expected); Array.Reverse(expected); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Reverse(); Assert.Equal(arrList1.Count, arrList2.Count); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(expected[i], arrList2[i]); } }); } [Fact] public static void Reverse_Basic_EmptyArrayList() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Reverse(); Assert.Equal(0, arrList2.Count); }); } [Fact] public static void Reverse_Basic_SingleObjectArrayList() { var arrList1 = new ArrayList(); arrList1.Add(0); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Reverse(); Assert.Equal(0, arrList2[0]); Assert.Equal(1, arrList2.Count); }); } [Fact] public static void Reverse_Int_Int() { int index = 5; int count = 4; int[] expected = Helpers.CreateIntArray(10); var arrList1 = new ArrayList(expected); Array.Reverse(expected, index, count); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Reverse(index, count); Assert.Equal(arrList1.Count, arrList2.Count); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(expected[i], arrList2[i]); } }); } [Fact] public static void Reverse_Int_Int_ZeroCount() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Reverse(0, 0); // No change Assert.Equal(arrList1.Count, arrList2.Count); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(arrList1[i], arrList2[i]); } }); } [Fact] public static void Reverse_Int_Int_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.Reverse(-1, arrList2.Count)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.Reverse(0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.Reverse(1000, arrList2.Count)); // Index is too big }); } [Fact] public static void Sort_Basic() { int[] expected = Helpers.CreateIntArray(10); var arrList1 = new ArrayList(expected); Array.Sort(expected); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Sort(); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(expected[i], arrList2[i]); } }); } [Fact] public static void Sort_Basic_EmptyArrayList() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Sort(); Assert.Equal(0, arrList2.Count); }); } [Fact] public static void Sort_Basic_SingleObjectArrayList() { var arrList1 = new ArrayList(); arrList1.Add(1); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Sort(); Assert.Equal(1, arrList2.Count); }); } [Fact] public static void Sort_IComparer() { int[] data = Helpers.CreateIntArray(10); int[] ascendingData = Helpers.CreateIntArray(10); int[] descendingData = Helpers.CreateIntArray(10); Array.Sort(ascendingData, new AscendingComparer()); Array.Sort(descendingData, new DescendingComparer()); var arrList1 = new ArrayList(data); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Sort(null); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(ascendingData[i], arrList2[i]); } arrList2.Sort(new AscendingComparer()); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(ascendingData[i], arrList2[i]); } arrList2.Sort(new DescendingComparer()); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(descendingData[i], arrList2[i]); } }); } [Fact] public static void Sort_Int_Int_IComparer() { int index = 3; int count = 5; int[] expected = Helpers.CreateIntArray(10); var arrList1 = new ArrayList(expected); Array.Sort(expected, index, count, new AscendingComparer()); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } arrList2.Sort(3, 5, new AscendingComparer()); for (int i = 0; i < arrList2.Count; i++) { Assert.Equal(expected[i], arrList2[i]); } }); } [Fact] public static void Sort_Int_Int_IComparer_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => arrList2.Sort(-1, arrList2.Count, null)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => arrList2.Sort(0, -1, null)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => arrList2.Sort(arrList2.Count, arrList2.Count, null)); // Index >= list.Count AssertExtensions.Throws<ArgumentException>(null, () => arrList2.Sort(0, arrList2.Count + 1, null)); // Count = list.Count }); } [Fact] public static void Sort_MultipleDataTypes_ThrowsInvalidOperationException() { var arrList1 = new ArrayList(); arrList1.Add((short)1); arrList1.Add(1); arrList1.Add((long)1); arrList1.Add((ushort)1); arrList1.Add((uint)1); arrList1.Add((ulong)1); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { if (arrList2.IsReadOnly) { return; } Assert.Throws<InvalidOperationException>(() => arrList2.Sort()); }); } [Fact] public static void Synchronized_ArrayList() { ArrayList arrList = ArrayList.Synchronized(new ArrayList()); Assert.False(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void Synchronized_FixedSizeArrayList() { ArrayList arrList = ArrayList.Synchronized(ArrayList.FixedSize(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.False(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void Synchronized_ReadOnlyArrayList() { ArrayList arrList = ArrayList.Synchronized(ArrayList.ReadOnly(new ArrayList())); Assert.True(arrList.IsFixedSize); Assert.True(arrList.IsReadOnly); Assert.True(arrList.IsSynchronized); } [Fact] public static void Synchronized_ArrayList_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.Synchronized(null)); // List is null } [Fact] public static void Synchronized_FixedSizeIList() { IList iList = ArrayList.Synchronized((IList)ArrayList.FixedSize(new ArrayList())); Assert.True(iList.IsFixedSize); Assert.False(iList.IsReadOnly); Assert.True(iList.IsSynchronized); } [Fact] public static void Synchronized_ReadOnlyIList() { IList iList = ArrayList.Synchronized((IList)ArrayList.ReadOnly(new ArrayList())); Assert.True(iList.IsFixedSize); Assert.True(iList.IsReadOnly); Assert.True(iList.IsSynchronized); } [Fact] public static void Synchronized_IList_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => ArrayList.Synchronized((IList)null)); // List is null } [Fact] public static void ToArray() { // ToArray returns an array of this. We will not extensively test this method as // this is a thin wrapper on Array.Copy which is extensively tested ArrayList arrList1 = Helpers.CreateIntArrayList(10); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { object[] arr1 = arrList2.ToArray(); Array arr2 = arrList2.ToArray(typeof(int)); for (int i = 0; i < 10; i++) { Assert.Equal(i, arr1[i]); Assert.Equal(i, arr2.GetValue(i)); } }); } [Fact] public static void ToArray_EmptyArrayList() { var arrList1 = new ArrayList(); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { object[] arr1 = arrList2.ToArray(); Assert.Equal(0, arr1.Length); Array arr2 = arrList2.ToArray(typeof(object)); Assert.Equal(0, arr2.Length); }); } [Fact] public static void ToArray_Invalid() { ArrayList arrList1 = Helpers.CreateIntArrayList(100); Helpers.PerformActionOnAllArrayListWrappers(arrList1, arrList2 => { // This should be covered in Array.Copy, but lets do it for completion's sake Assert.Throws<InvalidCastException>(() => arrList2.ToArray(typeof(string))); // Objects stored are not strings AssertExtensions.Throws<ArgumentNullException>("type", () => arrList2.ToArray(null)); // Type is null }); } [Fact] public static void TrimToSize() { ArrayList arrList = Helpers.CreateIntArrayList(10); arrList.Capacity = 2 * arrList.Count; Assert.True(arrList.Capacity > arrList.Count); arrList.TrimToSize(); Assert.Equal(arrList.Count, arrList.Capacity); // Test on Adapter arrList = ArrayList.Adapter(arrList); arrList.TrimToSize(); // Test on Synchronized arrList = ArrayList.Synchronized(Helpers.CreateIntArrayList(10)); arrList.TrimToSize(); Assert.Equal(arrList.Count, arrList.Capacity); } private class BinarySearchComparer : IComparer { public virtual int Compare(object x, object y) { if (x is string) { return ((string)x).CompareTo((string)y); } var comparer = new Comparer(Globalization.CultureInfo.InvariantCulture); if (x is int || y is string) { return comparer.Compare(x, y); } return -1; } } private class Foo { public string StringValue { get; set; } = "Hello World"; } private class MyCollection : ICollection { private ICollection _collection; private Array _array; private int _startIndex; public MyCollection(ICollection collection) { _collection = collection; } public Array Array => _array; public int StartIndex => _startIndex; public int Count =>_collection.Count; public object SyncRoot => _collection.SyncRoot; public bool IsSynchronized => _collection.IsSynchronized; public void CopyTo(Array array, int startIndex) { _array = array; _startIndex = startIndex; _collection.CopyTo(array, startIndex); } public IEnumerator GetEnumerator() { throw new NotSupportedException(); } } private class AscendingComparer : IComparer { public virtual int Compare(object x, object y) => ((int)x).CompareTo((int)y); } private class DescendingComparer : IComparer { public virtual int Compare(object x, object y) => -((int)x).CompareTo((int)y); } private class DerivedArrayList : ArrayList { public DerivedArrayList(ICollection c) : base(c) { } } } public class ArrayList_SyncRootTests { private ArrayList _arrDaughter; private ArrayList _arrGrandDaughter; [Fact] public void GetSyncRoot() { const int NumberOfElements = 100; const int NumberOfWorkers = 10; // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother ArrayList // 2) Get a Fixed wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth ArrayList arrMother1 = Helpers.CreateIntArrayList(NumberOfElements); Helpers.PerformActionOnAllArrayListWrappers(arrMother1, arrMother2 => { ArrayList arrSon1 = ArrayList.FixedSize(arrMother2); ArrayList arrSon2 = ArrayList.ReadOnly(arrMother2); _arrGrandDaughter = ArrayList.Synchronized(arrMother2); _arrDaughter = ArrayList.Synchronized(arrMother2); Assert.True(arrMother2.SyncRoot is ArrayList); Assert.True(arrSon1.SyncRoot is ArrayList); Assert.True(arrSon2.SyncRoot is ArrayList); Assert.True(_arrDaughter.SyncRoot is ArrayList); Assert.Equal(arrSon1.SyncRoot, arrMother2.SyncRoot); Assert.True(_arrGrandDaughter.SyncRoot is ArrayList); arrMother2 = new ArrayList(); for (int i = 0; i < NumberOfElements; i++) { arrMother2.Add(i); } arrSon1 = ArrayList.FixedSize(arrMother2); arrSon2 = ArrayList.ReadOnly(arrMother2); _arrGrandDaughter = ArrayList.Synchronized(arrSon1); _arrDaughter = ArrayList.Synchronized(arrMother2); // We are going to rumble with the ArrayLists with 2 threads var workers = new Task[NumberOfWorkers]; var action1 = new Action(SortElements); var action2 = new Action(ReverseElements); for (int iThreads = 0; iThreads < NumberOfWorkers; iThreads += 2) { workers[iThreads] = Task.Run(action1); workers[iThreads + 1] = Task.Run(action2); } Task.WaitAll(workers); // Checking time // Now lets see how this is done. // Reverse and sort - ascending more likely // Sort followed up Reverse - descending bool fDescending = ((int)arrMother2[0]).CompareTo((int)arrMother2[1]) > 0; int valye = (int)arrMother2[0]; for (int i = 1; i < NumberOfElements; i++) { if (fDescending) { Assert.True(valye.CompareTo((int)arrMother2[i]) > 0); } else { Assert.True(valye.CompareTo((int)arrMother2[i]) < 0); } valye = (int)arrMother2[i]; } }); } private void SortElements() => _arrGrandDaughter.Sort(); private void ReverseElements() => _arrDaughter.Reverse(); } public class ArrayList_SynchronizedTests { public static string[] s_synchronizedTestData = new string[] { "Aquaman", "Atom", "Batman", "Black Canary", "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null, "Aquaman", "Atom", "Batman", "Black Canary", "Captain America" }; private IList _iList; private const int NumberOfElements = 10; private const string Prefix = "String_"; public ArrayList _arrList; public Hashtable _hash; // This will verify that threads will only add elements the num of times they are specified to [Fact] public void Synchronized_ArrayList() { // Make 40 threads which add strHeroes to an ArrayList // the outcome is that the length of the ArrayList should be the same size as the strHeroes array _arrList = ArrayList.Synchronized(new ArrayList()); _hash = Hashtable.Synchronized(new Hashtable()); // Initialize the threads var workers = new Task[7]; for (int i = 0; i < workers.Length; i++) { string name = "ThreadID " + i.ToString(); Action delegStartMethod = () => AddElems(name); workers[i] = Task.Run(delegStartMethod); } Task.WaitAll(workers); Assert.Equal(workers.Length * s_synchronizedTestData.Length, _arrList.Count); } [Fact] public void Synchronized_IList() { int iNumberOfWorkers = 10; _iList = ArrayList.Synchronized((IList)new ArrayList()); var workers = new Task[10]; var action = new Action(AddElements); for (int i = 0; i < workers.Length; i++) { workers[i] = Task.Run(action); } Task.WaitAll(workers); // Checking time Assert.Equal(NumberOfElements * iNumberOfWorkers, _iList.Count); for (int i = 0; i < NumberOfElements; i++) { int iNumberOfTimes = 0; for (int j = 0; j < _iList.Count; j++) { if (((string)_iList[j]).Equals(Prefix + i)) iNumberOfTimes++; } Assert.Equal(iNumberOfTimes, iNumberOfWorkers); } workers = new Task[iNumberOfWorkers]; action = new Action(RemoveElements); for (int i = 0; i < workers.Length; i++) { workers[i] = Task.Run(action); } Task.WaitAll(workers); Assert.Equal(0, _iList.Count); } public void AddElems(string currThreadName) { int iNumTimesThreadUsed = 0; for (int i = 0; i < s_synchronizedTestData.Length; i++) { // To test that we only use the right threads the right number of times keep track with the hashtable // how many times we use this thread try { _hash.Add(currThreadName, null); // This test assumes ADD will throw for dup elements } catch (ArgumentException) { iNumTimesThreadUsed++; } Assert.NotNull(_arrList); Assert.True(_arrList.IsSynchronized); _arrList.Add(s_synchronizedTestData[i]); } Assert.Equal(s_synchronizedTestData.Length - 1, iNumTimesThreadUsed); } private void AddElements() { for (int i = 0; i < NumberOfElements; i++) { _iList.Add(Prefix + i); } } private void RemoveElements() { for (int i = 0; i < NumberOfElements; i++) { _iList.Remove(Prefix + i); } } } }
35.237145
197
0.518313
[ "MIT" ]
Castaneda1914/corefx
src/System.Collections.NonGeneric/tests/ArrayListTests.cs
104,161
C#
namespace Sashay.Core.OasGen.AzureFunctions.Configuration { public sealed class HttpSettings { public HttpSettings() { RoutePrefix = string.Empty; } public string RoutePrefix { get; set; } } }
19.307692
58
0.59761
[ "MIT" ]
joargp/Sashay
src/Sashay.Core.OasGen/AzureFunctions/Configuration/HttpSettings.cs
253
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace Calculator { class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyForm()); } } }
20.227273
65
0.653933
[ "MIT" ]
Mmmolin/Calculator
Calculator/Program.cs
447
C#
using System.Collections.Generic; using System.Threading.Tasks; using commercetools.Sdk.Client; using commercetools.Sdk.Domain; using commercetools.Sdk.Domain.Predicates; using commercetools.Sdk.Domain.Reviews; using commercetools.Sdk.Domain.States; using commercetools.Sdk.HttpApi.Domain.Exceptions; using Xunit; using static commercetools.Sdk.IntegrationTests.Reviews.ReviewsFixture; using static commercetools.Sdk.IntegrationTests.Customers.CustomersFixture; using static commercetools.Sdk.IntegrationTests.Project.ProjectFixture; using static commercetools.Sdk.IntegrationTests.States.StatesFixture; using static commercetools.Sdk.IntegrationTests.Types.TypesFixture; using static commercetools.Sdk.IntegrationTests.Products.ProductsFixture; namespace commercetools.Sdk.IntegrationTests.Reviews { [Collection("Integration Tests")] public class ReviewIntegrationTests { private readonly IClient client; public ReviewIntegrationTests(ServiceProviderFixture serviceProviderFixture) { this.client = serviceProviderFixture.GetService<IClient>(); } [Fact] public async Task CreateReview() { var key = $"CreateReview-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), review => { Assert.Equal(key, (string) review.Key); }); } [Fact] public async Task CreateReviewForProduct() { await WithProduct(client, async product => { await WithReview( client, reviewDraft => DefaultReviewDraftWithTarget(reviewDraft, new ResourceIdentifier<Product> {Key = product.Key}), review => { Assert.NotNull(review.Target); Assert.Equal(product.Id, review.Target.Id); }); }); } [Fact] public async Task GetReviewById() { var key = $"GetReviewById-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { var retrievedReview = await client .ExecuteAsync(new GetByIdCommand<Review>(review.Id)); Assert.Equal(key, retrievedReview.Key); }); } [Fact] public async Task GetReviewByKey() { var key = $"GetReviewByKey-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { var retrievedReview = await client .ExecuteAsync(new GetByKeyCommand<Review>(review.Key)); Assert.Equal(key, retrievedReview.Key); }); } [Fact] public async Task QueryReviews() { var key = $"QueryReviews-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { var queryCommand = new QueryCommand<Review>(); queryCommand.Where(p => p.Key == review.Key.valueOf()); var returnedSet = await client.ExecuteAsync(queryCommand); Assert.Single(returnedSet.Results); Assert.Equal(key, returnedSet.Results[0].Key); }); } [Fact] public async Task DeleteReviewById() { var key = $"DeleteReviewById-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { await client.ExecuteAsync(new DeleteByIdCommand<Review>(review)); await Assert.ThrowsAsync<NotFoundException>( () => client.ExecuteAsync(new GetByIdCommand<Review>(review)) ); }); } [Fact] public async Task DeleteReviewByKey() { var key = $"DeleteReviewByKey-{TestingUtility.RandomString()}"; await WithReview( client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { await client.ExecuteAsync(new DeleteByKeyCommand<Review>(review.Key, review.Version)); await Assert.ThrowsAsync<NotFoundException>( () => client.ExecuteAsync(new GetByIdCommand<Review>(review)) ); }); } #region UpdateActions [Fact] public async Task UpdateReviewSetKey() { var newKey = $"UpdateReviewSetKey-{TestingUtility.RandomString()}"; await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); SetKeyUpdateAction setKeyAction = new SetKeyUpdateAction() {Key = newKey}; updateActions.Add(setKeyAction); var updatedReview = await client .ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(newKey, updatedReview.Key); return updatedReview; }); } [Fact] public async Task UpdateReviewSetAuthorName() { var key = $"UpdateReviewSetAuthorName-{TestingUtility.RandomString()}"; var authorName = $"AuthorName-{TestingUtility.RandomString()}"; await WithUpdateableReview(client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { var updateActions = new List<UpdateAction<Review>>(); var setAuthorNameAction = new SetAuthorNameUpdateAction {AuthorName = authorName}; updateActions.Add(setAuthorNameAction); var updatedReview = await client .ExecuteAsync(new UpdateByKeyCommand<Review>(key, review.Version, updateActions)); Assert.Equal(authorName, updatedReview.AuthorName); return updatedReview; }); } [Fact] public async Task UpdateReviewSetCustomer() { var key = $"UpdateReviewSetCustomer-{TestingUtility.RandomString()}"; await WithCustomer(client, async customer => { await WithUpdateableReview(client, reviewDraft => DefaultReviewDraftWithKey(reviewDraft, key), async review => { var updateActions = new List<UpdateAction<Review>>(); var setCustomerAction = new SetCustomerUpdateAction { Customer = customer.ToKeyResourceIdentifier() }; updateActions.Add(setCustomerAction); var updateCommand = new UpdateByKeyCommand<Review>(key, review.Version, updateActions); updateCommand.Expand(r => r.Customer); var updatedReview = await client.ExecuteAsync(updateCommand); Assert.NotNull(updatedReview.Customer.Obj); Assert.Equal(customer.Key, updatedReview.Customer.Obj.Key); return updatedReview; }); }); } [Fact] public async Task UpdateReviewSetRating() { var newRating = TestingUtility.RandomInt(1, 100); await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var setRatingAction = new SetRatingUpdateAction() {Rating = newRating}; updateActions.Add(setRatingAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(newRating, updatedReview.Rating); return updatedReview; }); } [Fact] public async Task UpdateReviewSetTarget() { await WithProduct(client, async product => { await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var setTargetAction = new SetTargetUpdateAction { Target = new ResourceIdentifier<Product> { Key = product.Key } }; updateActions.Add(setTargetAction); var updatedReview = await client .ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.NotNull(updatedReview.Rating); Assert.Equal(product.Id, updatedReview.Target.Id); return updatedReview; }); }); } [Fact] public async Task UpdateReviewSetText() { var newText = TestingUtility.RandomString(); await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var setTextAction = new SetTextUpdateAction {Text = newText}; updateActions.Add(setTextAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(newText, updatedReview.Text); return updatedReview; }); } [Fact] public async Task UpdateReviewSetTitle() { var newTitle = TestingUtility.RandomString(); await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var setTextAction = new SetTitleUpdateAction {Title = newTitle}; updateActions.Add(setTextAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(newTitle, updatedReview.Title); return updatedReview; }); } [Fact] public async Task UpdateReviewSetLocale() { var projectLanguages = GetProjectLanguages(client); Assert.True(projectLanguages.Count > 0); //make sure that project has at least one language string locale = projectLanguages[0]; await WithUpdateableReview(client, async review => { Assert.Null(review.Locale); var updateActions = new List<UpdateAction<Review>>(); var setLocaleAction = new SetLocaleUpdateAction {Locale = locale}; updateActions.Add(setLocaleAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(locale, updatedReview.Locale); return updatedReview; }); } [Fact] public async Task UpdateReviewTransitionToNewState() { await WithState(client, stateDraft => DefaultStateDraftWithType(stateDraft, StateType.ReviewState), async state => { await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var transitionStateAction = new TransitionStateUpdateAction { State = state.ToKeyResourceIdentifier() }; updateActions.Add(transitionStateAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.NotNull(updatedReview.State); Assert.Equal(state.Id, updatedReview.State.Id); return updatedReview; }); }); } [Fact] public async Task UpdateReviewSetCustomType() { var fields = CreateNewFields(); await WithType(client, async type => { await WithUpdateableReview(client, async review => { var updateActions = new List<UpdateAction<Review>>(); var setTypeAction = new SetCustomTypeUpdateAction { Type = type.ToKeyResourceIdentifier(), Fields = fields }; updateActions.Add(setTypeAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(type.Id, updatedReview.Custom.Type.Id); return updatedReview; }); }); } [Fact] public async Task UpdateReviewSetCustomField() { var fields = CreateNewFields(); var newValue = TestingUtility.RandomString(10); await WithType(client, async type => { await WithUpdateableReview(client, reviewDraft => DefaultReviewDraftWithCustomType(reviewDraft, type, fields), async review => { Assert.Equal(type.Id, review.Custom.Type.Id); var updateActions = new List<UpdateAction<Review>>(); var setCustomFieldUpdateAction = new SetCustomFieldUpdateAction() { Name = "string-field", Value = newValue }; updateActions.Add(setCustomFieldUpdateAction); var updatedReview = await client.ExecuteAsync(new UpdateByIdCommand<Review>(review, updateActions)); Assert.Equal(newValue, updatedReview.Custom.Fields["string-field"]); return updatedReview; }); }); } #endregion } }
40.229551
128
0.533876
[ "Apache-2.0" ]
onepiecefreak3/commercetools-dotnet-core-sdk
commercetools.Sdk/IntegrationTests/commercetools.Sdk.IntegrationTests/Reviews/ReviewIntegrationTests.cs
15,247
C#
using MVVM.Core.ViewModels; using UniRx.Async; namespace MVVM.Extension.Views.Common { public interface IView { void Show(); void Hide(); bool Visibility { get; set; } UniTask InitializeAsync(ViewModelBase viewModel); } }
18.866667
58
0.60424
[ "MIT" ]
aliagamon/MVVM.Extention
Views/Common/IView.cs
285
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 合同模板管理接口 * 电子签章-合同模板管理接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Cloudsign.Apis { /// <summary> /// 删除合同模板 [MFA enabled] /// </summary> public class DeleteTemplateResult : JdcloudResult { } }
25
76
0.715122
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cloudsign/Apis/DeleteTemplateResult.cs
1,077
C#
using System; using System.Collections.Generic; using System.Linq; using CodeGeneration; namespace ABT { public enum StorageClass { AUTO, STATIC, EXTERN, TYPEDEF } public sealed class Decln : ExternDecln { public Decln(String name, StorageClass scs, ExprType type, Option<Initr> initr) { this.name = name; this.scs = scs; this.type = type; this.initr = initr; } public override String ToString() { String str = "[" + this.scs + "] "; str += this.name; str += " : " + this.type; return str; } // * function; // * extern function; // * static function; // * obj; // * obj = Init; // * static obj; // * static obj = Init; // * extern obj; // * extern obj = Init; public void CGenDecln(Env env, CGenState state) { if (env.IsGlobal()) { if (this.initr.IsSome) { Initr initr = this.initr.Value; switch (this.scs) { case StorageClass.AUTO: state.GLOBL(this.name); break; case StorageClass.EXTERN: throw new InvalidProgramException(); case StorageClass.STATIC: break; case StorageClass.TYPEDEF: // Ignore. return; default: throw new InvalidProgramException(); } state.DATA(); state.ALIGN(ExprType.ALIGN_LONG); state.CGenLabel(this.name); Int32 last = 0; initr.Iterate(this.type, (Int32 offset, Expr expr) => { if (offset > last) { state.ZERO(offset - last); } if (!expr.IsConstExpr) { throw new InvalidOperationException("Cannot initialize with non-const expression."); } switch (expr.Type.Kind) { // TODO: without const char/short, how do I initialize? case ExprTypeKind.CHAR: case ExprTypeKind.UCHAR: case ExprTypeKind.SHORT: case ExprTypeKind.USHORT: throw new NotImplementedException(); case ExprTypeKind.LONG: state.LONG(((ConstLong)expr).Value); break; case ExprTypeKind.ULONG: state.LONG((Int32)((ConstULong)expr).Value); break; case ExprTypeKind.POINTER: state.LONG((Int32)((ConstPtr)expr).Value); break; case ExprTypeKind.FLOAT: byte[] float_bytes = BitConverter.GetBytes(((ConstFloat)expr).Value); Int32 intval = BitConverter.ToInt32(float_bytes, 0); state.LONG(intval); break; case ExprTypeKind.DOUBLE: byte[] double_bytes = BitConverter.GetBytes(((ConstDouble)expr).Value); Int32 first_int = BitConverter.ToInt32(double_bytes, 0); Int32 second_int = BitConverter.ToInt32(double_bytes, 4); state.LONG(first_int); state.LONG(second_int); break; default: throw new InvalidProgramException(); } last = offset + expr.Type.SizeOf; }); } else { // Global without initialization. switch (this.scs) { case StorageClass.AUTO: // .comm name,size,align break; case StorageClass.EXTERN: break; case StorageClass.STATIC: // .local name // .comm name,size,align state.LOCAL(this.name); break; case StorageClass.TYPEDEF: // Ignore. return; default: throw new InvalidProgramException(); } if (this.type.Kind != ExprTypeKind.FUNCTION) { state.COMM(this.name, this.type.SizeOf, ExprType.ALIGN_LONG); } } state.NEWLINE(); } else { // stack object state.CGenExpandStackTo(env.StackSize, ToString()); Int32 stack_size = env.StackSize; // pos should be equal to stack_size, but whatever... Int32 pos = env.Find(this.name).Value.Offset; if (this.initr.IsNone) { return; } Initr initr = this.initr.Value; initr.Iterate(this.type, (Int32 offset, Expr expr) => { Reg ret = expr.CGenValue(state); switch (expr.Type.Kind) { case ExprTypeKind.CHAR: case ExprTypeKind.UCHAR: state.MOVB(Reg.EAX, pos + offset, Reg.EBP); break; case ExprTypeKind.SHORT: case ExprTypeKind.USHORT: state.MOVW(Reg.EAX, pos + offset, Reg.EBP); break; case ExprTypeKind.DOUBLE: state.FSTPL(pos + offset, Reg.EBP); break; case ExprTypeKind.FLOAT: state.FSTPS(pos + offset, Reg.EBP); break; case ExprTypeKind.LONG: case ExprTypeKind.ULONG: case ExprTypeKind.POINTER: state.MOVL(Reg.EAX, pos + offset, Reg.EBP); break; case ExprTypeKind.STRUCT_OR_UNION: state.MOVL(Reg.EAX, Reg.ESI); state.LEA(pos + offset, Reg.EBP, Reg.EDI); state.MOVL(expr.Type.SizeOf, Reg.ECX); state.CGenMemCpy(); break; case ExprTypeKind.ARRAY: case ExprTypeKind.FUNCTION: throw new InvalidProgramException($"How could a {expr.Type.Kind} be in a init list?"); default: throw new InvalidProgramException(); } state.CGenForceStackSizeTo(stack_size); }); } // stack object } private readonly String name; private readonly StorageClass scs; private readonly ExprType type; private readonly Option<Initr> initr; } /// <summary> /// 1. Scalar: an expression, optionally enclosed in braces. /// int a = 1; // valid /// int a = { 1 }; // valid /// int a[] = { { 1 }, 2 }; // valid /// int a = {{ 1 }}; // warning in gcc, a == 1; error in MSVC /// int a = { { 1 }, 2 }; // warning in gcc, a == 1; error in MSVC /// int a = { 1, 2 }; // warning in gcc, a == 1; error in MSVC /// I'm following MSVC: you either put an expression, or add a single layer of brace. /// /// 2. Union: /// union A { int a; int b; }; /// union A u = { 1 }; // always initialize the first member, i.e. a, not b. /// union A u = {{ 1 }}; // valid /// union A u = another_union; // valid /// /// 3. Struct: /// struct A { int a; int b; }; /// struct A = another_struct; // valid /// struct A = { another_struct }; // error, once you put a brace, the compiler assumes you want to initialize members. /// /// From 2 and 3, once seen union or struct, either read expression or brace. /// /// 4. Array of characters: /// char a[] = { 'a', 'b' }; // valid /// char a[] = "abc"; // becomes char a[4]: include '\0' /// char a[3] = "abc"; // valid, ignore '\0' /// char a[2] = "abc"; // warning in gcc; error in MSVC /// If the aggregate contains members that are aggregates or unions, or if the first member of a union is an aggregate or union, the rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the members of the subaggregate or the first member of the contained union. Otherwise, only enough initializers from the list are taken to account for the members of the first subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next member of the aggregate of which the current subaggregate or contained union is a part. /// </summary> public abstract class Initr { public enum Kind { EXPR, INIT_LIST } public abstract Kind kind { get; } public abstract Initr ConformType(MemberIterator iter); public Initr ConformType(ExprType type) => ConformType(new MemberIterator(type)); public abstract void Iterate(MemberIterator iter, Action<Int32, Expr> action); public void Iterate(ExprType type, Action<Int32, Expr> action) => Iterate(new MemberIterator(type), action); } public class InitExpr : Initr { public InitExpr(Expr expr) { this.expr = expr; } public readonly Expr expr; public override Kind kind => Kind.EXPR; public override Initr ConformType(MemberIterator iter) { iter.Locate(this.expr.Type); Expr expr = TypeCast.MakeCast(this.expr, iter.CurType); return new InitExpr(expr); } public override void Iterate(MemberIterator iter, Action<Int32, Expr> action) { iter.Locate(this.expr.Type); Int32 offset = iter.CurOffset; Expr expr = this.expr; action(offset, expr); } } public class InitList : Initr { public InitList(List<Initr> initrs) { this.initrs = initrs; } public override Kind kind => Kind.INIT_LIST; public readonly List<Initr> initrs; public override Initr ConformType(MemberIterator iter) { iter.InBrace(); List<Initr> initrs = new List<Initr>(); for (Int32 i = 0; i < this.initrs.Count; ++i) { initrs.Add(this.initrs[i].ConformType(iter)); if (i != this.initrs.Count - 1) { iter.Next(); } } iter.OutBrace(); return new InitList(initrs); } public override void Iterate(MemberIterator iter, Action<Int32, Expr> action) { iter.InBrace(); for (Int32 i = 0; i < this.initrs.Count; ++i) { this.initrs[i].Iterate(iter, action); if (i != this.initrs.Count - 1) { iter.Next(); } } iter.OutBrace(); } } public class MemberIterator { public MemberIterator(ExprType type) { this.trace = new List<Status> { new Status(type) }; } public class Status { public Status(ExprType base_type) { this.base_type = base_type; this.indices = new List<Int32>(); } public ExprType CurType => GetType(this.base_type, this.indices); public Int32 CurOffset => GetOffset(this.base_type, this.indices); //public List<Tuple<ExprType, Int32>> GetPath(ExprType base_type, IReadOnlyList<Int32> indices) { // ExprType Type = base_type; // List<Tuple<ExprType, Int32>> path = new List<Tuple<ExprType, int>>(); // foreach (Int32 index in indices) { // switch (Type.Kind) { // case ExprType.Kind.ARRAY: // Type = ((ArrayType)Type).ElemType; // break; // case ExprType.Kind.INCOMPLETE_ARRAY: // case ExprType.Kind.STRUCT_OR_UNION: // default: // throw new InvalidProgramException("Not an aggregate Type."); // } // } //} public static ExprType GetType(ExprType from_type, Int32 to_index) { switch (from_type.Kind) { case ExprTypeKind.ARRAY: return ((ArrayType)from_type).ElemType; case ExprTypeKind.INCOMPLETE_ARRAY: return ((IncompleteArrayType)from_type).ElemType; case ExprTypeKind.STRUCT_OR_UNION: return ((StructOrUnionType)from_type).Attribs[to_index].type; default: throw new InvalidProgramException("Not an aggregate Type."); } } public static ExprType GetType(ExprType base_type, IReadOnlyList<Int32> indices) => indices.Aggregate(base_type, GetType); public static Int32 GetOffset(ExprType from_type, Int32 to_index) { switch (from_type.Kind) { case ExprTypeKind.ARRAY: return to_index * ((ArrayType)from_type).ElemType.SizeOf; case ExprTypeKind.INCOMPLETE_ARRAY: return to_index * ((IncompleteArrayType)from_type).ElemType.SizeOf; case ExprTypeKind.STRUCT_OR_UNION: return ((StructOrUnionType)from_type).Attribs[to_index].offset; default: throw new InvalidProgramException("Not an aggregate Type."); } } public static Int32 GetOffset(ExprType base_type, IReadOnlyList<Int32> indices) { Int32 offset = 0; ExprType from_type = base_type; foreach (Int32 to_index in indices) { offset += GetOffset(from_type, to_index); from_type = GetType(from_type, to_index); } return offset; } public List<ExprType> GetTypes(ExprType base_type, IReadOnlyList<Int32> indices) { List<ExprType> types = new List<ExprType> { base_type }; ExprType from_type = base_type; foreach (Int32 to_index in indices) { from_type = GetType(from_type, to_index); types.Add(from_type); } return types; } public void Next() { // From base_type to CurType. List<ExprType> types = GetTypes(this.base_type, this.indices); // We try to jump as many levels out as we can. do { Int32 index = this.indices.Last(); this.indices.RemoveAt(this.indices.Count - 1); types.RemoveAt(types.Count - 1); ExprType type = types.Last(); switch (type.Kind) { case ExprTypeKind.ARRAY: if (index < ((ArrayType)type).NumElems - 1) { // There are more elements in the array. this.indices.Add(index + 1); return; } break; case ExprTypeKind.INCOMPLETE_ARRAY: this.indices.Add(index + 1); return; case ExprTypeKind.STRUCT_OR_UNION: if (((StructOrUnionType)type).IsStruct && index < ((StructOrUnionType)type).Attribs.Count - 1) { // There are more members in the struct. // (not union, since we can only initialize the first member of a union) this.indices.Add(index + 1); return; } break; default: break; } } while (this.indices.Any()); } /// <summary> /// Read an expression in the initializer list, locate the corresponding position. /// </summary> public void Locate(ExprType type) { switch (type.Kind) { case ExprTypeKind.STRUCT_OR_UNION: LocateStruct((StructOrUnionType)type); return; default: // Even if the expression is of array Type, treat it as a scalar (pointer). LocateScalar(); return; } } /// <summary> /// Try to match a scalar. /// This step doesn't check what scalar it is. Further steps would perform implicit conversions. /// </summary> private void LocateScalar() { while (!this.CurType.IsScalar) { this.indices.Add(0); } } /// <summary> /// Try to match a given struct. /// Go down to find the first element of the same struct Type. /// </summary> private void LocateStruct(StructOrUnionType type) { while (!this.CurType.EqualType(type)) { if (this.CurType.IsScalar) { throw new InvalidOperationException("Trying to match a struct or union, but found a scalar."); } // Go down one level. this.indices.Add(0); } } public readonly ExprType base_type; public readonly List<Int32> indices; } public ExprType CurType => this.trace.Last().CurType; public Int32 CurOffset => this.trace.Select(_ => _.CurOffset).Sum(); public void Next() => this.trace.Last().Next(); public void Locate(ExprType type) => this.trace.Last().Locate(type); public void InBrace() { /// Push the current position into the stack, so that we can get back by <see cref="OutBrace"/> this.trace.Add(new Status(this.trace.Last().CurType)); // For aggregate types, go inside and locate the first member. if (!this.CurType.IsScalar) { this.trace.Last().indices.Add(0); } } public void OutBrace() => this.trace.RemoveAt(this.trace.Count - 1); public readonly List<Status> trace; } }
38.833013
747
0.46723
[ "MIT" ]
KirillAldashkin/C-Compiler
ABT/Declarations.cs
20,234
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ETO; using BSO; using DAO; using System.Data; namespace CMS.Client.Admin { public partial class editadmin : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { string aName = ""; if (Page.RouteData.Values["Id"] != null) aName = Page.RouteData.Values["Id"].ToString(); if (Page.RouteData.Values["dll"] != null) NavigationTitle(Page.RouteData.Values["dll"].ToString()); if (!IsPostBack) { initControl(aName); //ViewRoles(); } } #region NavigationTitle private void NavigationTitle(string url) { ModulesBSO modulesBSO = new ModulesBSO(); Modules modules = modulesBSO.GetModulesByUrl(url); imgIcon.ImageUrl = "~/Upload/Admin_Theme/Icons/" + modules.ModulesIcon; litModules.Text = modules.ModulesName; } #endregion #region initControl protected void initControl(string adminName) { if (adminName != "") { hddAdmin_Username.Value = adminName; btn_add.Visible = false; btn_edit.Visible = true; try { AdminBSO adminBSO = new AdminBSO(); ETO.Admin admin = adminBSO.GetAdminById(adminName); txtAdminName.Text = admin.AdminName; txtAdminName.Enabled = false; hddPass.Value = admin.AdminPass; txtFullName.Text = admin.AdminFullName; txtAdminEmail.Text = admin.AdminEmail; rdbList.SelectedValue = admin.AdminActive.ToString(); hdd_Created.Value = admin.AdminCreated.ToString(); hdd_log.Value = admin.AdminLog.ToString(); ViewPermission(); string sPermission = admin.AdminPermission; if (!sPermission.Equals("")) { string[] sSlip = sPermission.Split(new char[] { ',' }); foreach (string s in sSlip) { foreach (ListItem items in chklist.Items) { if (items.Value == s) items.Selected = true; } } } txtAddress.Text = admin.AdminAddress; txtBirth.SelectedDate = admin.AdminBirth; rdbSex.SelectedValue = admin.AdminSex.ToString(); txtNickYahoo.Text = admin.AdminNickYahoo; txtNickSkype.Text = admin.AdminNickSkype; txtPhone.Text = admin.AdminPhone; rdbLoginType.SelectedValue = admin.AdminLoginType.ToString(); rdbLoginType.Enabled = false; hddImageThumb.Value = admin.AdminAvatar; uploadPreview.Src = ResolveUrl("~/Upload/Avatar/") + admin.AdminAvatar; } catch (Exception ex) { error.Text = ex.Message.ToString(); } } else if (adminName == "") { hddAdmin_Username.Value = ""; hdd_Created.Value = DateTime.Now.ToString(); hdd_log.Value = DateTime.Now.ToString(); btn_add.Visible = true; btn_edit.Visible = false; ViewPermission(); } } #endregion #region ViewPermission public void ViewPermission() { PermissionBSO permissionBSO = new PermissionBSO(); DataTable table = permissionBSO.GetPermissionAll(); DataView dataView = new DataView(table); dataView.Sort = "PermissionID ASC"; DataTable dataTable = dataView.ToTable(); commonBSO commonBSO = new commonBSO(); commonBSO.FillToCheckBoxList(chklist, dataTable, "PermissionName", "Value"); } #endregion #region CheckedList public string CheckedList() { string strID = ""; foreach (ListItem items in chklist.Items) { if (items.Selected) strID += items.Value + ","; } return strID; } #endregion #region ReceiveHtml public ETO.Admin ReceiveHtml() { ConfigBSO configBSO = new ConfigBSO(); ETO.Config config = configBSO.GetAllConfig(Language.language); int icon_w = Convert.ToInt32(config.New_icon_w); int icon_h = Convert.ToInt32(config.New_icon_h); SecurityBSO securityBSO = new SecurityBSO(); ETO.Admin admin = new ETO.Admin(); string path = Request.PhysicalApplicationPath.Replace(@"\", "/") + "/Upload/Avatar/"; commonBSO commonBSO = new commonBSO(); string image_thumb = commonBSO.UploadImage(txtAvatar, path, icon_w, icon_h); admin.AdminLoginType = Convert.ToBoolean(rdbLoginType.SelectedItem.Value); //if (rdbLoginType.SelectedItem.Value.Equals("True")) //{ admin.AdminPass = (txtAdminPass.Text != "") ? securityBSO.EncPwd(txtAdminPass.Text.Trim()) : hddPass.Value; admin.AdminName = (txtAdminName.Text != "") ? txtAdminName.Text.Trim() : hddAdmin_Username.Value; admin.AdminEmail = (txtAdminEmail.Text != "") ? txtAdminEmail.Text.Trim() : ""; //} // admin.RolesID = (ddlRoles.SelectedValue != "") ? Convert.ToInt32(ddlRoles.SelectedValue) : 0; admin.RolesID = 1; admin.AdminActive = Convert.ToBoolean(rdbList.SelectedItem.Value); admin.AdminFullName = (txtFullName.Text != "") ? txtFullName.Text.Trim() : ""; admin.AdminCreated = Convert.ToDateTime(hdd_Created.Value); admin.AdminLog = Convert.ToDateTime(hdd_log.Value); //admin.AdminPermission = ""; admin.AdminPermission = (CheckedList() != "") ? CheckedList() : ""; admin.AdminAddress = (txtAddress.Text != "") ? txtAddress.Text.Trim() : ""; admin.AdminPhone = (txtPhone.Text != "") ? txtPhone.Text.Trim() : ""; admin.AdminNickYahoo = (txtNickYahoo.Text != "") ? txtNickYahoo.Text.Trim() : ""; admin.AdminNickSkype = (txtNickSkype.Text != "") ? txtNickSkype.Text.Trim() : ""; admin.AdminAvatar = (image_thumb != "") ? image_thumb : hddImageThumb.Value; admin.AdminSex = Convert.ToBoolean(rdbSex.SelectedItem.Value); admin.AdminBirth = txtBirth.SelectedDate.Value; return admin; } #endregion protected void btn_add_Click(object sender, EventArgs e) { ETO.Admin admin = ReceiveHtml(); try { AdminBSO adminBSO = new AdminBSO(); if (adminBSO.CheckExist(admin.AdminName)) { error.Text = String.Format(Resources.StringAdmin.CheckExist, admin.AdminName); } else if (adminBSO.CheckExistEmail(admin.AdminEmail)) { error.Text = "<font color = 'red'>Địa chỉ Email đã được đăng ký. Vui lòng đăng ký lại</font>"; } else { if (CheckedList().Equals("")) { error.Text = "Loi : Xin hay lua chon it nhat 1 quyen"; } else { adminBSO.CreateAdmin(admin); RolesBSO rolesBSO = new RolesBSO(); IRoles roles = rolesBSO.GetRolesByName("Guest"); AdminRolesBSO adminRolesBSO = new AdminRolesBSO(); AdminRoles adminRoles = new AdminRoles(); adminRoles.AdminUserName = admin.AdminName; adminRoles.RolesID = roles.RolesID; adminRoles.UserName = Session["Admin_UserName"].ToString(); adminRoles.Permission = ""; adminRoles.Created = DateTime.Now; adminRolesBSO.CreateAdminRoles(adminRoles); error.Text = String.Format(Resources.StringAdmin.AddNewsSuccessful); } } } catch (Exception ex) { error.Text = ex.Message.ToString(); } } protected void btn_edit_Click(object sender, EventArgs e) { ETO.Admin admin = ReceiveHtml(); try { if (CheckedList().Equals("")) { error.Text = "Loi : Xin hay lua chon it nhat 1 quyen"; } else { AdminBSO adminBSO = new AdminBSO(); adminBSO.UpdateAdmin(admin); error.Text = String.Format(Resources.StringAdmin.UpdateSuccessful, "quản trị", admin.AdminName); } } catch (Exception ex) { error.Text = ex.Message.ToString(); } } protected void rdbLoginType_SelectedIndexChanged(object sender, EventArgs e) { string value = rdbLoginType.SelectedValue; //if (value.Equals("True")) //{ // divCMS.Visible = true; // divDomain.Visible = false; //} //if (value.Equals("False")) //{ // divCMS.Visible = false; // divDomain.Visible = true; // BindToRadCombo(); //} } } }
35.965398
119
0.497883
[ "MIT" ]
khiem2/quanlyhocsinh
cms_form/Web_CMS/CMS/CMS/Client/Admin/editadmin.ascx.cs
10,420
C#
// License text here using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ZigBeeNet.DAO; using ZigBeeNet.ZCL.Protocol; using ZigBeeNet.ZCL.Field; using ZigBeeNet.ZCL.Clusters.Thermostat; namespace ZigBeeNet.ZCL.Clusters { /// <summary> /// Thermostatcluster implementation (Cluster ID 0x0201). /// /// Code is auto-generated. Modifications may be overwritten! /// </summary> public class ZclThermostatCluster : ZclCluster { /// <summary> /// The ZigBee Cluster Library Cluster ID /// </summary> public const ushort CLUSTER_ID = 0x0201; /// <summary> /// The ZigBee Cluster Library Cluster Name /// </summary> public const string CLUSTER_NAME = "Thermostat"; /* Attribute constants */ /// <summary> /// LocalTemperature represents the temperature in degrees Celsius, as measured locally. /// </summary> public const ushort ATTR_LOCALTEMPERATURE = 0x0000; /// <summary> /// OutdoorTemperature represents the temperature in degrees Celsius, as measured locally. /// </summary> public const ushort ATTR_OUTDOORTEMPERATURE = 0x0001; /// <summary> /// Occupancy specifies whether the heated/cooled space is occupied or not /// </summary> public const ushort ATTR_OCCUPANCY = 0x0002; /// <summary> /// The MinHeatSetpointLimit attribute specifies the absolute minimum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// </summary> public const ushort ATTR_ABSMINHEATSETPOINTLIMIT = 0x0003; /// <summary> /// The MaxHeatSetpointLimit attribute specifies the absolute maximum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// </summary> public const ushort ATTR_ABSMAXHEATSETPOINTLIMIT = 0x0004; /// <summary> /// The MinCoolSetpointLimit attribute specifies the absolute minimum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// </summary> public const ushort ATTR_ABSMINCOOLSETPOINTLIMIT = 0x0005; /// <summary> /// The MaxCoolSetpointLimit attribute specifies the absolute maximum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// </summary> public const ushort ATTR_ABSMAXCOOLSETPOINTLIMIT = 0x0006; /// <summary> /// The PICoolingDemandattribute is 8 bits in length and specifies the level of cooling demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “heating” mode. /// </summary> public const ushort ATTR_PICOOLINGDEMAND = 0x0007; /// <summary> /// The PIHeatingDemand attribute is 8 bits in length and specifies the level of heating demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “cooling” mode. /// </summary> public const ushort ATTR_PIHEATINGDEMAND = 0x0008; /// <summary> /// </summary> public const ushort ATTR_HVACSYSTEMTYPECONFIGURATION = 0x0009; /// <summary> /// </summary> public const ushort ATTR_LOCALTEMPERATURECALIBRATION = 0x0010; /// <summary> /// </summary> public const ushort ATTR_OCCUPIEDCOOLINGSETPOINT = 0x0011; /// <summary> /// </summary> public const ushort ATTR_OCCUPIEDHEATINGSETPOINT = 0x0012; /// <summary> /// </summary> public const ushort ATTR_UNOCCUPIEDCOOLINGSETPOINT = 0x0013; /// <summary> /// </summary> public const ushort ATTR_UNOCCUPIEDHEATINGSETPOINT = 0x0014; /// <summary> /// </summary> public const ushort ATTR_MINHEATSETPOINTLIMIT = 0x0015; /// <summary> /// </summary> public const ushort ATTR_MAXHEATSETPOINTLIMIT = 0x0016; /// <summary> /// </summary> public const ushort ATTR_MINCOOLSETPOINTLIMIT = 0x0017; /// <summary> /// </summary> public const ushort ATTR_MAXCOOLSETPOINTLIMIT = 0x0018; /// <summary> /// </summary> public const ushort ATTR_MINSETPOINTDEADBAND = 0x0019; /// <summary> /// </summary> public const ushort ATTR_REMOTESENSING = 0x001A; /// <summary> /// </summary> public const ushort ATTR_CONTROLSEQUENCEOFOPERATION = 0x001B; /// <summary> /// </summary> public const ushort ATTR_SYSTEMMODE = 0x001C; /// <summary> /// </summary> public const ushort ATTR_ALARMMASK = 0x001D; /// <summary> /// </summary> public const ushort ATTR_THERMOSTATRUNNINGMODE = 0x001E; /// <summary> /// This indicates the type of errors encountered within the Mini Split AC. Error values are reported with four bytes /// values. Each bit within the four bytes indicates the unique error. /// </summary> public const ushort ATTR_ACERRORCODE = 0x0044; // Attribute initialisation protected override Dictionary<ushort, ZclAttribute> InitializeAttributes() { Dictionary<ushort, ZclAttribute> attributeMap = new Dictionary<ushort, ZclAttribute>(26); ZclClusterType thermostat = ZclClusterType.GetValueById(ClusterType.THERMOSTAT); attributeMap.Add(ATTR_LOCALTEMPERATURE, new ZclAttribute(thermostat, ATTR_LOCALTEMPERATURE, "LocalTemperature", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), true, true, false, true)); attributeMap.Add(ATTR_OUTDOORTEMPERATURE, new ZclAttribute(thermostat, ATTR_OUTDOORTEMPERATURE, "OutdoorTemperature", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_OCCUPANCY, new ZclAttribute(thermostat, ATTR_OCCUPANCY, "Occupancy", ZclDataType.Get(DataType.BITMAP_8_BIT), false, true, false, false)); attributeMap.Add(ATTR_ABSMINHEATSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_ABSMINHEATSETPOINTLIMIT, "AbsMinHeatSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_ABSMAXHEATSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_ABSMAXHEATSETPOINTLIMIT, "AbsMaxHeatSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_ABSMINCOOLSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_ABSMINCOOLSETPOINTLIMIT, "AbsMinCoolSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_ABSMAXCOOLSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_ABSMAXCOOLSETPOINTLIMIT, "AbsMaxCoolSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_PICOOLINGDEMAND, new ZclAttribute(thermostat, ATTR_PICOOLINGDEMAND, "PICoolingDemand", ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER), false, true, false, true)); attributeMap.Add(ATTR_PIHEATINGDEMAND, new ZclAttribute(thermostat, ATTR_PIHEATINGDEMAND, "PIHeatingDemand", ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER), false, true, false, true)); attributeMap.Add(ATTR_HVACSYSTEMTYPECONFIGURATION, new ZclAttribute(thermostat, ATTR_HVACSYSTEMTYPECONFIGURATION, "HVACSystemTypeConfiguration", ZclDataType.Get(DataType.BITMAP_8_BIT), false, true, false, false)); attributeMap.Add(ATTR_LOCALTEMPERATURECALIBRATION, new ZclAttribute(thermostat, ATTR_LOCALTEMPERATURECALIBRATION, "LocalTemperatureCalibration", ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_OCCUPIEDCOOLINGSETPOINT, new ZclAttribute(thermostat, ATTR_OCCUPIEDCOOLINGSETPOINT, "OccupiedCoolingSetpoint", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), true, true, false, false)); attributeMap.Add(ATTR_OCCUPIEDHEATINGSETPOINT, new ZclAttribute(thermostat, ATTR_OCCUPIEDHEATINGSETPOINT, "OccupiedHeatingSetpoint", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), true, true, false, false)); attributeMap.Add(ATTR_UNOCCUPIEDCOOLINGSETPOINT, new ZclAttribute(thermostat, ATTR_UNOCCUPIEDCOOLINGSETPOINT, "UnoccupiedCoolingSetpoint", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_UNOCCUPIEDHEATINGSETPOINT, new ZclAttribute(thermostat, ATTR_UNOCCUPIEDHEATINGSETPOINT, "UnoccupiedHeatingSetpoint", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_MINHEATSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_MINHEATSETPOINTLIMIT, "MinHeatSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_MAXHEATSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_MAXHEATSETPOINTLIMIT, "MaxHeatSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_MINCOOLSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_MINCOOLSETPOINTLIMIT, "MinCoolSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_MAXCOOLSETPOINTLIMIT, new ZclAttribute(thermostat, ATTR_MAXCOOLSETPOINTLIMIT, "MaxCoolSetpointLimit", ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_MINSETPOINTDEADBAND, new ZclAttribute(thermostat, ATTR_MINSETPOINTDEADBAND, "MinSetpointDeadBand", ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER), false, true, false, false)); attributeMap.Add(ATTR_REMOTESENSING, new ZclAttribute(thermostat, ATTR_REMOTESENSING, "RemoteSensing", ZclDataType.Get(DataType.BITMAP_8_BIT), false, true, false, false)); attributeMap.Add(ATTR_CONTROLSEQUENCEOFOPERATION, new ZclAttribute(thermostat, ATTR_CONTROLSEQUENCEOFOPERATION, "ControlSequenceOfOperation", ZclDataType.Get(DataType.ENUMERATION_8_BIT), true, true, false, false)); attributeMap.Add(ATTR_SYSTEMMODE, new ZclAttribute(thermostat, ATTR_SYSTEMMODE, "SystemMode", ZclDataType.Get(DataType.ENUMERATION_8_BIT), true, true, false, false)); attributeMap.Add(ATTR_ALARMMASK, new ZclAttribute(thermostat, ATTR_ALARMMASK, "AlarmMask", ZclDataType.Get(DataType.ENUMERATION_8_BIT), false, true, false, false)); attributeMap.Add(ATTR_THERMOSTATRUNNINGMODE, new ZclAttribute(thermostat, ATTR_THERMOSTATRUNNINGMODE, "ThermostatRunningMode", ZclDataType.Get(DataType.ENUMERATION_8_BIT), false, true, false, false)); attributeMap.Add(ATTR_ACERRORCODE, new ZclAttribute(thermostat, ATTR_ACERRORCODE, "ACErrorCode", ZclDataType.Get(DataType.BITMAP_32_BIT), false, true, false, false)); return attributeMap; } /// <summary> /// Default constructor to create a Thermostat cluster. /// /// <param name ="zigbeeEndpoint">The ZigBeeEndpoint</param> /// </summary> public ZclThermostatCluster(ZigBeeEndpoint zigbeeEndpoint) : base(zigbeeEndpoint, CLUSTER_ID, CLUSTER_NAME) { } /// <summary> /// Get the LocalTemperature attribute [attribute ID0]. /// /// LocalTemperature represents the temperature in degrees Celsius, as measured locally. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetLocalTemperatureAsync() { return Read(_attributes[ATTR_LOCALTEMPERATURE]); } /// <summary> /// Synchronously Get the LocalTemperature attribute [attribute ID0]. /// /// LocalTemperature represents the temperature in degrees Celsius, as measured locally. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetLocalTemperature(long refreshPeriod) { if (_attributes[ATTR_LOCALTEMPERATURE].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_LOCALTEMPERATURE].LastValue; } return (ushort)ReadSync(_attributes[ATTR_LOCALTEMPERATURE]); } /// <summary> /// Set reporting for the LocalTemperature attribute [attribute ID0]. /// /// LocalTemperature represents the temperature in degrees Celsius, as measured locally. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <param name="minInterval">Minimum reporting period</param> /// <param name="maxInterval">Maximum reporting period</param> /// <param name="reportableChange">Object delta required to trigger report</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> SetLocalTemperatureReporting(ushort minInterval, ushort maxInterval, object reportableChange) { return SetReporting(_attributes[ATTR_LOCALTEMPERATURE], minInterval, maxInterval, reportableChange); } /// <summary> /// Get the OutdoorTemperature attribute [attribute ID1]. /// /// OutdoorTemperature represents the temperature in degrees Celsius, as measured locally. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetOutdoorTemperatureAsync() { return Read(_attributes[ATTR_OUTDOORTEMPERATURE]); } /// <summary> /// Synchronously Get the OutdoorTemperature attribute [attribute ID1]. /// /// OutdoorTemperature represents the temperature in degrees Celsius, as measured locally. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetOutdoorTemperature(long refreshPeriod) { if (_attributes[ATTR_OUTDOORTEMPERATURE].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_OUTDOORTEMPERATURE].LastValue; } return (ushort)ReadSync(_attributes[ATTR_OUTDOORTEMPERATURE]); } /// <summary> /// Get the Occupancy attribute [attribute ID2]. /// /// Occupancy specifies whether the heated/cooled space is occupied or not /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetOccupancyAsync() { return Read(_attributes[ATTR_OCCUPANCY]); } /// <summary> /// Synchronously Get the Occupancy attribute [attribute ID2]. /// /// Occupancy specifies whether the heated/cooled space is occupied or not /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetOccupancy(long refreshPeriod) { if (_attributes[ATTR_OCCUPANCY].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_OCCUPANCY].LastValue; } return (byte)ReadSync(_attributes[ATTR_OCCUPANCY]); } /// <summary> /// Get the AbsMinHeatSetpointLimit attribute [attribute ID3]. /// /// The MinHeatSetpointLimit attribute specifies the absolute minimum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetAbsMinHeatSetpointLimitAsync() { return Read(_attributes[ATTR_ABSMINHEATSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the AbsMinHeatSetpointLimit attribute [attribute ID3]. /// /// The MinHeatSetpointLimit attribute specifies the absolute minimum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetAbsMinHeatSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_ABSMINHEATSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_ABSMINHEATSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_ABSMINHEATSETPOINTLIMIT]); } /// <summary> /// Get the AbsMaxHeatSetpointLimit attribute [attribute ID4]. /// /// The MaxHeatSetpointLimit attribute specifies the absolute maximum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetAbsMaxHeatSetpointLimitAsync() { return Read(_attributes[ATTR_ABSMAXHEATSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the AbsMaxHeatSetpointLimit attribute [attribute ID4]. /// /// The MaxHeatSetpointLimit attribute specifies the absolute maximum level that the heating setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetAbsMaxHeatSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_ABSMAXHEATSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_ABSMAXHEATSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_ABSMAXHEATSETPOINTLIMIT]); } /// <summary> /// Get the AbsMinCoolSetpointLimit attribute [attribute ID5]. /// /// The MinCoolSetpointLimit attribute specifies the absolute minimum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetAbsMinCoolSetpointLimitAsync() { return Read(_attributes[ATTR_ABSMINCOOLSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the AbsMinCoolSetpointLimit attribute [attribute ID5]. /// /// The MinCoolSetpointLimit attribute specifies the absolute minimum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetAbsMinCoolSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_ABSMINCOOLSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_ABSMINCOOLSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_ABSMINCOOLSETPOINTLIMIT]); } /// <summary> /// Get the AbsMaxCoolSetpointLimit attribute [attribute ID6]. /// /// The MaxCoolSetpointLimit attribute specifies the absolute maximum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetAbsMaxCoolSetpointLimitAsync() { return Read(_attributes[ATTR_ABSMAXCOOLSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the AbsMaxCoolSetpointLimit attribute [attribute ID6]. /// /// The MaxCoolSetpointLimit attribute specifies the absolute maximum level that the cooling setpoint MAY be /// set to. This is a limitation imposed by the manufacturer. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetAbsMaxCoolSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_ABSMAXCOOLSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_ABSMAXCOOLSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_ABSMAXCOOLSETPOINTLIMIT]); } /// <summary> /// Get the PICoolingDemand attribute [attribute ID7]. /// /// The PICoolingDemandattribute is 8 bits in length and specifies the level of cooling demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “heating” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetPICoolingDemandAsync() { return Read(_attributes[ATTR_PICOOLINGDEMAND]); } /// <summary> /// Synchronously Get the PICoolingDemand attribute [attribute ID7]. /// /// The PICoolingDemandattribute is 8 bits in length and specifies the level of cooling demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “heating” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetPICoolingDemand(long refreshPeriod) { if (_attributes[ATTR_PICOOLINGDEMAND].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_PICOOLINGDEMAND].LastValue; } return (byte)ReadSync(_attributes[ATTR_PICOOLINGDEMAND]); } /// <summary> /// Set reporting for the PICoolingDemand attribute [attribute ID7]. /// /// The PICoolingDemandattribute is 8 bits in length and specifies the level of cooling demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “heating” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <param name="minInterval">Minimum reporting period</param> /// <param name="maxInterval">Maximum reporting period</param> /// <param name="reportableChange">Object delta required to trigger report</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> SetPICoolingDemandReporting(ushort minInterval, ushort maxInterval, object reportableChange) { return SetReporting(_attributes[ATTR_PICOOLINGDEMAND], minInterval, maxInterval, reportableChange); } /// <summary> /// Get the PIHeatingDemand attribute [attribute ID8]. /// /// The PIHeatingDemand attribute is 8 bits in length and specifies the level of heating demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “cooling” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetPIHeatingDemandAsync() { return Read(_attributes[ATTR_PIHEATINGDEMAND]); } /// <summary> /// Synchronously Get the PIHeatingDemand attribute [attribute ID8]. /// /// The PIHeatingDemand attribute is 8 bits in length and specifies the level of heating demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “cooling” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetPIHeatingDemand(long refreshPeriod) { if (_attributes[ATTR_PIHEATINGDEMAND].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_PIHEATINGDEMAND].LastValue; } return (byte)ReadSync(_attributes[ATTR_PIHEATINGDEMAND]); } /// <summary> /// Set reporting for the PIHeatingDemand attribute [attribute ID8]. /// /// The PIHeatingDemand attribute is 8 bits in length and specifies the level of heating demanded by the PI /// (proportional integral) control loop in use by the thermostat (if any), in percent. This value is 0 when the /// thermostat is in “off” or “cooling” mode. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <param name="minInterval">Minimum reporting period</param> /// <param name="maxInterval">Maximum reporting period</param> /// <param name="reportableChange">Object delta required to trigger report</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> SetPIHeatingDemandReporting(ushort minInterval, ushort maxInterval, object reportableChange) { return SetReporting(_attributes[ATTR_PIHEATINGDEMAND], minInterval, maxInterval, reportableChange); } /// <summary> /// Get the HVACSystemTypeConfiguration attribute [attribute ID9]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetHVACSystemTypeConfigurationAsync() { return Read(_attributes[ATTR_HVACSYSTEMTYPECONFIGURATION]); } /// <summary> /// Synchronously Get the HVACSystemTypeConfiguration attribute [attribute ID9]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetHVACSystemTypeConfiguration(long refreshPeriod) { if (_attributes[ATTR_HVACSYSTEMTYPECONFIGURATION].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_HVACSYSTEMTYPECONFIGURATION].LastValue; } return (byte)ReadSync(_attributes[ATTR_HVACSYSTEMTYPECONFIGURATION]); } /// <summary> /// Get the LocalTemperatureCalibration attribute [attribute ID16]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetLocalTemperatureCalibrationAsync() { return Read(_attributes[ATTR_LOCALTEMPERATURECALIBRATION]); } /// <summary> /// Synchronously Get the LocalTemperatureCalibration attribute [attribute ID16]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetLocalTemperatureCalibration(long refreshPeriod) { if (_attributes[ATTR_LOCALTEMPERATURECALIBRATION].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_LOCALTEMPERATURECALIBRATION].LastValue; } return (byte)ReadSync(_attributes[ATTR_LOCALTEMPERATURECALIBRATION]); } /// <summary> /// Get the OccupiedCoolingSetpoint attribute [attribute ID17]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetOccupiedCoolingSetpointAsync() { return Read(_attributes[ATTR_OCCUPIEDCOOLINGSETPOINT]); } /// <summary> /// Synchronously Get the OccupiedCoolingSetpoint attribute [attribute ID17]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetOccupiedCoolingSetpoint(long refreshPeriod) { if (_attributes[ATTR_OCCUPIEDCOOLINGSETPOINT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_OCCUPIEDCOOLINGSETPOINT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_OCCUPIEDCOOLINGSETPOINT]); } /// <summary> /// Get the OccupiedHeatingSetpoint attribute [attribute ID18]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetOccupiedHeatingSetpointAsync() { return Read(_attributes[ATTR_OCCUPIEDHEATINGSETPOINT]); } /// <summary> /// Synchronously Get the OccupiedHeatingSetpoint attribute [attribute ID18]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetOccupiedHeatingSetpoint(long refreshPeriod) { if (_attributes[ATTR_OCCUPIEDHEATINGSETPOINT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_OCCUPIEDHEATINGSETPOINT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_OCCUPIEDHEATINGSETPOINT]); } /// <summary> /// Get the UnoccupiedCoolingSetpoint attribute [attribute ID19]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetUnoccupiedCoolingSetpointAsync() { return Read(_attributes[ATTR_UNOCCUPIEDCOOLINGSETPOINT]); } /// <summary> /// Synchronously Get the UnoccupiedCoolingSetpoint attribute [attribute ID19]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetUnoccupiedCoolingSetpoint(long refreshPeriod) { if (_attributes[ATTR_UNOCCUPIEDCOOLINGSETPOINT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_UNOCCUPIEDCOOLINGSETPOINT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_UNOCCUPIEDCOOLINGSETPOINT]); } /// <summary> /// Get the UnoccupiedHeatingSetpoint attribute [attribute ID20]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetUnoccupiedHeatingSetpointAsync() { return Read(_attributes[ATTR_UNOCCUPIEDHEATINGSETPOINT]); } /// <summary> /// Synchronously Get the UnoccupiedHeatingSetpoint attribute [attribute ID20]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetUnoccupiedHeatingSetpoint(long refreshPeriod) { if (_attributes[ATTR_UNOCCUPIEDHEATINGSETPOINT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_UNOCCUPIEDHEATINGSETPOINT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_UNOCCUPIEDHEATINGSETPOINT]); } /// <summary> /// Get the MinHeatSetpointLimit attribute [attribute ID21]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetMinHeatSetpointLimitAsync() { return Read(_attributes[ATTR_MINHEATSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the MinHeatSetpointLimit attribute [attribute ID21]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetMinHeatSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_MINHEATSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_MINHEATSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_MINHEATSETPOINTLIMIT]); } /// <summary> /// Get the MaxHeatSetpointLimit attribute [attribute ID22]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetMaxHeatSetpointLimitAsync() { return Read(_attributes[ATTR_MAXHEATSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the MaxHeatSetpointLimit attribute [attribute ID22]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetMaxHeatSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_MAXHEATSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_MAXHEATSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_MAXHEATSETPOINTLIMIT]); } /// <summary> /// Get the MinCoolSetpointLimit attribute [attribute ID23]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetMinCoolSetpointLimitAsync() { return Read(_attributes[ATTR_MINCOOLSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the MinCoolSetpointLimit attribute [attribute ID23]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetMinCoolSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_MINCOOLSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_MINCOOLSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_MINCOOLSETPOINTLIMIT]); } /// <summary> /// Get the MaxCoolSetpointLimit attribute [attribute ID24]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetMaxCoolSetpointLimitAsync() { return Read(_attributes[ATTR_MAXCOOLSETPOINTLIMIT]); } /// <summary> /// Synchronously Get the MaxCoolSetpointLimit attribute [attribute ID24]. /// /// The attribute is of type ushort. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public ushort GetMaxCoolSetpointLimit(long refreshPeriod) { if (_attributes[ATTR_MAXCOOLSETPOINTLIMIT].IsLastValueCurrent(refreshPeriod)) { return (ushort)_attributes[ATTR_MAXCOOLSETPOINTLIMIT].LastValue; } return (ushort)ReadSync(_attributes[ATTR_MAXCOOLSETPOINTLIMIT]); } /// <summary> /// Get the MinSetpointDeadBand attribute [attribute ID25]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetMinSetpointDeadBandAsync() { return Read(_attributes[ATTR_MINSETPOINTDEADBAND]); } /// <summary> /// Synchronously Get the MinSetpointDeadBand attribute [attribute ID25]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetMinSetpointDeadBand(long refreshPeriod) { if (_attributes[ATTR_MINSETPOINTDEADBAND].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_MINSETPOINTDEADBAND].LastValue; } return (byte)ReadSync(_attributes[ATTR_MINSETPOINTDEADBAND]); } /// <summary> /// Get the RemoteSensing attribute [attribute ID26]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetRemoteSensingAsync() { return Read(_attributes[ATTR_REMOTESENSING]); } /// <summary> /// Synchronously Get the RemoteSensing attribute [attribute ID26]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetRemoteSensing(long refreshPeriod) { if (_attributes[ATTR_REMOTESENSING].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_REMOTESENSING].LastValue; } return (byte)ReadSync(_attributes[ATTR_REMOTESENSING]); } /// <summary> /// Get the ControlSequenceOfOperation attribute [attribute ID27]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetControlSequenceOfOperationAsync() { return Read(_attributes[ATTR_CONTROLSEQUENCEOFOPERATION]); } /// <summary> /// Synchronously Get the ControlSequenceOfOperation attribute [attribute ID27]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetControlSequenceOfOperation(long refreshPeriod) { if (_attributes[ATTR_CONTROLSEQUENCEOFOPERATION].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_CONTROLSEQUENCEOFOPERATION].LastValue; } return (byte)ReadSync(_attributes[ATTR_CONTROLSEQUENCEOFOPERATION]); } /// <summary> /// Get the SystemMode attribute [attribute ID28]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetSystemModeAsync() { return Read(_attributes[ATTR_SYSTEMMODE]); } /// <summary> /// Synchronously Get the SystemMode attribute [attribute ID28]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is MANDATORY /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetSystemMode(long refreshPeriod) { if (_attributes[ATTR_SYSTEMMODE].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_SYSTEMMODE].LastValue; } return (byte)ReadSync(_attributes[ATTR_SYSTEMMODE]); } /// <summary> /// Get the AlarmMask attribute [attribute ID29]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetAlarmMaskAsync() { return Read(_attributes[ATTR_ALARMMASK]); } /// <summary> /// Synchronously Get the AlarmMask attribute [attribute ID29]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetAlarmMask(long refreshPeriod) { if (_attributes[ATTR_ALARMMASK].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_ALARMMASK].LastValue; } return (byte)ReadSync(_attributes[ATTR_ALARMMASK]); } /// <summary> /// Get the ThermostatRunningMode attribute [attribute ID30]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetThermostatRunningModeAsync() { return Read(_attributes[ATTR_THERMOSTATRUNNINGMODE]); } /// <summary> /// Synchronously Get the ThermostatRunningMode attribute [attribute ID30]. /// /// The attribute is of type byte. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public byte GetThermostatRunningMode(long refreshPeriod) { if (_attributes[ATTR_THERMOSTATRUNNINGMODE].IsLastValueCurrent(refreshPeriod)) { return (byte)_attributes[ATTR_THERMOSTATRUNNINGMODE].LastValue; } return (byte)ReadSync(_attributes[ATTR_THERMOSTATRUNNINGMODE]); } /// <summary> /// Get the ACErrorCode attribute [attribute ID68]. /// /// This indicates the type of errors encountered within the Mini Split AC. Error values are reported with four bytes /// values. Each bit within the four bytes indicates the unique error. /// /// The attribute is of type int. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetACErrorCodeAsync() { return Read(_attributes[ATTR_ACERRORCODE]); } /// <summary> /// Synchronously Get the ACErrorCode attribute [attribute ID68]. /// /// This indicates the type of errors encountered within the Mini Split AC. Error values are reported with four bytes /// values. Each bit within the four bytes indicates the unique error. /// /// The attribute is of type int. /// /// The implementation of this attribute by a device is OPTIONAL /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public int GetACErrorCode(long refreshPeriod) { if (_attributes[ATTR_ACERRORCODE].IsLastValueCurrent(refreshPeriod)) { return (int)_attributes[ATTR_ACERRORCODE].LastValue; } return (int)ReadSync(_attributes[ATTR_ACERRORCODE]); } /// <summary> /// The Setpoint Raise/Lower Command /// /// <param name="mode"><see cref="byte"/> Mode</param> /// <param name="amount"><see cref="sbyte"/> Amount</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> SetpointRaiseLowerCommand(byte mode, sbyte amount) { SetpointRaiseLowerCommand command = new SetpointRaiseLowerCommand(); // Set the fields command.Mode = mode; command.Amount = amount; return Send(command); } /// <summary> /// The Set Weekly Schedule /// /// The set weekly schedule command is used to update the thermostat weekly set point schedule from a management system. /// If the thermostat already has a weekly set point schedule programmed then it SHOULD replace each daily set point set /// as it receives the updates from the management system. For example if the thermostat has 4 set points for every day of /// the week and is sent a Set Weekly Schedule command with one set point for Saturday then the thermostat SHOULD remove /// all 4 set points for Saturday and replace those with the updated set point but leave all other days unchanged. /// <br> /// If the schedule is larger than what fits in one ZigBee frame or contains more than 10 transitions, the schedule SHALL /// then be sent using multipleSet Weekly Schedule Commands. /// /// <param name="numberOfTransitions"><see cref="byte"/> Number of Transitions</param> /// <param name="dayOfWeek"><see cref="byte"/> Day of Week</param> /// <param name="mode"><see cref="byte"/> Mode</param> /// <param name="transition"><see cref="ushort"/> Transition</param> /// <param name="heatSet"><see cref="ushort"/> Heat Set</param> /// <param name="coolSet"><see cref="ushort"/> Cool Set</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> SetWeeklySchedule(byte numberOfTransitions, byte dayOfWeek, byte mode, ushort transition, ushort heatSet, ushort coolSet) { SetWeeklySchedule command = new SetWeeklySchedule(); // Set the fields command.NumberOfTransitions = numberOfTransitions; command.DayOfWeek = dayOfWeek; command.Mode = mode; command.Transition = transition; command.HeatSet = heatSet; command.CoolSet = coolSet; return Send(command); } /// <summary> /// The Get Weekly Schedule /// /// <param name="daysToReturn"><see cref="byte"/> Days To Return</param> /// <param name="modeToReturn"><see cref="byte"/> Mode To Return</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetWeeklySchedule(byte daysToReturn, byte modeToReturn) { GetWeeklySchedule command = new GetWeeklySchedule(); // Set the fields command.DaysToReturn = daysToReturn; command.ModeToReturn = modeToReturn; return Send(command); } /// <summary> /// The Clear Weekly Schedule /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> ClearWeeklySchedule() { ClearWeeklySchedule command = new ClearWeeklySchedule(); return Send(command); } /// <summary> /// The Get Relay Status Log /// /// The Get Relay Status Log command is used to query the thermostat internal relay status log. This command has no payload. /// <br> /// The log storing order is First in First Out (FIFO) when the log is generated and stored into the Queue. /// <br> /// The first record in the log (i.e., the oldest) one, is the first to be replaced when there is a new record and there is /// no more space in the log. Thus, the newest record will overwrite the oldest one if there is no space left. /// <br> /// The log storing order is Last In First Out (LIFO) when the log is being retrieved from the Queue by a client device. /// Once the "Get Relay Status Log Response" frame is sent by the Server, the "Unread Entries" attribute /// SHOULD be decremented to indicate the number of unread records that remain in the queue. /// <br> /// If the "Unread Entries"attribute reaches zero and the Client sends a new "Get Relay Status Log Request", the Server /// MAY send one of the following items as a response: /// <br> /// i) resend the last Get Relay Status Log Response /// or /// ii) generate new log record at the time of request and send Get Relay Status Log Response with the new data /// /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetRelayStatusLog() { GetRelayStatusLog command = new GetRelayStatusLog(); return Send(command); } /// <summary> /// The Get Weekly Schedule Response /// /// <param name="numberOfTransitions"><see cref="byte"/> Number of Transitions</param> /// <param name="dayOfWeek"><see cref="byte"/> Day of Week</param> /// <param name="mode"><see cref="byte"/> Mode</param> /// <param name="transition"><see cref="ushort"/> Transition</param> /// <param name="heatSet"><see cref="ushort"/> Heat Set</param> /// <param name="coolSet"><see cref="ushort"/> Cool Set</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetWeeklyScheduleResponse(byte numberOfTransitions, byte dayOfWeek, byte mode, ushort transition, ushort heatSet, ushort coolSet) { GetWeeklyScheduleResponse command = new GetWeeklyScheduleResponse(); // Set the fields command.NumberOfTransitions = numberOfTransitions; command.DayOfWeek = dayOfWeek; command.Mode = mode; command.Transition = transition; command.HeatSet = heatSet; command.CoolSet = coolSet; return Send(command); } /// <summary> /// The Get Relay Status Log Response /// /// <param name="timeOfDay"><see cref="ushort"/> Time of day</param> /// <param name="relayStatus"><see cref="byte"/> Relay Status</param> /// <param name="localTemperature"><see cref="ushort"/> Local Temperature</param> /// <param name="humidity"><see cref="byte"/> Humidity</param> /// <param name="setpoint"><see cref="ushort"/> Setpoint</param> /// <param name="unreadEntries"><see cref="ushort"/> Unread Entries</param> /// <returns>The Task<CommandResult> command result Task</returns> /// </summary> public Task<CommandResult> GetRelayStatusLogResponse(ushort timeOfDay, byte relayStatus, ushort localTemperature, byte humidity, ushort setpoint, ushort unreadEntries) { GetRelayStatusLogResponse command = new GetRelayStatusLogResponse(); // Set the fields command.TimeOfDay = timeOfDay; command.RelayStatus = relayStatus; command.LocalTemperature = localTemperature; command.Humidity = humidity; command.Setpoint = setpoint; command.UnreadEntries = unreadEntries; return Send(command); } public override ZclCommand GetCommandFromId(int commandId) { switch (commandId) { case 0: // SETPOINT_RAISE_LOWER_COMMAND return new SetpointRaiseLowerCommand(); case 1: // SET_WEEKLY_SCHEDULE return new SetWeeklySchedule(); case 2: // GET_WEEKLY_SCHEDULE return new GetWeeklySchedule(); case 3: // CLEAR_WEEKLY_SCHEDULE return new ClearWeeklySchedule(); case 4: // GET_RELAY_STATUS_LOG return new GetRelayStatusLog(); default: return null; } } public ZclCommand getResponseFromId(int commandId) { switch (commandId) { case 0: // GET_WEEKLY_SCHEDULE_RESPONSE return new GetWeeklyScheduleResponse(); case 1: // GET_RELAY_STATUS_LOG_RESPONSE return new GetRelayStatusLogResponse(); default: return null; } } } }
42.036827
235
0.624335
[ "EPL-1.0" ]
AutomationGarage/ZigbeeNet
libraries/ZigBeeNet/ZCL/Clusters/ZclThermostatCluster.cs
59,422
C#
using UnityEngine; public class GradientBackground : MonoBehaviour { public Color topColor; public Color bottomColor = Color.white; public int gradientLayer = 7; public Shader shader; public float time; private float H; private float S; private float V; private Mesh mesh; GameObject gradientPlane; void Awake() { H = Random.Range(0.5f, 1f); S = Random.Range(0.5f, 1f); V = Random.Range(0.5f, 1f); time = Random.Range(1f, 255f); topColor = Random.ColorHSV(); gradientLayer = Mathf.Clamp(gradientLayer, 0, 31); GetComponent<Camera>().clearFlags = CameraClearFlags.Depth; GetComponent<Camera>().cullingMask = GetComponent<Camera>().cullingMask & ~(1 << gradientLayer); Camera gradientCam = new GameObject("Gradient Cam", typeof(Camera)).GetComponent<Camera>(); gradientCam.depth = GetComponent<Camera>().depth - 1; gradientCam.cullingMask = 1 << gradientLayer; mesh = new Mesh(); mesh.vertices = new Vector3[4] {new Vector3(-100f, .577f, 1f), new Vector3(100f, .577f, 1f), new Vector3(-100f, -.577f, 1f), new Vector3(100f, -.577f, 1f)}; mesh.colors = new Color[4] { topColor, topColor, bottomColor, bottomColor }; mesh.triangles = new int[6] { 0, 1, 2, 1, 3, 2 }; Material mat = new Material(shader); gradientPlane = new GameObject("Gradient Plane", typeof(MeshFilter), typeof(MeshRenderer)); ((MeshFilter)gradientPlane.GetComponent(typeof(MeshFilter))).mesh = mesh; gradientPlane.GetComponent<MeshRenderer>().material = mat; gradientPlane.layer = gradientLayer; } private void Update() { time += Time.deltaTime; topColor = Color.HSVToRGB((time / 100f) % H, S, V); mesh.colors = new Color[4] { topColor, topColor, bottomColor, bottomColor }; ((MeshFilter)gradientPlane.GetComponent(typeof(MeshFilter))).mesh = mesh; } }
36.218182
133
0.63755
[ "MIT" ]
SaadAhmadSaddiqui/StackUp
Assets/N3K EN/Scripts/GradientBackground.cs
1,994
C#
using System; using System.Linq; using System.Text; using DBreeze; using DBreeze.DataTypes; using NBitcoin; using NBitcoin.BitcoinCore; using Xels.Bitcoin.Utilities; using Xunit; namespace Xels.Bitcoin.Tests.Utilities { /// <summary> /// Tests of DBreeze database and <see cref="DBreezeSerializer"/> class. /// </summary> public class DBreezeTest : TestBase { /// <summary>Provider of binary (de)serialization for data stored in the database.</summary> private readonly DBreezeSerializer dbreezeSerializer; /// <summary> /// Initializes the DBreeze serializer. /// </summary> public DBreezeTest() { this.dbreezeSerializer = new DBreezeSerializer(); } [Fact] public void SerializerWithBitcoinSerializableReturnsAsBytes() { Block block = new Block(); byte[] result = this.dbreezeSerializer.Serializer(block); Assert.Equal(block.ToBytes(), result); } [Fact] public void SerializerWithUint256ReturnsAsBytes() { uint256 val = new uint256(); byte[] result = this.dbreezeSerializer.Serializer(val); Assert.Equal(val.ToBytes(), result); } [Fact] public void SerializerWithUnsupportedObjectThrowsException() { Assert.Throws<NotSupportedException>(() => { string test = "Should throw exception."; this.dbreezeSerializer.Serializer(test); }); } [Fact] public void DeserializerWithCoinsDeserializesObject() { var network = Network.RegTest; var genesis = network.GetGenesis(); var coins = new Coins(genesis.Transactions[0], 0); var result = (Coins)this.dbreezeSerializer.Deserializer(coins.ToBytes(), typeof(Coins)); Assert.Equal(coins.CoinBase, result.CoinBase); Assert.Equal(coins.Height, result.Height); Assert.Equal(coins.IsEmpty, result.IsEmpty); Assert.Equal(coins.IsPruned, result.IsPruned); Assert.Equal(coins.Outputs.Count, result.Outputs.Count); Assert.Equal(coins.Outputs[0].ScriptPubKey.Hash, result.Outputs[0].ScriptPubKey.Hash); Assert.Equal(coins.Outputs[0].Value, result.Outputs[0].Value); Assert.Equal(coins.UnspentCount, result.UnspentCount); Assert.Equal(coins.Value, result.Value); Assert.Equal(coins.Version, result.Version); } [Fact] public void DeserializerWithBlockHeaderDeserializesObject() { var network = Network.RegTest; var genesis = network.GetGenesis(); var blockHeader = genesis.Header; var result = (BlockHeader)this.dbreezeSerializer.Deserializer(blockHeader.ToBytes(), typeof(BlockHeader)); Assert.Equal(blockHeader.GetHash(), result.GetHash()); } [Fact] public void DeserializerWithRewindDataDeserializesObject() { Network network = Network.RegTest; Block genesis = network.GetGenesis(); var rewindData = new RewindData(genesis.GetHash()); var result = (RewindData)this.dbreezeSerializer.Deserializer(rewindData.ToBytes(), typeof(RewindData)); Assert.Equal(genesis.GetHash(), result.PreviousBlockHash); } [Fact] public void DeserializerWithuint256DeserializesObject() { uint256 val = uint256.One; var result = (uint256)this.dbreezeSerializer.Deserializer(val.ToBytes(), typeof(uint256)); Assert.Equal(val, result); } [Fact] public void DeserializerWithBlockDeserializesObject() { Network network = Network.RegTest; Block block = network.GetGenesis(); var result = (Block)this.dbreezeSerializer.Deserializer(block.ToBytes(), typeof(Block)); Assert.Equal(block.GetHash(), result.GetHash()); } [Fact] public void DeserializerWithNotSupportedClassThrowsException() { Assert.Throws<NotSupportedException>(() => { string test = "Should throw exception."; this.dbreezeSerializer.Deserializer(Encoding.UTF8.GetBytes(test), typeof(string)); }); } [Fact] public void DBreezeEngineAbleToAccessExistingTransactionData() { var dir = CreateTestDir(this); uint256[] data = SetupTransactionData(dir); using (var engine = new DBreezeEngine(dir)) { using (DBreeze.Transactions.Transaction transaction = engine.GetTransaction()) { var data2 = new uint256[data.Length]; int i = 0; foreach (Row<int, byte[]> row in transaction.SelectForward<int, byte[]>("Table")) { data2[i++] = new uint256(row.Value, false); } Assert.True(data.SequenceEqual(data2)); } } } private static uint256[] SetupTransactionData(string folder) { using (var engine = new DBreezeEngine(folder)) { var data = new[] { new uint256(3), new uint256(2), new uint256(5), new uint256(10), }; int i = 0; using (DBreeze.Transactions.Transaction tx = engine.GetTransaction()) { foreach (uint256 d in data) tx.Insert<int, byte[]>("Table", i++, d.ToBytes(false)); tx.Commit(); } return data; } } } }
32.32973
118
0.562782
[ "MIT" ]
rahhh/FullNodeUI
XelsBitcoinFullNode/src/Xels.Bitcoin.Tests/Utilities/DBreezeTest.cs
5,983
C#
using RepoDb.Extensions; using RepoDb.Reflection; using System; using System.Collections.Generic; using System.Data.Common; using System.Threading; using System.Threading.Tasks; namespace RepoDb { /// <summary> /// A class that is used to extract the multiple resultsets of the 'ExecuteQueryMultiple' operation. /// </summary> public sealed class QueryMultipleExtractor : IDisposable { /* * TODO: The extraction within this class does not use the DbFieldCache.Get() operation, therefore, * we are not passing the values to the DataReader.ToEnumerable() method. */ private DbDataReader reader = null; /// <summary> /// Creates a new instance of <see cref="QueryMultipleExtractor"/> class. /// </summary> /// <param name="reader">The <see cref="DbDataReader"/> to be extracted.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> object to be used during the asynchronous operation.</param> internal QueryMultipleExtractor(DbDataReader reader, CancellationToken cancellationToken = default) { this.reader = reader; Position = 0; CancellationToken = cancellationToken; } /// <summary> /// Disposes the current instance of <see cref="QueryMultipleExtractor"/>. /// </summary> public void Dispose() => reader?.Dispose(); #region Properties /// <summary> /// Gets the position of the <see cref="DbDataReader"/>. /// </summary> public int Position { get; private set; } /// <summary> /// Gets the instance of the <see cref="CancellationToken"/> currently in used. /// </summary> public CancellationToken CancellationToken { get; private set; } #endregion #region Extract #region Extract<TEntity> /// <summary> /// Extract the <see cref="DbDataReader"/> object into an enumerable of data entity objects. /// </summary> /// <typeparam name="TEntity">The type of data entity to be extracted.</typeparam> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An enumerable of extracted data entity.</returns> public IEnumerable<TEntity> Extract<TEntity>(bool isMoveToNextResult = true) where TEntity : class { var result = DataReader.ToEnumerable<TEntity>(reader).AsList(); if (isMoveToNextResult) { NextResult(); } return result; } /// <summary> /// Extract the <see cref="DbDataReader"/> object into an enumerable of data entity objects in an asynchronous way. /// </summary> /// <typeparam name="TEntity">The type of data entity to be extracted.</typeparam> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An enumerable of extracted data entity.</returns> public async Task<IEnumerable<TEntity>> ExtractAsync<TEntity>(bool isMoveToNextResult = true) where TEntity : class { var result = (await DataReader.ToEnumerableAsync<TEntity>(reader, cancellationToken: CancellationToken)).AsList(); if (isMoveToNextResult) { await NextResultAsync(); } return result; } #endregion #region Extract<dynamic> /// <summary> /// Extract the <see cref="DbDataReader"/> object into an enumerable of dynamic objects. /// </summary> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An enumerable of extracted data entity.</returns> public IEnumerable<dynamic> Extract(bool isMoveToNextResult = true) { var result = DataReader.ToEnumerable(reader).AsList(); if (isMoveToNextResult) { NextResult(); } return result; } /// <summary> /// Extract the <see cref="DbDataReader"/> object into an enumerable of dynamic objects in an asynchronous way. /// </summary> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An enumerable of extracted data entity.</returns> public async Task<IEnumerable<dynamic>> ExtractAsync(bool isMoveToNextResult = true) { var result = (await DataReader.ToEnumerableAsync(reader, cancellationToken: CancellationToken)).AsList(); if (isMoveToNextResult) { await NextResultAsync(); } return result; } #endregion #endregion #region Scalar #region Scalar<TResult> /// <summary> /// Converts the first column of the first row of the <see cref="DbDataReader"/> to an object. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An instance of extracted object as value result.</returns> public TResult Scalar<TResult>(bool isMoveToNextResult = true) { var value = default(TResult); if (reader.Read()) { value = Converter.ToType<TResult>(reader[0]); } if (isMoveToNextResult) { NextResult(); } return value; } /// <summary> /// Converts the first column of the first row of the <see cref="DbDataReader"/> to an object in an asynchronous way. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An instance of extracted object as value result.</returns> public async Task<TResult> ScalarAsync<TResult>(bool isMoveToNextResult = true) { var value = default(TResult); if (await reader.ReadAsync(CancellationToken)) { value = Converter.ToType<TResult>(reader[0]); } if (isMoveToNextResult) { await NextResultAsync(); } return value; } #endregion #region Scalar<object> /// <summary> /// Converts the first column of the first row of the <see cref="DbDataReader"/> to an object. /// </summary> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An instance of extracted object as value result.</returns> public object Scalar(bool isMoveToNextResult = true) => Scalar<object>(isMoveToNextResult); /// <summary> /// Converts the first column of the first row of the <see cref="DbDataReader"/> to an object in an asynchronous way. /// </summary> /// <param name="isMoveToNextResult">A flag to use whether the operation would call the <see cref="System.Data.IDataReader.NextResult()"/> method.</param> /// <returns>An instance of extracted object as value result.</returns> public Task<object> ScalarAsync(bool isMoveToNextResult = true) => ScalarAsync<object>(isMoveToNextResult); #endregion #endregion #region NextResult /// <summary> /// Advances the <see cref="DbDataReader"/> object to the next result. /// <returns>True if there are more result sets; otherwise false.</returns> /// </summary> public bool NextResult() => (Position = reader.NextResult() ? Position + 1 : -1) >= 0; /// <summary> /// Advances the <see cref="DbDataReader"/> object to the next result in an asynchronous way. /// <returns>True if there are more result sets; otherwise false.</returns> /// </summary> public async Task<bool> NextResultAsync() => (Position = await reader.NextResultAsync(CancellationToken) ? Position + 1 : -1) >= 0; #endregion } }
40.616438
162
0.603485
[ "Apache-2.0" ]
wolfbomb/RepoDB
RepoDb.Core/RepoDb/QueryMultipleExtractor.cs
8,895
C#
using System.ComponentModel.DataAnnotations; using GrabNReadApp.Web.Constants.Blog; namespace GrabNReadApp.Web.Areas.Blog.Models.Articles { public class ArticleViewModel { [Required] [StringLength(ArticleConstants.TitleMaxLength, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = ArticleConstants.TitleMinLength)] public string Title { get; set; } [Required] [StringLength(ArticleConstants.ContentMaxLength, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = ArticleConstants.ContentMinLength)] public string Content { get; set; } } }
40.411765
187
0.714702
[ "MIT" ]
alexandrateneva/CSharp-Web-SoftUni
CSharp MVC Frameworks - ASP.NET Core/GrabNReadApp - Final Project/GrabNReadApp/GrabNReadApp.Web/Areas/Blog/Models/Articles/ArticleViewModel.cs
689
C#
using System; using dotNetty_kcp.thread; namespace base_kcp { public class MessageExecutorTest:ITask { private static IMessageExecutor _messageExecutor; public int i; public static long start = KcpUntils.currentMs(); private static int index = 0; public MessageExecutorTest(int i) { this.i = i; } public static int addIndex; public static void en() { int i = 0; while (true) { var queueTest = new MessageExecutorTest(i); if (_messageExecutor.execute(queueTest)) { i++; } } } public void execute() { long now = KcpUntils.currentMs(); if (now - start > 1000) { Console.WriteLine("i "+(i-index) +"time "+(now-start)); index = i; start = now; } } public static void test() { _messageExecutor = new DistuptorMessageExecutor(); _messageExecutor.start(); en(); } } }
21.690909
71
0.463537
[ "Apache-2.0" ]
l42111996/csharp-kcp
dotNetty-kcp/thread/MessageExecutorTest.cs
1,193
C#
using Pardis.Product.DAL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pardis.Product.DAL.Models { public interface IContent { int Id { get; set; } Content Content { get; set; } } public partial class Product : IContent { } public partial class Need : IContent { } public partial class SalesFolder : IContent { } public partial class CallForPrice : IContent { } }
24.9
52
0.692771
[ "Apache-2.0" ]
AmirCpu2/PardisCMS
Pardis.Product.DAL/Repasitory/Interfaces/IContentGeneric.cs
500
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Functional.Traversal { internal interface IAssignEmptyToOutputOperatorSubProcessor : IAssignOperatorSubProcessor { } }
30.444444
113
0.781022
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Functional/Traversal/4. Processing/Operators/Assign/ToOutput/IAssignEmptyToOutputOperatorSubProcessor.cs
276
C#
 using PSDocs.Data.Internal; using PSDocs.Runtime; using System.Management.Automation; namespace PSDocs.Commands { internal static class LanguageKeywords { public const string Definition = "Definition"; public const string Document = "Document"; public const string Block = "Block"; public const string Note = "Note"; public const string Warning = "Warning"; public const string Code = "Code"; public const string BlockQuote = "BlockQuote"; public const string Table = "Table"; public const string List = "List"; public const string Include = "Include"; public const string Section = "Section"; public const string Metadata = "Metadata"; public const string Title = "Title"; } internal static class LanguageCmdlets { public const string NewDefinition = "New-Definition"; public const string NewSection = "New-Section"; public const string InvokeBlock = "Invoke-Block"; public const string FormatCode = "Format-Code"; public const string FormatBlockQuote = "Format-BlockQuote"; public const string FormatNote = "Format-Note"; public const string FormatWarning = "Format-Warning"; public const string FormatTable = "Format-Table"; public const string FormatList = "Format-List"; public const string SetMetadata = "Set-Metadata"; public const string SetTitle = "Set-Title"; public const string AddInclude = "Add-Include"; } internal abstract class KeywordCmdlet : PSCmdlet { protected ScriptDocumentBuilder Builder { get { return RunspaceContext.CurrentThread.Builder; } } protected ScriptDocumentBuilder GetBuilder() { return RunspaceContext.CurrentThread.Builder; } protected PSObject GetTargetObject() { return RunspaceContext.CurrentThread.TargetObject; } protected static bool True(object o) { return o != null && TryBool(o, out bool bResult) && bResult; } protected static bool TryBool(object o, out bool value) { value = false; if (GetBaseObject(o) is bool result) { value = result; return true; } return false; } protected static bool TryString(object o, out string value) { value = null; if (GetBaseObject(o) is string result) { value = result; return true; } return false; } private static object GetBaseObject(object o) { return o is PSObject pso ? pso.BaseObject : o; } } }
31.21978
72
0.592397
[ "MIT" ]
cporteou/PSDocs
src/PSDocs/Commands/Keyword.cs
2,843
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.ExtensionPoints { public interface IUserControlActions { void SaveAction(int portalId, int tabId, int moduleId); void CancelAction(int portalId, int tabId, int moduleId); void BindAction(int portalId, int tabId, int moduleId); } }
30.875
71
0.724696
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/Library/ExtensionPoints/IUserControlActions.cs
496
C#
using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; namespace day24 { class Program { static void Main(string[] args) { var inputs = File.ReadAllLines("./input.txt").Skip(1); var boost = 34; var units = new List<Unit>(); var immuneCrew = true; foreach (var input in inputs) { if (string.IsNullOrWhiteSpace(input) || input.StartsWith("Infection")) { immuneCrew = false; } else { var unit = new Unit(input, immuneCrew); if (immuneCrew) unit.Damage += boost; units.Add(unit); } } var i = 1; while ( true ) { System.Console.WriteLine("Round " + i++); // if (i == 3) break; units.ForEach(u => { u.Defender = null; u.Attacker = null; }); var attackers = units.OrderByDescending(u => u.EffectivePower).ThenByDescending(u => u.Initiative); foreach (var item in attackers) { var enemy = units .Where(u => u.Type != item.Type && !u.Immunities.Contains(item.AttackType) && u.Attacker == null) .OrderByDescending(u => u.Weaknesses.Contains(item.AttackType) ? 1 : 0) .ThenByDescending(u => u.EffectivePower) .ThenByDescending(u => u.Initiative) .FirstOrDefault(); if (enemy != null) { item.Defender = enemy; enemy.Attacker = item; } System.Console.WriteLine(item); } attackers = units.OrderByDescending(u => u.Initiative); foreach (var item in attackers) { if (item.Defender != null) { var hp = item.EffectivePower; if (item.Defender.Weaknesses.Contains(item.AttackType)) hp *= 2; var unitsKilled = hp / item.Defender.HP; item.Defender.NumberOfUnits -= unitsKilled; } } units.RemoveAll(u => u.NumberOfUnits <= 0); if (units.All(u => u.Type == UnitType.IMMUNE) || units.All(u => u.Type == UnitType.INFECTION)) break; } if (units.All(u => u.Type == UnitType.IMMUNE)) { System.Console.WriteLine("Immune won with: " + units.Sum(u => u.NumberOfUnits)); } if (units.All(u => u.Type == UnitType.INFECTION)) { System.Console.WriteLine("Infection won with: " + units.Sum(u => u.NumberOfUnits)); } Console.WriteLine("Done"); } } public class Unit { public int HP { get; set; } public List<AttackType> Immunities {get; set; } public List<AttackType> Weaknesses { get; set; } public int Damage { get; set; } public AttackType AttackType { get; set; } public int NumberOfUnits { get; set; } public int Initiative { get; set; } public UnitType Type { get; set; } public Unit Defender { get; set; } public Unit Attacker { get; set; } public int EffectivePower { get { return NumberOfUnits * Damage; } } public override string ToString() { var result = $"Unit {Type} with {NumberOfUnits} units and initiative {Initiative} "; if (Defender == null) { result += "will attack no one"; } else { result += $"will attack unit {Defender.Type} with {Defender.NumberOfUnits} and initiative {Defender.Initiative}"; } return result; } public Unit(string input, bool isImmune) { Type = isImmune ? UnitType.IMMUNE : UnitType.INFECTION; var regex = new Regex(@"(\d+) units each with (\d+) hit points (\([^)]*\) )?with an attack that does (\d+) (\w+) damage at initiative (\d+)"); var groups = regex.Match(input).Groups; NumberOfUnits = int.Parse(groups[1].Value); HP = int.Parse(groups[2].Value); Damage = int.Parse(groups[4].Value); AttackType = (AttackType)Enum.Parse(typeof(AttackType), groups[5].Value.ToUpper()); Initiative = int.Parse(groups[6].Value); Immunities = new List<AttackType>(); Weaknesses = new List<AttackType>(); var modifiers = groups[3].Value.Replace("(", "").Replace(")", "").Trim(); if (!string.IsNullOrWhiteSpace(modifiers)) { var pieces = modifiers.Split("; "); var immunities = ""; var weaknesses = ""; if (pieces[0].StartsWith("immune to")) { immunities = pieces[0].Substring("immune to ".Length); if (pieces.Length > 1) { weaknesses = pieces[1].Substring("weak to".Length); } } else { weaknesses = pieces[0].Substring("weak to".Length); if (pieces.Length > 1) { immunities = pieces[1].Substring("immune to ".Length); } } foreach (var item in immunities.Split(", ")) { if (item != string.Empty) Immunities.Add((AttackType)Enum.Parse(typeof(AttackType), item.ToUpper())); } foreach (var item in weaknesses.Split(", ")) { if (item != string.Empty) Weaknesses.Add((AttackType)Enum.Parse(typeof(AttackType), item.ToUpper())); } } } } public enum AttackType { BLUDGEONING, FIRE, SLASHING, RADIATION, COLD } public enum UnitType { IMMUNE, INFECTION } }
39.0875
154
0.482091
[ "Apache-2.0" ]
kbaley/AdventOfCode-2018
day24/Program.cs
6,256
C#
/* Copyright 2009-2012 Matvei Stefarov <me@matvei.org> * * Based, in part, on SmartIrc4net code. Original license is reproduced below. * * * * SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net> * * Copyright (c) 2003-2005 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> * * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //Modified LegendCraft Team using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Threading; using fCraft.Events; using System.Collections.Concurrent; using JetBrains.Annotations; using System.Text; namespace fCraft { public static class GlobalChat { public sealed class GlobalThread : IDisposable { static TcpClient client; static StreamReader reader; static StreamWriter writer; static Thread thread; public static bool isConnected; public bool IsReady; bool reconnect; public bool ResponsibleForInputParsing; public string ActualBotNick; string desiredBotNick = ""; DateTime lastMessageSent; ConcurrentQueue<string> localQueue = new ConcurrentQueue<string>(); public static bool GCReady = false; public bool Start([NotNull] string botNick, bool parseInput) { ConfigKey.GlobalChat.TryGetBool(out isEnabled); if (!isEnabled) { return false; } if (botNick == null) throw new ArgumentNullException("botNick"); //shouldn't happen since Init is called before Start if (botNick.Length > 30) { Logger.Log(LogType.Error, "Server name exceeds 30 characters in length."); return false; } desiredBotNick = botNick; ResponsibleForInputParsing = parseInput; try { thread = new Thread(IoThread) { Name = "LegendCraft.GlobalChat", IsBackground = true }; thread.Start(); return true; } catch (Exception ex) { Logger.Log(LogType.Error, "GlobalChat: Could not start the bot: {0}", ex); return false; } } void Connect() { ConfigKey.GlobalChat.TryGetBool(out isEnabled); if (!isEnabled) { return; } // initialize the client IPAddress ipToBindTo = IPAddress.Parse(ConfigKey.IP.GetString()); IPEndPoint localEndPoint = new IPEndPoint(ipToBindTo, 0); client = new TcpClient(localEndPoint) { NoDelay = true, ReceiveTimeout = Timeout, SendTimeout = Timeout }; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); // connect client.Connect(hostName, port); // prepare to read/write reader = new StreamReader(client.GetStream()); writer = new StreamWriter(client.GetStream()); isConnected = true; GCReady = true; } public void Send([NotNull] string msg) { if (msg == null) throw new ArgumentNullException("msg"); localQueue.Enqueue(msg); } public static void SendChannelMessage([NotNull] string line) { if (line == null) throw new ArgumentNullException("line"); line = Color.MinecraftToIrcColors(line); if (channelNames == null || !GCReady) return; // in case IRC bot is disabled. for (int i = 0; i < channelNames.Length; i++) { SendRawMessage(IRCCommands.Privmsg(channelNames[i], line)); } } public static void SendRawMessage([NotNull] string line) { if (line == null) throw new ArgumentNullException("line"); OutputQueue.Enqueue(line); } // runs in its own thread, started from Connect() void IoThread() { string outputLine = ""; lastMessageSent = DateTime.UtcNow; do { try { ActualBotNick = desiredBotNick; reconnect = false; Logger.Log(LogType.SystemActivity, "Connecting to LegendCraft Global Chat as {2}", hostName, port, ActualBotNick); if (ActualBotNick == "Custom Minecraft Server (LegendCraft)") { Logger.Log(LogType.Error, "You must set a server name to connect to global chat."); reconnect = false; DisconnectThread(); } else { Connect(); } // register Send(IRCCommands.User(ActualBotNick, 8, ConfigKey.ServerName.GetString())); Send(IRCCommands.Nick(ActualBotNick)); while (isConnected && !reconnect) { Thread.Sleep(10); if (localQueue.Count > 0 && DateTime.UtcNow.Subtract(lastMessageSent).TotalMilliseconds >= SendDelay && localQueue.TryDequeue(out outputLine)) { writer.Write(outputLine + "\r\n"); lastMessageSent = DateTime.UtcNow; writer.Flush(); } if (OutputQueue.Count > 0 && DateTime.UtcNow.Subtract(lastMessageSent).TotalMilliseconds >= SendDelay && OutputQueue.TryDequeue(out outputLine)) { writer.Write(outputLine + "\r\n"); lastMessageSent = DateTime.UtcNow; writer.Flush(); } if (client.Client.Available > 0) { string line = reader.ReadLine(); if (line == null) break; HandleMessage(line); } } } catch (SocketException) { Logger.Log(LogType.Warning, "GlobalChat: Socket Error. Disconnected. Will retry in {0} seconds.", ReconnectDelay / 1000); reconnect = true; } catch (IOException) { Logger.Log(LogType.Warning, "GlobalChat: IO Error. Disconnected. Will retry in {0} seconds.", ReconnectDelay / 1000); reconnect = true; #if !DEBUG } catch (Exception ex) { Logger.Log(LogType.Error, "GlobalChat: {0}", ex); reconnect = true; #endif } if (reconnect) Thread.Sleep(ReconnectDelay); } while (reconnect); } public void SendMessage(string message) { HandleMessage("PRIVMSG " + message); } void HandleMessage([NotNull] string message) { if (message == null) throw new ArgumentNullException("message"); IRCMessage msg = IRC.MessageParser(message, ActualBotNick); var SendList = Server.Players.Where(p => !p.IsDeaf && !p.GlobalChatIgnore); #if DEBUG_IRC Logger.Log( LogType.IRC, "[{0}]: {1}", msg.Type, msg.RawMessage ); #endif switch (msg.Type) { case IRCMessageType.Login: foreach (string channel in channelNames) { Send(IRCCommands.Join(channel)); } IsReady = true; AssignBotForInputParsing(); // bot should be ready to receive input after joining return; case IRCMessageType.Ping: // ping-pong Send(IRCCommands.Pong(msg.RawMessageArray[1].Substring(1))); return; case IRCMessageType.ChannelAction: case IRCMessageType.ChannelMessage: // channel chat if (!ResponsibleForInputParsing) return; string processedMessage = msg.Message; if (msg.Type == IRCMessageType.ChannelAction) { if (processedMessage.StartsWith("\u0001ACTION")) { processedMessage = processedMessage.Substring(8); } else { return; } } processedMessage = IRC.NonPrintableChars.Replace(processedMessage, ""); if (processedMessage.Length > 0) { if (msg.Type == IRCMessageType.ChannelAction) { SendList.Message("&g[Global] * {1} {2}", ActualBotNick, msg.Nick, processedMessage); Logger.Log(LogType.GlobalChat,"[Global] * {1} {2}", ActualBotNick, msg.Nick, processedMessage); } else { SendList.Message("&g[Global] {1}: {2}", ActualBotNick, msg.Nick, processedMessage); Logger.Log(LogType.GlobalChat,"[Global] {1}: {2}", ActualBotNick, msg.Nick, processedMessage); } } else if (msg.Message.StartsWith("#")) { SendList.Message("&g[Global] {1}: {2}", ActualBotNick, msg.Nick, processedMessage.Substring(1)); Logger.Log(LogType.GlobalChat,"[Global] {1}: {2}", ActualBotNick, msg.Nick, processedMessage.Substring(1)); } return; case IRCMessageType.Join: if (!ResponsibleForInputParsing) return; if (msg.Nick.StartsWith("(")) { SendList.Message("&g[Global] Server {0} joined the LegendCraft Global Chat", msg.Nick); Logger.Log(LogType.GlobalChat,"[Global] Server {0} joined the LegendCraft Global Chat", msg.Nick); } else { SendList.Message("&g[Global] {0} joined the LegendCraft Global Chat", msg.Nick); Logger.Log(LogType.GlobalChat, "[Global] {0} joined the LegendCraft Global Chat", msg.Nick); } return; case IRCMessageType.Kick: string kicked = msg.RawMessageArray[3]; if (kicked == ActualBotNick) { Logger.Log(LogType.SystemActivity, "Bot was kicked from {0} by {1} ({2}), rejoining.", msg.Channel, msg.Nick, msg.Message); Thread.Sleep(ReconnectDelay); Send(IRCCommands.Join(msg.Channel)); } else { if (!ResponsibleForInputParsing) return; SendList.Message("&g[Global] {0} kicked {1} ({2})", msg.Nick, kicked, msg.Message); Logger.Log(LogType.GlobalChat, "[Global] {0} kicked {1} ({2})", msg.Nick, kicked, msg.Message); } return; case IRCMessageType.Part: case IRCMessageType.Quit: if (!ResponsibleForInputParsing) return; SendList.Message("&g[Global] Server {0} left the LegendCraft Global Chat", msg.Nick); Logger.Log(LogType.GlobalChat, "[Global] Server {0} left the LegendCraft Global Chat", msg.Nick); return; case IRCMessageType.NickChange: if (!ResponsibleForInputParsing) return; SendList.Message("&g[Global] {0} is now known as {1}", msg.Nick, msg.Message); Logger.Log(LogType.GlobalChat, "[Global] {0} is now known as {1}", msg.Nick, msg.Message); return; case IRCMessageType.ErrorMessage: case IRCMessageType.Error: bool die = false; switch (msg.ReplyCode) { case IRCReplyCode.ErrorNicknameInUse: case IRCReplyCode.ErrorNicknameCollision: ActualBotNick = ActualBotNick.Remove(ActualBotNick.Length - 4) + "_"; Logger.Log(LogType.SystemActivity, "Error: Global Chat Nickname is already in use. Trying \"{0}\"", ActualBotNick); Send(IRCCommands.Nick(ActualBotNick)); break; case IRCReplyCode.ErrorBannedFromChannel: case IRCReplyCode.ErrorNoSuchChannel: Logger.Log(LogType.SystemActivity, "Error: {0} ({1})", msg.ReplyCode, msg.Channel); GCReady = false; die = true; break; //wont happen case IRCReplyCode.ErrorBadChannelKey: Logger.Log(LogType.SystemActivity, "Error: Channel password required for {0}. LegendCraft does not currently support passworded channels.", msg.Channel); die = true; GCReady = false; break; default: Logger.Log(LogType.SystemActivity, "Error ({0}): {1}", msg.ReplyCode, msg.RawMessage); GCReady = false; break; } if (die) { Logger.Log(LogType.SystemActivity, "Error: Disconnecting from Global Chat."); reconnect = false; DisconnectThread(); } return; case IRCMessageType.QueryAction: // TODO: PMs Logger.Log(LogType.SystemActivity, "Query: {0}", msg.RawMessage); break; case IRCMessageType.Kill: Logger.Log(LogType.SystemActivity, "Bot was killed from {0} by {1} ({2}), reconnecting.", hostName, msg.Nick, msg.Message); reconnect = true; isConnected = false; return; } } public void DisconnectThread() { IsReady = false; AssignBotForInputParsing(); isConnected = false; GCReady = false; if (thread != null && thread.IsAlive) { thread.Join(1000); if (thread.IsAlive) { thread.Abort(); } } try { if (reader != null) reader.Close(); } catch (ObjectDisposedException) { } try { if (writer != null) writer.Close(); } catch (ObjectDisposedException) { } try { if (client != null) client.Close(); } catch (ObjectDisposedException) { } } #region IDisposable members public void Dispose() { try { if (reader != null) reader.Dispose(); } catch (ObjectDisposedException) { } try { if (reader != null) writer.Dispose(); } catch (ObjectDisposedException) { } try { if (client != null && client.Connected) { client.Close(); } } catch (ObjectDisposedException) { } } #endregion } public static GlobalThread[] threads; public static bool isEnabled; const int Timeout = 10000; // socket timeout (ms) internal static int SendDelay = 750; //default const int ReconnectDelay = 15000; static string hostName; static int port; static string[] channelNames; static string botNick; static readonly ConcurrentQueue<string> OutputQueue = new ConcurrentQueue<string>(); static void AssignBotForInputParsing() { bool needReassignment = false; for (int i = 0; i < threads.Length; i++) { if (threads[i].ResponsibleForInputParsing && !threads[i].IsReady) { threads[i].ResponsibleForInputParsing = false; needReassignment = true; } } if (needReassignment) { for (int i = 0; i < threads.Length; i++) { if (threads[i].IsReady) { threads[i].ResponsibleForInputParsing = true; Logger.Log(LogType.SystemActivity, "Bot \"{0}\" is now responsible for parsing input.", threads[i].ActualBotNick); return; } } Logger.Log(LogType.SystemActivity, "All Global Chat bots have disconnected."); } } // includes IRC color codes and non-printable ASCII public static readonly Regex NonPrintableChars = new Regex("\x03\\d{1,2}(,\\d{1,2})?|[\x00-\x1F\x7E-\xFF]", RegexOptions.Compiled); public static void Init() { hostName = "irc.dal.net"; port = 6667; channelNames = new[] { "#LegendCraft" }; for (int i = 0; i < channelNames.Length; i++) { channelNames[i] = channelNames[i].Trim(); if (!channelNames[i].StartsWith("#")) { channelNames[i] = '#' + channelNames[i].Trim(); } } //make sure irc nick will be under 30 string serverName = ConfigKey.ServerName.GetString(); if (serverName.Length > 28) { serverName = ConfigKey.ServerName.GetString().Substring(0, 28); } botNick = "[" + RemoveTroublesomeCharacters(serverName) + "]"; } public static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; for (int i = 0; i < inString.Length; i++) { ch = inString[i]; if ((ch <= 0x007A && ch >= 0x0061) || (ch <= 0x005A && ch >= 0x0041) || (ch <= 0x0039 && ch >= 0x0030) || ch == ']') { newString.Append(ch); } } return newString.ToString(); } public static bool Start() { ConfigKey.GlobalChat.TryGetBool(out isEnabled); if (!isEnabled) { return false; } int threadCount = 1; if (threadCount == 1) { GlobalThread thread = new GlobalThread(); if (thread.Start(botNick, true)) { threads = new[] { thread }; } } else { List<GlobalThread> threadTemp = new List<GlobalThread>(); for (int i = 0; i < threadCount; i++) { GlobalThread temp = new GlobalThread(); if (temp.Start(botNick + (i + 1), (threadTemp.Count == 0))) { threadTemp.Add(temp); } } threads = threadTemp.ToArray(); } if (threads.Length > 0) { //HookUpHandlers(); return true; } else { Logger.Log(LogType.SystemActivity, "GlobalChat functionality disabled."); return false; } } } }
38.205329
231
0.429169
[ "MIT" ]
CybertronicToon/LegendCraft
fCraft/Network/GlobalChat.cs
24,377
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstProject { public class ObjectCreator { public T CreateFromTypeUsingDefaultConstructor<T>(string typeName) where T : class, new() { T element = null; Type t = Type.GetType(typeName, false); if (t != null) { element = (T)Activator.CreateInstance(t); } return element; } } }
20.538462
97
0.573034
[ "MIT" ]
michalurbanski/CSharpTraining
FirstProject/FirstProject/PersonCreator.cs
536
C#
// See https://aka.ms/new-console-template for more information using; using System; namespace Foreach { class Program { static void Main (string[] args) { var numeros = new [] {1, 10, 100, 1000}; foreach (var item in numeros) { Console.WriteLine(item); } } } }
18.3
71
0.5
[ "MIT" ]
thiago1602/desenvolvimento-full-stack-c-sharp
fundamentos/foreach/Program.cs
368
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace DailyNotes.LoginFunction { public partial class Register { /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// txtUserName 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtUserName; /// <summary> /// RequiredFieldValidator1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; /// <summary> /// lnkbtnCheck 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.LinkButton lnkbtnCheck; /// <summary> /// txtPwd 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPwd; /// <summary> /// RequiredFieldValidator2 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2; /// <summary> /// txtRepwd 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtRepwd; /// <summary> /// RequiredFieldValidator3 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator3; /// <summary> /// CompareValidator1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.CompareValidator CompareValidator1; /// <summary> /// txtEmail 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtEmail; /// <summary> /// RequiredFieldValidator4 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator4; /// <summary> /// RegularExpressionValidator1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1; /// <summary> /// btnOk 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnOk; /// <summary> /// btnBack 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnBack; } }
29.528169
107
0.49845
[ "Apache-2.0" ]
Sky-shang/DailyNotes
DailyNotes/LoginFunction/Register.aspx.designer.cs
5,393
C#
using System; using HaloOnline.Server.Common; using Microsoft.Owin.Hosting; namespace HaloOnline.Server.App { public class AppSelfHost { private readonly IServerOptions _options; private IDisposable _app; public AppSelfHost(IServerOptions options) { _options = options; } public void Start() { if (_app == null) { var startOptions = new StartOptions(); startOptions.Urls.Add("http://+:" + _options.AppPort + "/"); try { _app = WebApp.Start(startOptions, app => { var startup = new Startup(_options); startup.Configuration(app); }); } catch (Exception e) { Console.WriteLine("Unable to start server." + "Do you have firewall enabled?" + "Try running as administrator."); Console.WriteLine(e.ToString()); } } } public void Stop() { if (_app != null) { _app.Dispose(); _app = null; } } } }
26.666667
76
0.418382
[ "MIT" ]
Atvaark/Emurado
HaloOnline.Server.App/AppSelfHost.cs
1,362
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace WebApp_OpenIDConnect_DotNet { public class Program { // Entry point for the application. public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
23.384615
64
0.587171
[ "MIT" ]
VitorX/active-directory-dotnet-webapp-openidconnect-aspnetcore
WebApp-OpenIDConnect-DotNet/Program.cs
610
C#
// <auto-generated /> namespace MomWorld.DataContexts.Migrations.ArticleMigrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.0-30225")] public sealed partial class _6th : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(_6th)); string IMigrationMetadata.Id { get { return "201504040929595_6th"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.366667
88
0.599295
[ "MIT" ]
shortgiraffe4/MomWorld
MomWorld/DataContexts/Migrations/ArticleMigrations/201504040929595_6th.Designer.cs
851
C#
using System; using System.Collections.Generic; namespace OrderTracker.Models { public class Order { //Properties public string Title{get;set;} public string Description{get;set;} public int Price{get;set;} public string Date{get;set;} public int Id {get;set;} public static List<Order> _instances = new List<Order>{}; //Constructor public Order(string title, string description, int price, string date) { Title = title; Description = description; Price = price; Date = date; _instances.Add(this); Id = _instances.Count; } public static List<Order> GetAll() { return _instances; } public static void ClearAll() { _instances.Clear(); } public static Order Find(int id) { return _instances[id-1]; } } }
19.674419
74
0.621749
[ "MIT" ]
MaxBrockbank/OrderTracker.Solution
OrderTracker/Models/Orders.cs
846
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Mvc; public interface IProxyActionResult { }
23.888889
71
0.786047
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/shared/Mvc.TestDiagnosticListener/IProxyActionResult.cs
215
C#
using Microsoft.AspNetCore.Routing; namespace MinimalHelpers.Routing; /// <summary> /// Defines a contract for a class that holds one or more route handlers that must be registered by the application. /// </summary> /// <seealso cref="IEndpointRouteBuilder" /> /// <seealso cref="IEndpointRouteBuilderExtensions" /> public interface IEndpointRouteHandler { /// <summary> /// Maps route endpoints to the corresponding handlers. /// </summary> /// <param name="endpoints">The <see cref="IEndpointRouteBuilder" /> to add routes to.</param> public void MapEndpoints(IEndpointRouteBuilder endpoints); }
34.5
116
0.731079
[ "MIT" ]
marcominerva/MinimalHelpers.Registration
src/MinimalHelpers.Routing/IEndpointRouteHandler.cs
623
C#
// <auto-generated> /* * Clash of Clans API * * Check out <a href=\"https://developer.clashofclans.com/#/getting-started\" target=\"_parent\">Getting Started</a> for instructions and links to other resources. Clash of Clans API uses <a href=\"https://jwt.io/\" target=\"_blank\">JSON Web Tokens</a> for authorizing the requests. Tokens are created by developers on <a href=\"https://developer.clashofclans.com/#/account\" target=\"_parent\">My Account</a> page and must be passed in every API request in Authorization HTTP header using Bearer authentication scheme. Correct Authorization header looks like this: \"Authorization: Bearer API_TOKEN\". * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; using System.Text.Json.Serialization; namespace CocApi.Rest.Models { /// <summary> /// Label /// </summary> public partial class Label : IEquatable<Label?> { /// <summary> /// Initializes a new instance of the <see cref="Label" /> class. /// </summary> /// <param name="iconUrls">iconUrls</param> /// <param name="id">id</param> /// <param name="name">name</param> [JsonConstructor] internal Label(IconUrls iconUrls, int id, string name) { #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' #pragma warning disable CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' if (name == null) throw new ArgumentNullException("name is a required property for Label and cannot be null."); if (id == null) throw new ArgumentNullException("id is a required property for Label and cannot be null."); if (iconUrls == null) throw new ArgumentNullException("iconUrls is a required property for Label and cannot be null."); #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' #pragma warning restore CS8073 // The result of the expression is always the same since a value of this type is never equal to 'null' IconUrls = iconUrls; Id = id; Name = name; } /// <summary> /// Gets or Sets IconUrls /// </summary> [JsonPropertyName("iconUrls")] public IconUrls IconUrls { get; } /// <summary> /// Gets or Sets Id /// </summary> [JsonPropertyName("id")] public int Id { get; } /// <summary> /// Gets or Sets Name /// </summary> [JsonPropertyName("name")] public string Name { get; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Label {\n"); sb.Append(" IconUrls: ").Append(IconUrls).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object? input) { return this.Equals(input as Label); } /// <summary> /// Returns true if Label instances are equal /// </summary> /// <param name="input">Instance of Label to be compared</param> /// <returns>Boolean</returns> public bool Equals(Label? input) { if (input == null) return false; return ( IconUrls == input.IconUrls || (IconUrls != null && IconUrls.Equals(input.IconUrls)) ) && ( Id == input.Id || (Id != null && Id.Equals(input.Id)) ) && ( Name == input.Name || (Name != null && Name.Equals(input.Name)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = (hashCode * 59) + IconUrls.GetHashCode(); hashCode = (hashCode * 59) + Id.GetHashCode(); hashCode = (hashCode * 59) + Name.GetHashCode(); return hashCode; } } } /// <summary> /// A Json converter for type Label /// </summary> public class LabelJsonConverter : JsonConverter<Label> { /// <summary> /// A Json reader. /// </summary> /// <param name="reader"></param> /// <param name="typeToConvert"></param> /// <param name="options"></param> /// <returns></returns> /// <exception cref="JsonException"></exception> public override Label Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { int currentDepth = reader.CurrentDepth; if (reader.TokenType != JsonTokenType.StartObject && reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); JsonTokenType startingTokenType = reader.TokenType; IconUrls iconUrls = default; int id = default; string name = default; while (reader.Read()) { if (startingTokenType == JsonTokenType.StartObject && reader.TokenType == JsonTokenType.EndObject && currentDepth == reader.CurrentDepth) break; if (startingTokenType == JsonTokenType.StartArray && reader.TokenType == JsonTokenType.EndArray && currentDepth == reader.CurrentDepth) break; if (reader.TokenType == JsonTokenType.PropertyName) { string? propertyName = reader.GetString(); reader.Read(); switch (propertyName) { case "iconUrls": Utf8JsonReader iconUrlsReader = reader; iconUrls = JsonSerializer.Deserialize<IconUrls>(ref reader, options); break; case "id": id = reader.GetInt32(); break; case "name": Utf8JsonReader nameReader = reader; name = JsonSerializer.Deserialize<string>(ref reader, options); break; } } } return new Label(iconUrls, id, name); } /// <summary> /// A Json writer /// </summary> /// <param name="writer"></param> /// <param name="label"></param> /// <param name="options"></param> /// <exception cref="NotImplementedException"></exception> public override void Write(Utf8JsonWriter writer, Label label, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WritePropertyName("iconUrls"); JsonSerializer.Serialize(writer, label.IconUrls, options); writer.WriteNumber("id", (int)label.Id); writer.WritePropertyName("name"); JsonSerializer.Serialize(writer, label.Name, options); writer.WriteEndObject(); } } }
36.668122
604
0.544242
[ "MIT" ]
realdevhl/CocApi
src/CocApi.Rest/Models/Label.cs
8,397
C#
using System; using System.Collections.Generic; using System.Threading; namespace OpenMetaverse.TestClient { public class ChangePermsCommand : Command { AutoResetEvent GotPermissionsEvent = new AutoResetEvent(false); Dictionary<UUID, Primitive> Objects = new Dictionary<UUID, Primitive>(); PermissionMask Perms = PermissionMask.None; private bool PermsSent; private int PermCount; public ChangePermsCommand(TestClient testClient) { testClient.Objects.ObjectProperties += new EventHandler<ObjectPropertiesEventArgs>(Objects_OnObjectProperties); Name = "changeperms"; Description = "Recursively changes all of the permissions for child and task inventory objects. Usage prim-uuid [copy] [mod] [xfer]"; Category = CommandCategory.Objects; } public override string Execute(string[] args, UUID fromAgentID) { UUID rootID; Primitive rootPrim; List<Primitive> childPrims; List<uint> localIDs = new List<uint>(); // Reset class-wide variables PermsSent = false; Objects.Clear(); Perms = PermissionMask.None; PermCount = 0; if (args.Length < 1 || args.Length > 4) return "Usage prim-uuid [copy] [mod] [xfer]"; if (!UUID.TryParse(args[0], out rootID)) return "Usage prim-uuid [copy] [mod] [xfer]"; for (int i = 1; i < args.Length; i++) { switch (args[i].ToLower()) { case "copy": Perms |= PermissionMask.Copy; break; case "mod": Perms |= PermissionMask.Modify; break; case "xfer": Perms |= PermissionMask.Transfer; break; default: return "Usage prim-uuid [copy] [mod] [xfer]"; } } Logger.DebugLog("Using PermissionMask: " + Perms.ToString(), Client); // Find the requested prim rootPrim = Client.Network.CurrentSim.ObjectsPrimitives.Find(delegate(Primitive prim) { return prim.ID == rootID; }); if (rootPrim == null) return "Cannot find requested prim " + rootID.ToString(); else Logger.DebugLog("Found requested prim " + rootPrim.ID.ToString(), Client); if (rootPrim.ParentID != 0) { // This is not actually a root prim, find the root if (!Client.Network.CurrentSim.ObjectsPrimitives.TryGetValue(rootPrim.ParentID, out rootPrim)) return "Cannot find root prim for requested object"; else Logger.DebugLog("Set root prim to " + rootPrim.ID.ToString(), Client); } // Find all of the child objects linked to this root childPrims = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(delegate(Primitive prim) { return prim.ParentID == rootPrim.LocalID; }); // Build a dictionary of primitives for referencing later Objects[rootPrim.ID] = rootPrim; for (int i = 0; i < childPrims.Count; i++) Objects[childPrims[i].ID] = childPrims[i]; // Build a list of all the localIDs to set permissions for localIDs.Add(rootPrim.LocalID); for (int i = 0; i < childPrims.Count; i++) localIDs.Add(childPrims[i].LocalID); // Go through each of the three main permissions and enable or disable them #region Set Linkset Permissions PermCount = 0; if ((Perms & PermissionMask.Modify) == PermissionMask.Modify) Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Modify, true); else Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Modify, false); PermsSent = true; if (!GotPermissionsEvent.WaitOne(1000 * 30, false)) return "Failed to set the modify bit, permissions in an unknown state"; PermCount = 0; if ((Perms & PermissionMask.Copy) == PermissionMask.Copy) Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Copy, true); else Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Copy, false); PermsSent = true; if (!GotPermissionsEvent.WaitOne(1000 * 30, false)) return "Failed to set the copy bit, permissions in an unknown state"; PermCount = 0; if ((Perms & PermissionMask.Transfer) == PermissionMask.Transfer) Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Transfer, true); else Client.Objects.SetPermissions(Client.Network.CurrentSim, localIDs, PermissionWho.NextOwner, PermissionMask.Transfer, false); PermsSent = true; if (!GotPermissionsEvent.WaitOne(1000 * 30, false)) return "Failed to set the transfer bit, permissions in an unknown state"; #endregion Set Linkset Permissions // Check each prim for task inventory and set permissions on the task inventory int taskItems = 0; foreach (Primitive prim in Objects.Values) { if ((prim.Flags & PrimFlags.InventoryEmpty) == 0) { List<InventoryBase> items = Client.Inventory.GetTaskInventory(prim.ID, prim.LocalID, 1000 * 30); if (items != null) { for (int i = 0; i < items.Count; i++) { if (!(items[i] is InventoryFolder)) { InventoryItem item = (InventoryItem)items[i]; item.Permissions.NextOwnerMask = Perms; Client.Inventory.UpdateTaskInventory(prim.LocalID, item); ++taskItems; } } } } } return "Set permissions to " + Perms.ToString() + " on " + localIDs.Count + " objects and " + taskItems + " inventory items"; } void Objects_OnObjectProperties(object sender, ObjectPropertiesEventArgs e) { if (PermsSent) { if (Objects.ContainsKey(e.Properties.ObjectID)) { // FIXME: Confirm the current operation against properties.Permissions.NextOwnerMask ++PermCount; if (PermCount >= Objects.Count) GotPermissionsEvent.Set(); } } } } }
43.707602
150
0.537597
[ "BSD-3-Clause" ]
BigManzai/libopenmetaverse
Programs/examples/TestClient/Commands/Prims/ChangePermsCommand.cs
7,474
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PathPlanner : MonoBehaviour { public UDPCommunication comm; bool enabled; // Use this for initialization void Start () { enabled = false; } // Update is called once per frame void Update () { } private void Enable() { enabled = true; } private void Disable() { enabled = false; } }
14.625
42
0.594017
[ "MIT" ]
autochair/hololens
Assets/Scripts/PathPlanner.cs
470
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CodeProject.RESTRepository.Data.Entities; namespace CodeProject.RESTRepository.Data.Repository { public interface _IRepository<T> where T : IEntity { void Add(T item); IEnumerable<T> GetAll(); T GetByID(int key); void Remove(int key); void Update(T item); } }
23.166667
54
0.685851
[ "MIT" ]
SharePointGuy1/CodeProjectRestRepository
CodeProject.RESTRepository.Data/Repository/_IRepository.cs
419
C#
using DND.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace DND.Web.DynamicForms { public class Startup : AppStartup { public Startup(ILoggerFactory loggerFactory, IConfiguration configuration, IHostingEnvironment hostingEnvironment) : base(loggerFactory, configuration, hostingEnvironment) { } public override void AddDatabases(IServiceCollection services, string defaultConnectionString) { } public override void ConfigureHttpClients(IServiceCollection services) { } } }
25.321429
122
0.722144
[ "MIT" ]
davidikin45/DigitalNomadDaveAspNetCore
src/DND.Web.DynamicForms/Startup.cs
711
C#
using ASP.NET_CORE_MongoDB.Contracts.Filters; using ASP.NET_CORE_MongoDB.Contracts.Paginated; using ASP.NET_CORE_MongoDB.Entities; using MongoDB.Driver; using MongoDB.Driver.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace ASP.NET_CORE_MongoDB.Repositories { public class BaseRepository<T> : IRepositoryBase<T> where T : BaseEntity { private const string DATABASE = "mongodb"; private readonly IMongoClient _mongoClient; private readonly IClientSessionHandle _clientSessionHandle; private readonly string _collection; public BaseRepository(IMongoClient mongoClient, IClientSessionHandle clientSessionHandle, string collection) { _mongoClient = mongoClient; _clientSessionHandle = clientSessionHandle; _collection = collection; if (!_mongoClient.GetDatabase(DATABASE).ListCollectionNames().ToList().Contains(collection)) _mongoClient.GetDatabase(DATABASE).CreateCollection(collection); } protected virtual IMongoCollection<T> Collection => _mongoClient.GetDatabase(DATABASE).GetCollection<T>(_collection); public IEnumerable<T> GetAll() => Collection.AsQueryable(_clientSessionHandle).ToList(); public async Task<IEnumerable<T>> GetAllAsync() => await Collection.AsQueryable(_clientSessionHandle).ToListAsync(); public T GetById(Guid id) { var filter = Builders<T>.Filter.Eq(x => x.Id, id); return Collection.Find(_clientSessionHandle, filter).FirstOrDefault(); } public async Task<T> GetByIdAsync(Guid id) => await Collection.Find(_clientSessionHandle, x => x.Id == id).FirstOrDefaultAsync(); public IEnumerable<TSelect> GetToExpression<TSelect>( Expression<Func<T, bool>> expression, Expression<Func<T, TSelect>> selector) { return Collection.AsQueryable(_clientSessionHandle) .Where(expression) .Select(selector) .ToList(); } public async Task<IEnumerable<TSelect>> GetToExpressionAsync<TSelect>( Expression<Func<T, bool>> expression, Expression<Func<T, TSelect>> selector) { return await Collection.AsQueryable(_clientSessionHandle) .Where(expression) .Select(selector) .ToListAsync(); } public PaginatedData<TSelect> GetPaginated<TSelect>( FilterBase filter, Expression<Func<T, bool>> expression, Expression<Func<T, TSelect>> selector) { var list = Collection.AsQueryable(_clientSessionHandle) .Where(expression) .Select(selector) .Skip((filter.CurrentPage - 1) * filter.PerPage) .Take(filter.PerPage) .ToList(); return new PaginatedData<TSelect>(filter.CurrentPage, list.Count, filter.PerPage, list); } public async Task<PaginatedData<TSelect>> GetPaginatedAsync<TSelect>( FilterBase filter, Expression<Func<T, bool>> expression, Expression<Func<T, TSelect>> selector) { var countDocuments = await Collection.CountDocumentsAsync(_clientSessionHandle, expression); var documents = await Collection.AsQueryable(_clientSessionHandle) .Where(expression) .Select(selector) .Skip((filter.CurrentPage - 1) * filter.PerPage) .Take(filter.PerPage) .ToListAsync(); return new PaginatedData<TSelect>(filter.CurrentPage, Convert.ToInt32(countDocuments), filter.PerPage, documents); } public bool Exist(Guid id) => Collection.CountDocuments(_clientSessionHandle, x => x.Id == id) > 0 ? true : false; public async Task<bool> ExistAsync(Guid id) => await Collection.CountDocumentsAsync(_clientSessionHandle, x => x.Id == id) > 0 ? true : false; public T Insert(T obj) { obj.InformCreated(); Collection.InsertOne(_clientSessionHandle, obj); return obj; } public async Task<T> InsertAsync(T obj) { obj.InformCreated(); await Collection.InsertOneAsync(_clientSessionHandle, obj); return obj; } public T Update(T obj) { obj.InformUpdated(); var filter = Builders<T>.Filter.Eq(x => x.Id, obj.Id); Collection.ReplaceOne(_clientSessionHandle, filter, obj); return obj; } public async Task<T> UpdateAsync(T obj) { obj.InformUpdated(); await Collection.ReplaceOneAsync(_clientSessionHandle, x => x.Id == obj.Id, obj); return obj; } public T InsertOrUpdate(T obj) => Exist(obj.Id) ? Update(obj) : Insert(obj); public async Task<T> InsertOrUpdateAsync(T obj) => await ExistAsync(obj.Id) ? await UpdateAsync(obj) : await InsertAsync(obj); public void Remove(Guid id) { Collection.DeleteOne(_clientSessionHandle, x => x.Id == id); } public async Task RemoveAsync(Guid id) { await Collection.DeleteOneAsync(_clientSessionHandle, x => x.Id == id); } public async Task RemoveLogicAsync(Guid id) { var obj = await GetByIdAsync(id); obj.InformRemoved(); await Collection.ReplaceOneAsync(_clientSessionHandle, x => x.Id == id, obj); } } }
40.152778
150
0.614839
[ "MIT" ]
dougglas1/ASP.NET_CORE_MongoDB
ASP.NET_CORE_MongoDB/Repositories/BaseRepository.cs
5,784
C#
/* * Copyright 2021 Swisscom Trust Services (Schweiz) AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace AIS.Model.Rest.SignResponse { public class Timestamp__1 { public string RFC3161TimeStampToken { get; set; } } }
33
75
0.729908
[ "Apache-2.0" ]
SwisscomTrustServices/itext-dotnet-ais
AisClient/AIS/Model/Rest/SignResponse/Timestamp__1.cs
761
C#
/* * Copyright 2019 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://floralicense.org/license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace MediaContent.Constants { /// <summary> /// MediaContentType enum. /// </summary> public enum MediaContentType { /// <summary> /// Refers to image type. /// </summary> IMAGE, /// <summary> /// Refers to video type. /// </summary> VIDEO, /// <summary> /// Refers to sound type. /// </summary> SOUND, /// <summary> /// Refers to music type. /// </summary> MUSIC, /// <summary> /// Refers to other type. /// </summary> OTHER } }
26.934783
75
0.589992
[ "Apache-2.0" ]
AchoWang/Tizen-CSharp-Samples
Mobile/MediaContent/src/MediaContent/MediaContent/Constants/MediaContentType.cs
1,241
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using OpenQA.Selenium; namespace WebAddressbookTests { [TestFixture] public class ContactCreationTests : AuthTestBase { [Test] public void ContactCreationTest() { ContactData contact = new ContactData("Alex","Nikitenko"); app.Navigation.GoToHomePage(); List<ContactData> oldContacts = app.Contacts.GetContactsList(); app.Contacts.Create(contact); Assert.AreEqual(oldContacts.Count + 1, app.Contacts.GetContactsCount()); List<ContactData> newContacts = app.Contacts.GetContactsList(); oldContacts.Add(contact); oldContacts.Sort(); newContacts.Sort(); Assert.AreEqual(oldContacts, newContacts); } } }
26.114286
84
0.646608
[ "Apache-2.0" ]
OlenaKh/Csharp_training
addressbook-web-tests/addressbook-web-tests/tests/ContactCreationTests.cs
916
C#
/* * Ory APIs * * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.15 * Contact: support@ory.sh * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Ory.Client.Client.OpenAPIDateConverter; namespace Ory.Client.Model { /// <summary> /// ClientRegistrationFlow /// </summary> [DataContract(Name = "registrationFlow")] public partial class ClientRegistrationFlow : IEquatable<ClientRegistrationFlow>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ClientRegistrationFlow" /> class. /// </summary> [JsonConstructorAttribute] protected ClientRegistrationFlow() { this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// Initializes a new instance of the <see cref="ClientRegistrationFlow" /> class. /// </summary> /// <param name="active">and so on..</param> /// <param name="expiresAt">ExpiresAt is the time (UTC) when the flow expires. If the user still wishes to log in, a new flow has to be initiated. (required).</param> /// <param name="id">id (required).</param> /// <param name="issuedAt">IssuedAt is the time (UTC) when the flow occurred. (required).</param> /// <param name="requestUrl">RequestURL is the initial URL that was requested from Ory Kratos. It can be used to forward information contained in the URL&#39;s path or query for example. (required).</param> /// <param name="type">The flow type can either be &#x60;api&#x60; or &#x60;browser&#x60;..</param> /// <param name="ui">ui (required).</param> public ClientRegistrationFlow(string active = default(string), DateTime expiresAt = default(DateTime), string id = default(string), DateTime issuedAt = default(DateTime), string requestUrl = default(string), string type = default(string), ClientUiContainer ui = default(ClientUiContainer)) { this.ExpiresAt = expiresAt; // to ensure "id" is required (not null) this.Id = id ?? throw new ArgumentNullException("id is a required property for ClientRegistrationFlow and cannot be null"); this.IssuedAt = issuedAt; // to ensure "requestUrl" is required (not null) this.RequestUrl = requestUrl ?? throw new ArgumentNullException("requestUrl is a required property for ClientRegistrationFlow and cannot be null"); // to ensure "ui" is required (not null) this.Ui = ui ?? throw new ArgumentNullException("ui is a required property for ClientRegistrationFlow and cannot be null"); this.Active = active; this.Type = type; this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// and so on. /// </summary> /// <value>and so on.</value> [DataMember(Name = "active", EmitDefaultValue = false)] public string Active { get; set; } /// <summary> /// ExpiresAt is the time (UTC) when the flow expires. If the user still wishes to log in, a new flow has to be initiated. /// </summary> /// <value>ExpiresAt is the time (UTC) when the flow expires. If the user still wishes to log in, a new flow has to be initiated.</value> [DataMember(Name = "expires_at", IsRequired = true, EmitDefaultValue = false)] public DateTime ExpiresAt { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name = "id", IsRequired = true, EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// IssuedAt is the time (UTC) when the flow occurred. /// </summary> /// <value>IssuedAt is the time (UTC) when the flow occurred.</value> [DataMember(Name = "issued_at", IsRequired = true, EmitDefaultValue = false)] public DateTime IssuedAt { get; set; } /// <summary> /// RequestURL is the initial URL that was requested from Ory Kratos. It can be used to forward information contained in the URL&#39;s path or query for example. /// </summary> /// <value>RequestURL is the initial URL that was requested from Ory Kratos. It can be used to forward information contained in the URL&#39;s path or query for example.</value> [DataMember(Name = "request_url", IsRequired = true, EmitDefaultValue = false)] public string RequestUrl { get; set; } /// <summary> /// The flow type can either be &#x60;api&#x60; or &#x60;browser&#x60;. /// </summary> /// <value>The flow type can either be &#x60;api&#x60; or &#x60;browser&#x60;.</value> [DataMember(Name = "type", EmitDefaultValue = false)] public string Type { get; set; } /// <summary> /// Gets or Sets Ui /// </summary> [DataMember(Name = "ui", IsRequired = true, EmitDefaultValue = false)] public ClientUiContainer Ui { get; set; } /// <summary> /// Gets or Sets additional properties /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalProperties { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ClientRegistrationFlow {\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" ExpiresAt: ").Append(ExpiresAt).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" IssuedAt: ").Append(IssuedAt).Append("\n"); sb.Append(" RequestUrl: ").Append(RequestUrl).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Ui: ").Append(Ui).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ClientRegistrationFlow); } /// <summary> /// Returns true if ClientRegistrationFlow instances are equal /// </summary> /// <param name="input">Instance of ClientRegistrationFlow to be compared</param> /// <returns>Boolean</returns> public bool Equals(ClientRegistrationFlow input) { if (input == null) return false; return ( this.Active == input.Active || (this.Active != null && this.Active.Equals(input.Active)) ) && ( this.ExpiresAt == input.ExpiresAt || (this.ExpiresAt != null && this.ExpiresAt.Equals(input.ExpiresAt)) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.IssuedAt == input.IssuedAt || (this.IssuedAt != null && this.IssuedAt.Equals(input.IssuedAt)) ) && ( this.RequestUrl == input.RequestUrl || (this.RequestUrl != null && this.RequestUrl.Equals(input.RequestUrl)) ) && ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && ( this.Ui == input.Ui || (this.Ui != null && this.Ui.Equals(input.Ui)) ) && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Active != null) hashCode = hashCode * 59 + this.Active.GetHashCode(); if (this.ExpiresAt != null) hashCode = hashCode * 59 + this.ExpiresAt.GetHashCode(); if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.IssuedAt != null) hashCode = hashCode * 59 + this.IssuedAt.GetHashCode(); if (this.RequestUrl != null) hashCode = hashCode * 59 + this.RequestUrl.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.Ui != null) hashCode = hashCode * 59 + this.Ui.GetHashCode(); if (this.AdditionalProperties != null) hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
44.104
297
0.57047
[ "Apache-2.0" ]
Stackwalkerllc/sdk
clients/client/dotnet/src/Ory.Client/Model/ClientRegistrationFlow.cs
11,026
C#
using Oracle.ManagedDataAccess.Client; using System; using System.Data.Common; namespace MilestoneTG.TransientFaultHandling.Data.Oracle { public class ReliableOracleConnection : ReliableDbConnection { //, RetryManager.Instance.GetDefaultOracleCommandRetryPolicy() ?? retryPolicy //GetDefaultOracleConnectionRetryPolicy /// <summary> /// Initializes a new instance of the <see cref="ReliableOracleConnection"/> class. /// </summary> /// <param name="connectionString">The connection string.</param> public ReliableOracleConnection(string connectionString) : this(connectionString, RetryManager.Instance.GetDefaultOracleConnectionRetryPolicy()) { } /// <summary> /// Initializes a new instance of the <see cref="ReliableOracleConnection"/> class. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="retryPolicy">The retry policy.</param> public ReliableOracleConnection(string connectionString, RetryPolicy retryPolicy) : this(connectionString, retryPolicy, RetryManager.Instance.GetDefaultOracleCommandRetryPolicy() ?? retryPolicy) { } /// <summary> /// Initializes a new instance of the <see cref="ReliableOracleConnection"/> class. /// </summary> /// <param name="connectionString">The connection string used to open the Oracle Database.</param> /// <param name="connectionRetryPolicy">The retry policy that defines whether to retry a request if a connection fails to be established.</param> /// <param name="commandRetryPolicy">The retry policy that defines whether to retry a request if a command fails to be executed.</param> public ReliableOracleConnection(string connectionString, RetryPolicy connectionRetryPolicy, RetryPolicy commandRetryPolicy) : base(connectionString, connectionRetryPolicy, commandRetryPolicy) { } /// <summary> /// Clones this instance. /// </summary> /// <returns>ReliableDbConnection.</returns> protected override ReliableDbConnection Clone() { return new ReliableOracleConnection(this.ConnectionString, this.ConnectionRetryPolicy, this.CommandRetryPolicy); } /// <summary> /// Creates the connection. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns>DbConnection.</returns> protected override DbConnection CreateConnection(string connectionString) { return new OracleConnection(connectionString); } /// <summary> /// Creates the connection string failover policy. /// </summary> /// <returns>RetryPolicy.</returns> protected override RetryPolicy CreateConnectionStringFailoverPolicy() { return new RetryPolicy<OracleDatabaseTransientErrorDetectionStrategy>(1, TimeSpan.FromMilliseconds(1)); } } }
43.605634
153
0.669574
[ "MIT" ]
milestonetg/transient-fault-handling
src/MilestoneTG.TransientFaultHandling.Data.Oracle/ReliableOracleConnection.cs
3,098
C#
using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading.Tasks; namespace Exodus.Core.Database.Communication { public abstract class Message<TConnection, TCommand, TParameters> where TConnection : IDbConnection where TCommand : IDbCommand where TParameters : IDataParameterCollection { protected string ConnectionString { get; } protected string Sql { get; set; } public Message(string connectionString) { ConnectionString = connectionString; } protected virtual void Validate() { if (string.IsNullOrEmpty(ConnectionString)) { throw new ArgumentException("Connection string is not defined.", nameof(ConnectionString)); } if (string.IsNullOrEmpty(Sql)) { throw new ArgumentException("SQL statement is not defined.", nameof(Sql)); } } protected abstract TConnection CreateConnection(); protected abstract TCommand CreateCommand(TConnection connection); protected abstract Task OpenConnection(TConnection connection); protected virtual void AddParameters(TParameters parameters) { } } }
30.55814
107
0.641553
[ "MIT" ]
ninjah187/Exodus
Exodus.Core/Database/Communication/Message.cs
1,316
C#
/* * Copyright 2006 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; using NUnit.Framework; using ZXing.Datamatrix.Encoder; namespace ZXing.Datamatrix.Test { /// <summary> /// Tests for {@link HighLevelEncoder}. /// </summary> [TestFixture] public sealed class HighLevelEncodeTestCase { private static readonly SymbolInfo[] TEST_SYMBOLS = { new SymbolInfo(false, 3, 5, 8, 8, 1), new SymbolInfo(false, 5, 7, 10, 10, 1), /*rect*/new SymbolInfo(true, 5, 7, 16, 6, 1), new SymbolInfo(false, 8, 10, 12, 12, 1), /*rect*/new SymbolInfo(true, 10, 11, 14, 6, 2), new SymbolInfo(false, 13, 0, 0, 0, 1), new SymbolInfo(false, 77, 0, 0, 0, 1) //The last entries are fake entries to test special conditions with C40 encoding }; private static void useTestSymbols() { SymbolInfo.overrideSymbolSet(TEST_SYMBOLS); } private static void resetSymbols() { SymbolInfo.overrideSymbolSet(SymbolInfo.PROD_SYMBOLS); } [Test] public void testASCIIEncodation() { String visualized = encodeHighLevel("123456"); Assert.AreEqual("142 164 186", visualized); visualized = encodeHighLevel("123456£"); Assert.AreEqual("142 164 186 235 36", visualized); visualized = encodeHighLevel("30Q324343430794<OQQ"); Assert.AreEqual("160 82 162 173 173 173 137 224 61 80 82 82", visualized); } [Test] public void testC40EncodationBasic1() { String visualized = encodeHighLevel("AIMAIMAIM"); Assert.AreEqual("230 91 11 91 11 91 11 254", visualized); //230 shifts to C40 encodation, 254 unlatches, "else" case } [Test] public void testC40EncodationBasic2() { String visualized = encodeHighLevel("AIMAIAB"); Assert.AreEqual("230 91 11 90 255 254 67 129", visualized); //"B" is normally encoded as "15" (one C40 value) //"else" case: "B" is encoded as ASCII visualized = encodeHighLevel("AIMAIAb"); Assert.AreEqual("66 74 78 66 74 66 99 129", visualized); //Encoded as ASCII //Alternative solution: //Assert.AreEqual("230 91 11 90 255 254 99 129", visualized); //"b" is normally encoded as "Shift 3, 2" (two C40 values) //"else" case: "b" is encoded as ASCII visualized = encodeHighLevel("AIMAIMAIMË"); Assert.AreEqual("230 91 11 91 11 91 11 254 235 76", visualized); //Alternative solution: //Assert.AreEqual("230 91 11 91 11 91 11 11 9 254", visualized); //Expl: 230 = shift to C40, "91 11" = "AIM", //"11 9" = "�" = "Shift 2, UpperShift, <char> //"else" case visualized = encodeHighLevel("AIMAIMAIMë"); Assert.AreEqual("230 91 11 91 11 91 11 254 235 108", visualized); //Activate when additional rectangulars are available //Expl: 230 = shift to C40, "91 11" = "AIM", //"�" in C40 encodes to: 1 30 2 11 which doesn't fit into a triplet //"10 243" = //254 = unlatch, 235 = Upper Shift, 108 = � = 0xEB/235 - 128 + 1 //"else" case } [Test] public void testC40EncodationSpecExample() { //Example in Figure 1 in the spec String visualized = encodeHighLevel("A1B2C3D4E5F6G7H8I9J0K1L2"); Assert.AreEqual("230 88 88 40 8 107 147 59 67 126 206 78 126 144 121 35 47 254", visualized); } [Test] public void testC40EncodationSpecialCases1() { //Special tests avoiding ultra-long test strings because these tests are only used //with the 16x48 symbol (47 data codewords) useTestSymbols(); String visualized = encodeHighLevel("AIMAIMAIMAIMAIMAIM"); Assert.AreEqual("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized); //case "a": Unlatch is not required visualized = encodeHighLevel("AIMAIMAIMAIMAIMAI"); Assert.AreEqual("230 91 11 91 11 91 11 91 11 91 11 90 241", visualized); //case "b": Add trailing shift 0 and Unlatch is not required visualized = encodeHighLevel("AIMAIMAIMAIMAIMA"); Assert.AreEqual("230 91 11 91 11 91 11 91 11 91 11 254 66", visualized); //case "c": Unlatch and write last character in ASCII resetSymbols(); visualized = encodeHighLevel("AIMAIMAIMAIMAIMAI"); Assert.AreEqual("230 91 11 91 11 91 11 91 11 91 11 254 66 74 129 237", visualized); visualized = encodeHighLevel("AIMAIMAIMA"); Assert.AreEqual("230 91 11 91 11 91 11 66", visualized); //case "d": Skip Unlatch and write last character in ASCII } [Test] public void testC40EncodationSpecialCases2() { String visualized = encodeHighLevel("AIMAIMAIMAIMAIMAIMAI"); Assert.AreEqual("230 91 11 91 11 91 11 91 11 91 11 91 11 254 66 74", visualized); //available > 2, rest = 2 --> unlatch and encode as ASCII } [Test] public void testTextEncodation() { String visualized = encodeHighLevel("aimaimaim"); Assert.AreEqual("239 91 11 91 11 91 11 254", visualized); //239 shifts to Text encodation, 254 unlatches visualized = encodeHighLevel("aimaimaim'"); Assert.AreEqual("239 91 11 91 11 91 11 254 40 129", visualized); //Assert.AreEqual("239 91 11 91 11 91 11 7 49 254", visualized); //This is an alternative, but doesn't strictly follow the rules in the spec. visualized = encodeHighLevel("aimaimaIm"); Assert.AreEqual("239 91 11 91 11 87 218 110", visualized); visualized = encodeHighLevel("aimaimaimB"); Assert.AreEqual("239 91 11 91 11 91 11 254 67 129", visualized); visualized = encodeHighLevel("aimaimaim{txt}\u0004"); Assert.AreEqual("239 91 11 91 11 91 11 16 218 236 107 181 69 254 129 237", visualized); } [Test] public void testX12Encodation() { //238 shifts to X12 encodation, 254 unlatches String visualized = encodeHighLevel("ABC>ABC123>AB"); Assert.AreEqual("238 89 233 14 192 100 207 44 31 67", visualized); visualized = encodeHighLevel("ABC>ABC123>ABC"); Assert.AreEqual("238 89 233 14 192 100 207 44 31 254 67 68", visualized); visualized = encodeHighLevel("ABC>ABC123>ABCD"); Assert.AreEqual("238 89 233 14 192 100 207 44 31 96 82 254", visualized); visualized = encodeHighLevel("ABC>ABC123>ABCDE"); Assert.AreEqual("238 89 233 14 192 100 207 44 31 96 82 70", visualized); visualized = encodeHighLevel("ABC>ABC123>ABCDEF"); Assert.AreEqual("238 89 233 14 192 100 207 44 31 96 82 254 70 71 129 237", visualized); visualized = encodeHighLevel("ABC>900>8123567"); Assert.AreEqual("238 89 233 14 141 25 93 254 142 165 197 129", visualized); } [Test] public void testEDIFACTEncodation() { //240 shifts to EDIFACT encodation String visualized = encodeHighLevel(".A.C1.3.DATA.123DATA.123DATA"); Assert.AreEqual("240 184 27 131 198 236 238 16 21 1 187 28 179 16 21 1 187 28 179 16 21 1", visualized); visualized = encodeHighLevel(".A.C1.3.X.X2.."); Assert.AreEqual("240 184 27 131 198 236 238 98 230 50 47 47", visualized); visualized = encodeHighLevel(".A.C1.3.X.X2."); Assert.AreEqual("240 184 27 131 198 236 238 98 230 50 47 129", visualized); visualized = encodeHighLevel(".A.C1.3.X.X2"); Assert.AreEqual("240 184 27 131 198 236 238 98 230 50", visualized); visualized = encodeHighLevel(".A.C1.3.X.X"); Assert.AreEqual("240 184 27 131 198 236 238 98 230 31", visualized); visualized = encodeHighLevel(".A.C1.3.X."); Assert.AreEqual("240 184 27 131 198 236 238 98 231 192", visualized); visualized = encodeHighLevel(".A.C1.3.X"); Assert.AreEqual("240 184 27 131 198 236 238 89", visualized); //Checking temporary unlatch from EDIFACT visualized = encodeHighLevel(".XXX.XXX.XXX.XXX.XXX.XXX.üXX.XXX.XXX.XXX.XXX.XXX.XXX"); Assert.AreEqual("240 185 134 24 185 134 24 185 134 24 185 134 24 185 134 24 185 134 24" + " 124 47 235 125 240" //<-- this is the temporary unlatch + " 97 139 152 97 139 152 97 139 152 97 139 152 97 139 152 97 139 152 89 89", visualized); } [Test] public void testBase256Encodation() { //231 shifts to Base256 encodation String visualized = encodeHighLevel("«äöüé»"); Assert.AreEqual("231 44 108 59 226 126 1 104", visualized); visualized = encodeHighLevel("«äöüéà»"); Assert.AreEqual("231 51 108 59 226 126 1 141 254 129", visualized); visualized = encodeHighLevel("«äöüéàá»"); Assert.AreEqual("231 44 108 59 226 126 1 141 36 147", visualized); visualized = encodeHighLevel(" 23£"); //ASCII only (for reference) Assert.AreEqual("33 153 235 36 129", visualized); visualized = encodeHighLevel("«äöüé» 234"); //Mixed Base256 + ASCII Assert.AreEqual("231 51 108 59 226 126 1 104 99 153 53 129", visualized); visualized = encodeHighLevel("«äöüé» 23£ 1234567890123456789"); Assert.AreEqual("231 55 108 59 226 126 1 104 99 10 161 167 185 142 164 186 208" + " 220 142 164 186 208 58 129 59 209 104 254 150 45", visualized); visualized = encodeHighLevel(createBinaryMessage(20)); Assert.AreEqual("231 44 108 59 226 126 1 141 36 5 37 187 80 230 123 17 166 60 210 103 253 150", visualized); visualized = encodeHighLevel(createBinaryMessage(19)); //padding necessary at the end Assert.AreEqual("231 63 108 59 226 126 1 141 36 5 37 187 80 230 123 17 166 60 210 103 1 129", visualized); visualized = encodeHighLevel(createBinaryMessage(276)); assertStartsWith("231 38 219 2 208 120 20 150 35", visualized); assertEndsWith("146 40 194 129", visualized); visualized = encodeHighLevel(createBinaryMessage(277)); assertStartsWith("231 38 220 2 208 120 20 150 35", visualized); assertEndsWith("146 40 190 87", visualized); } private static String createBinaryMessage(int len) { var sb = new StringBuilder(); sb.Append("«äöüéàá-"); for (int i = 0; i < len - 9; i++) { sb.Append('\u00B7'); } sb.Append('»'); return sb.ToString(); } private static void assertStartsWith(String expected, String actual) { if (!actual.StartsWith(expected)) { throw new AssertionException(actual); } } private static void assertEndsWith(String expected, String actual) { if (!actual.EndsWith(expected)) { throw new AssertionException(actual); } } [Test] public void testUnlatchingFromC40() { String visualized = encodeHighLevel("AIMAIMAIMAIMaimaimaim"); Assert.AreEqual("230 91 11 91 11 91 11 254 66 74 78 239 91 11 91 11 91 11", visualized); } [Test] public void testUnlatchingFromText() { String visualized = encodeHighLevel("aimaimaimaim12345678"); Assert.AreEqual("239 91 11 91 11 91 11 91 11 254 142 164 186 208 129 237", visualized); } [Test] public void testHelloWorld() { String visualized = encodeHighLevel("Hello World!"); Assert.AreEqual("73 239 116 130 175 123 148 64 158 233 254 34", visualized); } [Test] public void testBug1664266() { //There was an exception and the encoder did not handle the unlatching from //EDIFACT encoding correctly String visualized = encodeHighLevel("CREX-TAN:h"); Assert.AreEqual("240 13 33 88 181 64 78 124 59 105", visualized); visualized = encodeHighLevel("CREX-TAN:hh"); Assert.AreEqual("240 13 33 88 181 64 78 124 59 105 105 129", visualized); visualized = encodeHighLevel("CREX-TAN:hhh"); Assert.AreEqual("240 13 33 88 181 64 78 124 59 105 105 105", visualized); } [Test] public void testX12Unlatch() { String visualized = encodeHighLevel("*DTCP01"); Assert.AreEqual("238 9 10 104 141 254 50 129", visualized); } [Test] public void testX12Unlatch2() { String visualized = encodeHighLevel("*DTCP0"); Assert.AreEqual("238 9 10 104 141", visualized); } [Test] public void testBug3048549() { //There was an IllegalArgumentException for an illegal character here because //of an encoding problem of the character 0x0060 in Java source code. String visualized = encodeHighLevel("fiykmj*Rh2`,e6"); Assert.AreEqual("239 122 87 154 40 7 171 115 207 12 130 71 155 254 129 237", visualized); } [Test] public void testMacroCharacters() { String visualized = encodeHighLevel("[)>\u001E05\u001D5555\u001C6666\u001E\u0004"); //Assert.AreEqual("92 42 63 31 135 30 185 185 29 196 196 31 5 129 87 237", visualized); Assert.AreEqual("236 185 185 29 196 196 129 56", visualized); } [Test] public void testEncodingWithStartAsX12AndLatchToEDIFACTInTheMiddle() { String visualized = encodeHighLevel("*MEMANT-1F-MESTECH"); Assert.AreEqual("238 10 99 164 204 254 240 82 220 70 180 209 83 80 80 200", visualized); } [Ignore] [Test] public void testDataURL() { byte[] data = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x7E, 0x7F, (byte) 0x80, (byte) 0x81, (byte) 0x82}; String expected = encodeHighLevel(Encoding.GetEncoding("ISO8859-1").GetString(data, 0, data.Length)); String visualized = encodeHighLevel("url(data:text/plain;charset=iso-8859-1," + "%00%01%02%03%04%05%06%07%08%09%0A%7E%7F%80%81%82)"); Assert.AreEqual(expected, visualized); Assert.AreEqual("1 2 3 4 5 6 7 8 9 10 11 231 153 173 67 218 112 7", visualized); visualized = encodeHighLevel("url(data:;base64,flRlc3R+)"); Assert.AreEqual("127 85 102 116 117 127 129 56", visualized); } private static String encodeHighLevel(String msg) { String encoded = HighLevelEncoder.encodeHighLevel(msg); //DecodeHighLevel.decode(encoded); return visualize(encoded); } /// <summary> /// Convert a string of char codewords into a different string which lists each character /// using its decimal value. /// </summary> /// <param name="codewords">The codewords.</param> /// <returns>the visualized codewords</returns> internal static String visualize(String codewords) { var sb = new StringBuilder(); for (int i = 0; i < codewords.Length; i++) { if (i > 0) { sb.Append(' '); } sb.Append((int) codewords[i]); } return sb.ToString(); } } }
37.267898
128
0.608415
[ "Apache-2.0" ]
vjames13/ScannerTestV2
Source/test/src/datamatrix/encoder/HighLevelEncodeTestCase.cs
16,190
C#
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using UnityEditor; using System; namespace PixelCrushers.DialogueSystem { /// <summary> /// Custom inspector editor for DialogueSystemController (e.g., Dialogue Manager). /// </summary> [CustomEditor(typeof(DialogueSystemController), true)] public class DialogueSystemControllerEditor : Editor { private const string LightSkinIconFilename = "Dialogue System/DialogueManager Inspector Light.png"; private const string DarkSkinIconFilename = "Dialogue System/DialogueManager Inspector Dark.png"; private const string DefaultLightSkinIconFilepath = "Assets/Dialogue System/DLLs/DialogueManager Inspector Light.png"; private const string DefaultDarkSkinIconFilepath = "Assets/Dialogue System/DLLs/DialogueManager Inspector Dark.png"; private const string IconFilepathEditorPrefsKey = "PixelCrushers.DialogueSystem.IconFilename"; private const string InspectorEditorPrefsKey = "PixelCrushers.DialogueSystem.DialogueSystemControllerPrefs"; private static Texture2D icon = null; private static GUIStyle iconButtonStyle = null; private static GUIContent iconButtonContent = null; [Serializable] public class Foldouts { public bool displaySettingsFoldout = true; public bool localizationSettingsFoldout = false; public bool subtitleSettingsFoldout = false; public bool cameraSettingsFoldout = false; public bool inputSettingsFoldout = false; public bool barkSettingsFoldout = false; public bool alertSettingsFoldout = false; public bool persistentDataSettingsFoldout = false; public bool otherSettingsFoldout = false; } private Foldouts foldouts = null; private DialogueSystemController dialogueSystemController = null; private SerializedProperty displaySettingsProperty = null; private SerializedProperty persistentDataSettingsProperty = null; private bool createDatabase = false; public static Texture2D FindIcon() { var iconPath = EditorGUIUtility.isProSkin ? DarkSkinIconFilename : LightSkinIconFilename; return EditorGUIUtility.Load(iconPath) as Texture2D; } private void OnEnable() { dialogueSystemController = target as DialogueSystemController; displaySettingsProperty = serializedObject.FindProperty("displaySettings"); persistentDataSettingsProperty = serializedObject.FindProperty("persistentDataSettings"); foldouts = EditorPrefs.HasKey(InspectorEditorPrefsKey) ? JsonUtility.FromJson<Foldouts>(EditorPrefs.GetString(InspectorEditorPrefsKey)) : new Foldouts(); if (foldouts == null) foldouts = new Foldouts(); } private void OnDisable() { EditorPrefs.SetString(InspectorEditorPrefsKey, JsonUtility.ToJson(foldouts)); } /// <summary> /// Draws the inspector GUI. Adds a Dialogue System banner. /// </summary> public override void OnInspectorGUI() { createDatabase = false; DrawExtraFeatures(); var originalDialogueUI = GetCurrentDialogueUI(); serializedObject.Update(); DrawDatabaseField(); DrawDisplaySettings(); DrawPersistentDataSettings(); DrawOtherSettings(); serializedObject.ApplyModifiedProperties(); var newDialogueUI = GetCurrentDialogueUI(); if (newDialogueUI != originalDialogueUI) CheckDialogueUI(newDialogueUI); if (createDatabase) CreateInitialDatabase(); } private GameObject GetCurrentDialogueUI() { if (dialogueSystemController == null || dialogueSystemController.displaySettings == null) return null; return dialogueSystemController.displaySettings.dialogueUI; } private void CheckDialogueUI(GameObject newDialogueUIObject) { if (dialogueSystemController.displaySettings.dialogueUI == null) return; var newUIs = dialogueSystemController.displaySettings.dialogueUI.GetComponentsInChildren<CanvasDialogueUI>(true); if (newUIs.Length > 0) { DialogueManagerWizard.HandleCanvasDialogueUI(newUIs[0], DialogueManager.instance); } } private void DrawExtraFeatures() { if (icon == null) icon = FindIcon(); if (dialogueSystemController == null || icon == null) return; if (iconButtonStyle == null) { iconButtonStyle = new GUIStyle(EditorStyles.label); iconButtonStyle.normal.background = icon; iconButtonStyle.active.background = icon; } if (iconButtonContent == null) { iconButtonContent = new GUIContent(string.Empty, "Click to open Dialogue Editor."); } GUILayout.BeginHorizontal(); if (GUILayout.Button(iconButtonContent, iconButtonStyle, GUILayout.Width(icon.width), GUILayout.Height(icon.height))) { Selection.activeObject = dialogueSystemController.initialDatabase; PixelCrushers.DialogueSystem.DialogueEditor.DialogueEditorWindow.OpenDialogueEditorWindow(); } GUILayout.FlexibleSpace(); if (GUILayout.Button("Wizard...", GUILayout.Width(64))) { DialogueManagerWizard.Init(); } GUILayout.EndHorizontal(); EditorWindowTools.DrawHorizontalLine(); } private void DrawDatabaseField() { EditorGUILayout.BeginHorizontal(); var initialDatabaseProperty = serializedObject.FindProperty("initialDatabase"); EditorGUILayout.PropertyField(initialDatabaseProperty, true); if (initialDatabaseProperty.objectReferenceValue == null) { if (GUILayout.Button("Create", EditorStyles.miniButton, GUILayout.Width(50))) { createDatabase = true; // Must delay until after drawing GUI to not interrupt GUI layout. } } else { if (GUILayout.Button("Edit", EditorStyles.miniButton, GUILayout.Width(36))) { Selection.activeObject = dialogueSystemController.initialDatabase; PixelCrushers.DialogueSystem.DialogueEditor.DialogueEditorWindow.OpenDialogueEditorWindow(); } } EditorGUILayout.EndHorizontal(); } private void CreateInitialDatabase() { var path = EditorUtility.SaveFilePanelInProject("Create Dialogue Database", "Dialogue Database", "asset", "Save dialogue database asset as", "Assets"); if (string.IsNullOrEmpty(path)) return; var database = DialogueSystemMenuItems.CreateDialogueDatabaseInstance(); serializedObject.Update(); serializedObject.FindProperty("initialDatabase").objectReferenceValue = database; serializedObject.ApplyModifiedProperties(); if (AssetDatabase.LoadAssetAtPath<DialogueDatabase>(path)) AssetDatabase.DeleteAsset(path); AssetDatabase.CreateAsset(database, path); AssetDatabase.SaveAssets(); Selection.activeObject = database; PixelCrushers.DialogueSystem.DialogueEditor.DialogueEditorWindow.OpenDialogueEditorWindow(); } private void DrawDisplaySettings() { foldouts.displaySettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Display Settings", "Settings related to display and input.", foldouts.displaySettingsFoldout); if (foldouts.displaySettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); EditorGUILayout.PropertyField(displaySettingsProperty.FindPropertyRelative("dialogueUI"), true); EditorGUILayout.PropertyField(displaySettingsProperty.FindPropertyRelative("defaultCanvas"), true); DrawLocalizationSettings(); DrawSubtitleSettings(); DrawCameraSettings(); DrawInputSettings(); DrawBarkSettings(); DrawAlertSettings(); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawLocalizationSettings() { foldouts.localizationSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Localization Settings", "Language localization settings.", foldouts.localizationSettingsFoldout, false); if (foldouts.localizationSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var localizationSettings = displaySettingsProperty.FindPropertyRelative("localizationSettings"); EditorGUILayout.PropertyField(localizationSettings.FindPropertyRelative("language"), true); EditorGUILayout.PropertyField(localizationSettings.FindPropertyRelative("useSystemLanguage"), true); EditorGUILayout.PropertyField(localizationSettings.FindPropertyRelative("textTable"), true); if (GUILayout.Button(new GUIContent("Reset Language PlayerPrefs", "Delete the language selection saved in PlayerPrefs."))) { ResetLanguagePlayerPrefs(); } } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void ResetLanguagePlayerPrefs() { var uiLocalizationManager = dialogueSystemController.GetComponent<UILocalizationManager>(); if (uiLocalizationManager != null) { PlayerPrefs.DeleteKey(uiLocalizationManager.currentLanguagePlayerPrefsKey); } else { PlayerPrefs.DeleteKey("Language"); } } private void DrawSubtitleSettings() { foldouts.subtitleSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Subtitle Settings", "Subtitle settings.", foldouts.subtitleSettingsFoldout, false); if (foldouts.subtitleSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var subtitleSettings = displaySettingsProperty.FindPropertyRelative("subtitleSettings"); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("richTextEmphases"), new GUIContent("Use Rich Text For [em#] Tags", "Use rich text codes for [em#] markup tags. If unticked, [em#] tag will apply color to entire text."), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("showNPCSubtitlesDuringLine"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("showNPCSubtitlesWithResponses"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("showPCSubtitlesDuringLine"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("allowPCSubtitleReminders"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("skipPCSubtitleAfterResponseMenu"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("subtitleCharsPerSecond"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("minSubtitleSeconds"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("continueButton"), true); EditorGUILayout.PropertyField(subtitleSettings.FindPropertyRelative("informSequenceStartAndEnd"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawCameraSettings() { foldouts.cameraSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Camera & Cutscene Settings", "Camera and cutscene sequencer settings.", foldouts.cameraSettingsFoldout, false); if (foldouts.cameraSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var cameraSettings = displaySettingsProperty.FindPropertyRelative("cameraSettings"); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("sequencerCamera"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("alternateCameraObject"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("cameraAngles"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("defaultSequence"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("defaultPlayerSequence"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("defaultResponseMenuSequence"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("entrytagFormat"), true); EditorGUILayout.PropertyField(cameraSettings.FindPropertyRelative("disableInternalSequencerCommands"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawInputSettings() { foldouts.inputSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Input Settings", "Input and response menu settings.", foldouts.inputSettingsFoldout, false); if (foldouts.inputSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var inputSettings = displaySettingsProperty.FindPropertyRelative("inputSettings"); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("alwaysForceResponseMenu"), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("includeInvalidEntries"), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("responseTimeout"), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("responseTimeoutAction"), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("emTagForOldResponses"), new GUIContent("[em#] Tag For Old Responses", "The [em#] tag to wrap around responses that have been previously chosen."), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("emTagForInvalidResponses"), new GUIContent("[em#] Tag For Invalid Responses", "The [em#] tag to wrap around invalid responses. These responses are only shown if Include Invalid Entries is ticked."), true); try { EditorWindowTools.StartIndentedSection(); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("qteButtons"), new GUIContent("QTE Input Buttons", "Input buttons mapped to QTEs."), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("cancel"), new GUIContent("Cancel Subtitle Input", "Key or button that cancels subtitle sequences."), true); EditorGUILayout.PropertyField(inputSettings.FindPropertyRelative("cancelConversation"), new GUIContent("Cancel Conversation Input", "Key or button that cancels active conversation while in response menu."), true); } finally { EditorWindowTools.EndIndentedSection(); } } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawBarkSettings() { foldouts.barkSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Bark Settings", "Bark settings.", foldouts.barkSettingsFoldout, false); if (foldouts.barkSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var barkSettings = displaySettingsProperty.FindPropertyRelative("barkSettings"); EditorGUILayout.PropertyField(barkSettings.FindPropertyRelative("allowBarksDuringConversations"), true); EditorGUILayout.PropertyField(barkSettings.FindPropertyRelative("barkCharsPerSecond"), true); EditorGUILayout.PropertyField(barkSettings.FindPropertyRelative("minBarkSeconds"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawAlertSettings() { foldouts.alertSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Alert Settings", "Alert settings.", foldouts.alertSettingsFoldout, false); if (foldouts.alertSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var alertSettings = displaySettingsProperty.FindPropertyRelative("alertSettings"); EditorGUILayout.PropertyField(alertSettings.FindPropertyRelative("allowAlertsDuringConversations"), true); EditorGUILayout.PropertyField(alertSettings.FindPropertyRelative("alertCheckFrequency"), true); EditorGUILayout.PropertyField(alertSettings.FindPropertyRelative("alertCharsPerSecond"), true); EditorGUILayout.PropertyField(alertSettings.FindPropertyRelative("minAlertSeconds"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawPersistentDataSettings() { foldouts.persistentDataSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Persistent Data Settings", "Settings used by the save subsystem.", foldouts.persistentDataSettingsFoldout); if (foldouts.persistentDataSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("recordPersistentDataOn"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("includeStatusAndRelationshipData"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("includeActorData"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("includeAllItemData"), new GUIContent("Include All Item & Quest Data"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("includeLocationData"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("includeAllConversationFields"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("saveConversationSimStatusWithField"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("saveDialogueEntrySimStatusWithField"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("asyncGameObjectBatchSize"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("asyncDialogueEntryBatchSize"), true); EditorGUILayout.PropertyField(persistentDataSettingsProperty.FindPropertyRelative("initializeNewVariables"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private void DrawOtherSettings() { foldouts.otherSettingsFoldout = EditorWindowTools.EditorGUILayoutFoldout("Other Settings", "Miscellaneous settings.", foldouts.otherSettingsFoldout); if (foldouts.otherSettingsFoldout) { try { EditorWindowTools.EditorGUILayoutBeginGroup(); var dontDestroyOnLoadProperty = serializedObject.FindProperty("dontDestroyOnLoad"); EditorGUILayout.PropertyField(serializedObject.FindProperty("allowOnlyOneInstance"), true); var previousDontDestroyOnLoadValue = dontDestroyOnLoadProperty.boolValue; EditorGUILayout.PropertyField(dontDestroyOnLoadProperty, true); if (previousDontDestroyOnLoadValue == true && dontDestroyOnLoadProperty.boolValue == false) { if (!VerifyDisableDontDestroyOnLoad()) { dontDestroyOnLoadProperty.boolValue = true; } } EditorGUILayout.PropertyField(serializedObject.FindProperty("preloadResources"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("warmUpConversationController"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("instantiateDatabase"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("includeSimStatus"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("allowSimultaneousConversations"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("dialogueTimeMode"), true); EditorGUILayout.PropertyField(serializedObject.FindProperty("debugLevel"), true); } finally { EditorWindowTools.EditorGUILayoutEndGroup(); } } } private bool VerifyDisableDontDestroyOnLoad() { var controller = target as DialogueSystemController; if (controller == null) return true; var inputDeviceManager = controller.GetComponent<InputDeviceManager>(); var dontDestroyInputDeviceManager = (inputDeviceManager != null && inputDeviceManager.singleton); var saveSystem = controller.GetComponent<SaveSystem>(); if (saveSystem != null && dontDestroyInputDeviceManager) { EditorUtility.DisplayDialog("Can't Untick Don't Destroy On Load", "The Dialogue Manager has a Save System component, which always sets the GameObject to Don't Destroy On Load. Before unticking this checkbox, move the Save System to a different GameObject. Also untick the Input Device Manager's Singleton checkbox, which also sets Don't Destroy On Load.", "OK"); return false; } else if (saveSystem != null) { EditorUtility.DisplayDialog("Can't Untick Don't Destroy On Load", "The Dialogue Manager has a Save System component, which always sets the GameObject to Don't Destroy On Load. Before unticking this checkbox, move the Save System to a different GameObject.", "OK"); return false; } else if (dontDestroyInputDeviceManager) { if (EditorUtility.DisplayDialog("Unticking Don't Destroy On Load", "The Input Device Manager's Singleton checkbox is ticked, which will also set this GameObject to Don't Destroy On Load. Untick its Singleton checkbox too?", "Yes", "No")) { Undo.RecordObject(inputDeviceManager, "Untick Singleton"); inputDeviceManager.singleton = false; } return true; } return true; } } }
56.380531
379
0.629061
[ "Apache-2.0" ]
NGTO-WONG/KishiStory
Assets/Plugins/Pixel Crushers/Dialogue System/Scripts/Editor/Inspectors/Manager/DialogueSystemControllerEditor.cs
25,484
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using System.Linq; [ExecuteInEditMode] public class YoumuSlashEventMap : MonoBehaviour { [SerializeField] private YoumuSlashTimingData timingData; [SerializeField] private bool sort; [SerializeField] private List<Event> events; [System.Serializable] public class Event { public string description; public float beat; public bool debugPause; public UnityEvent unityEvent; } private Queue<Event> upcomingEvents; void Start() { if (!Application.isPlaying) return; upcomingEvents = new Queue<Event>(events); YoumuSlashPlayerController.onFail += onFail; } void Update() { if (!Application.isPlaying) { if (sort) { events = events.OrderBy (a => a.beat).ToList (); sort = false; } return; } if (!upcomingEvents.Any()) return; else if (timingData.CurrentBeat >= upcomingEvents.Peek().beat) { var newEvent = upcomingEvents.Dequeue(); newEvent.unityEvent.Invoke(); if (newEvent.debugPause) Debug.Break(); } } void onFail() { enabled = false; } }
20.030769
70
0.615975
[ "MIT" ]
Anxeal/NitoriWare
Assets/Microgames/_Bosses/YoumuSlash/Scripts/YoumuSlashEventMap.cs
1,304
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. using System; using System.Runtime.InteropServices; using static TorchSharp.torch; namespace TorchSharp { using Modules; namespace Modules { /// <summary> /// This class is used to represent a Tanh module. /// </summary> public class Tanh : torch.nn.Module { internal Tanh(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { } [DllImport("LibTorchSharp")] private static extern IntPtr THSNN_Tanh_forward(torch.nn.Module.HType module, IntPtr tensor); public override Tensor forward(Tensor tensor) { var res = THSNN_Tanh_forward(handle, tensor.Handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return new Tensor(res); } public override string GetName() { return typeof(Tanh).Name; } } } public static partial class torch { public static partial class nn { [DllImport("LibTorchSharp")] extern static IntPtr THSNN_Tanh_ctor(out IntPtr pBoxedModule); /// <summary> /// Tanh activation /// </summary> /// <returns></returns> static public Tanh Tanh() { var handle = THSNN_Tanh_ctor(out var boxedHandle); if (handle == IntPtr.Zero) { torch.CheckForErrors(); } return new Tanh(handle, boxedHandle); } public static partial class functional { /// <summary> /// Tanh activation /// </summary> /// <param name="x">The input tensor</param> /// <returns></returns> static public Tensor tanh(Tensor x) { using (var m = nn.Tanh()) { return m.forward(x); } } } } } }
30.56338
130
0.509677
[ "MIT" ]
FusionBolt/TorchSharp
src/TorchSharp/NN/Activation/Tanh.cs
2,170
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("WoWthing Sync")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WoWthing Sync")] [assembly: AssemblyCopyright("Copyright © Freddie 2015-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("703aa41f-6a76-47fb-8199-95ba972927a8")] // 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("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")]
38.135135
84
0.745571
[ "MIT" ]
fronbow/wowthing-sync
WoWthing Sync/Properties/AssemblyInfo.cs
1,414
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Es.V20180416.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeInstanceOperationsResponse : AbstractModel { /// <summary> /// 操作记录总数 /// </summary> [JsonProperty("TotalCount")] public ulong? TotalCount{ get; set; } /// <summary> /// 操作记录 /// </summary> [JsonProperty("Operations")] public Operation[] Operations{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount); this.SetParamArrayObj(map, prefix + "Operations.", this.Operations); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.051724
83
0.632982
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Es/V20180416/Models/DescribeInstanceOperationsResponse.cs
1,879
C#
using System; namespace R5T.Veria.Base.Construction { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
15.923077
47
0.512077
[ "MIT" ]
MinexAutomation/R5T.Veria.Base
source/R5T.Veria.Base.Construction/Code/Program.cs
209
C#
using Auth.Data; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Security.Claims; using System.Text; namespace Auth.Biz.Core { public static class TokenService { public static string GenerateToken(Usuario user) { var tokenHandler = new JwtSecurityTokenHandler(); IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(@Directory.GetCurrentDirectory() + "/../../Projects/Auth.API/appsettings.json") .Build(); var key = Encoding.ASCII.GetBytes(configuration.GetSection("SecretKey").Value); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Nome.ToString()), new Claim(ClaimTypes.Email, user.Email.ToString()) }), Expires = DateTime.UtcNow.AddHours(2), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } }
35.775
130
0.634521
[ "MIT" ]
LucasRufo/auth-jwt
Api/Projects/Auth.Biz/Core/TokenService.cs
1,433
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/udpmib.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="MIB_UDPSTATS" /> struct.</summary> public static unsafe partial class MIB_UDPSTATSTests { /// <summary>Validates that the <see cref="MIB_UDPSTATS" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<MIB_UDPSTATS>(), Is.EqualTo(sizeof(MIB_UDPSTATS))); } /// <summary>Validates that the <see cref="MIB_UDPSTATS" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(MIB_UDPSTATS).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="MIB_UDPSTATS" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(MIB_UDPSTATS), Is.EqualTo(20)); } }
36.371429
145
0.710134
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/shared/udpmib/MIB_UDPSTATSTests.cs
1,275
C#
using System; using System.Collections.Generic; using UnityEngine; public class KMBossModule : MonoBehaviour { public string[] GetIgnoredModules(KMBombModule module, string[] @default = null) { return GetIgnoredModules(module.ModuleDisplayName, @default); } public string[] GetIgnoredModules(string moduleDisplayName, string[] @default = null) { if (Application.isEditor) return @default ?? new string[0]; var bossModuleManagerAPIGameObject = GameObject.Find("BossModuleManager"); if (bossModuleManagerAPIGameObject == null) // Boss Module Manager is not installed return @default ?? new string[0]; var bossModuleManagerAPI = bossModuleManagerAPIGameObject.GetComponent<IDictionary<string, object>>(); if (bossModuleManagerAPI == null || !bossModuleManagerAPI.ContainsKey("GetIgnoredModules")) return @default ?? new string[0]; return ((Func<string, string[]>)bossModuleManagerAPI["GetIgnoredModules"])(moduleDisplayName) ?? @default ?? new string[0]; } }
36.666667
125
0.761616
[ "MIT" ]
JakkOfKlubs/ktane-purgatory
Assets/Scripts/KMBossModule.cs
992
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 Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for HeaderOperations. /// </summary> public static partial class HeaderOperationsExtensions { /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fooClientRequestId'> /// The fooRequestId /// </param> public static HeaderCustomNamedRequestIdHeadersInner CustomNamedRequestId(this IHeaderOperations operations, string fooClientRequestId) { return operations.CustomNamedRequestIdAsync(fooClientRequestId).GetAwaiter().GetResult(); } /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fooClientRequestId'> /// The fooRequestId /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HeaderCustomNamedRequestIdHeadersInner> CustomNamedRequestIdAsync(this IHeaderOperations operations, string fooClientRequestId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CustomNamedRequestIdWithHttpMessagesAsync(fooClientRequestId, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request, via a parameter group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerCustomNamedRequestIdParamGroupingParameters'> /// Additional parameters for the operation /// </param> public static HeaderCustomNamedRequestIdParamGroupingHeadersInner CustomNamedRequestIdParamGrouping(this IHeaderOperations operations, HeaderCustomNamedRequestIdParamGroupingParametersInner headerCustomNamedRequestIdParamGroupingParameters) { return operations.CustomNamedRequestIdParamGroupingAsync(headerCustomNamedRequestIdParamGroupingParameters).GetAwaiter().GetResult(); } /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request, via a parameter group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerCustomNamedRequestIdParamGroupingParameters'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HeaderCustomNamedRequestIdParamGroupingHeadersInner> CustomNamedRequestIdParamGroupingAsync(this IHeaderOperations operations, HeaderCustomNamedRequestIdParamGroupingParametersInner headerCustomNamedRequestIdParamGroupingParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CustomNamedRequestIdParamGroupingWithHttpMessagesAsync(headerCustomNamedRequestIdParamGroupingParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } } }
47.071429
335
0.636462
[ "MIT" ]
DiogenesPolanco/autorest
src/generator/AutoRest.CSharp.Azure.Fluent.Tests/Expected/AcceptanceTests/AzureSpecials/HeaderOperationsExtensions.cs
4,613
C#
using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace DotNext.Buffers; /// <summary> /// Represents simple memory reader backed by <see cref="ReadOnlySpan{T}"/>. /// </summary> /// <typeparam name="T">The type of elements in the span.</typeparam> [StructLayout(LayoutKind.Auto)] public ref struct SpanReader<T> { private readonly ReadOnlySpan<T> span; private int position; /// <summary> /// Initializes a new memory reader. /// </summary> /// <param name="span">The span to read from.</param> public SpanReader(ReadOnlySpan<T> span) { this.span = span; position = 0; } /// <summary> /// Initializes a new memory reader. /// </summary> /// <param name="reference">Managed pointer to the memory block.</param> /// <param name="length">The length of the elements referenced by the pointer.</param> public SpanReader(ref T reference, int length) { if (Unsafe.IsNullRef(ref reference)) throw new ArgumentNullException(nameof(reference)); span = MemoryMarshal.CreateReadOnlySpan(ref reference, length); position = 0; } /// <summary> /// Gets the element at the current position in the /// underlying memory block. /// </summary> /// <exception cref="InvalidOperationException">The position of this reader is out of range.</exception> public readonly ref readonly T Current { get { if ((uint)position >= (uint)span.Length) throw new InvalidOperationException(); return ref Unsafe.Add(ref MemoryMarshal.GetReference(span), position); } } /// <summary> /// Gets the number of consumed elements. /// </summary> public readonly int ConsumedCount => position; /// <summary> /// Gets the number of unread elements. /// </summary> public readonly int RemainingCount => span.Length - position; /// <summary> /// Gets underlying span. /// </summary> public readonly ReadOnlySpan<T> Span => span; /// <summary> /// Gets the span over consumed elements. /// </summary> public readonly ReadOnlySpan<T> ConsumedSpan => span.Slice(0, position); /// <summary> /// Gets the remaining part of the span. /// </summary> public readonly ReadOnlySpan<T> RemainingSpan => span.Slice(position); /// <summary> /// Advances the position of this reader. /// </summary> /// <param name="count">The number of consumed elements.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is greater than the available space in the rest of the memory block.</exception> public void Advance(int count) { var newPosition = position + count; if ((uint)newPosition > (uint)span.Length) throw new ArgumentOutOfRangeException(nameof(count)); position = newPosition; } /// <summary> /// Moves the reader back the specified number of items. /// </summary> /// <param name="count">The number of items.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is less than zero or greater than <see cref="ConsumedCount"/>.</exception> public void Rewind(int count) { if ((uint)count > (uint)position) throw new ArgumentOutOfRangeException(nameof(count)); position -= count; } /// <summary> /// Sets reader position to the first element. /// </summary> public void Reset() => position = 0; /// <summary> /// Copies elements from the underlying span. /// </summary> /// <param name="output">The span used to write elements from the underlying span.</param> /// <returns><see langword="true"/> if size of <paramref name="output"/> is less than or equal to <see cref="RemainingCount"/>; otherwise, <see langword="false"/>.</returns> public bool TryRead(Span<T> output) => TryRead(output.Length, out var input) && input.TryCopyTo(output); /// <summary> /// Reads the portion of data from the underlying span. /// </summary> /// <param name="count">The number of elements to read from the underlying span.</param> /// <param name="result">The segment of the underlying span.</param> /// <returns><see langword="true"/> if <paramref name="count"/> is less than or equal to <see cref="RemainingCount"/>; otherwise <see langword="false"/>.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative.</exception> public bool TryRead(int count, out ReadOnlySpan<T> result) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); var newLength = position + count; if ((uint)newLength <= (uint)span.Length) { result = span.Slice(position, count); position = newLength; return true; } result = default; return false; } /// <summary> /// Reads single element from the underlying span. /// </summary> /// <param name="result">The obtained element.</param> /// <returns><see langword="true"/> if element is obtained successfully; otherwise, <see langword="false"/>.</returns> public bool TryRead([MaybeNullWhen(false)] out T result) { var newLength = position + 1; if ((uint)newLength <= (uint)span.Length) { result = Unsafe.Add(ref MemoryMarshal.GetReference(span), position); position = newLength; return true; } result = default; return false; } /// <summary> /// Copies elements from the underlying span. /// </summary> /// <param name="output">The span used to write elements from the underlying span.</param> /// <returns>The number of obtained elements.</returns> public int Read(Span<T> output) { RemainingSpan.CopyTo(output, out var writtenCount); position += writtenCount; return writtenCount; } /// <summary> /// Reads single element from the underlying span. /// </summary> /// <returns>The element obtained from the span.</returns> /// <exception cref="InternalBufferOverflowException">The end of memory block is reached.</exception> public T Read() => TryRead(out var result) ? result : throw new InternalBufferOverflowException(); /// <summary> /// Reads the portion of data from the underlying span. /// </summary> /// <param name="count">The number of elements to read from the underlying span.</param> /// <returns>The portion of data within the underlying span.</returns> /// <exception cref="InternalBufferOverflowException"><paramref name="count"/> is greater than <see cref="RemainingCount"/>.</exception> public ReadOnlySpan<T> Read(int count) => TryRead(count, out var result) ? result : throw new InternalBufferOverflowException(); /// <summary> /// Decodes the value from the block of memory. /// </summary> /// <param name="reader">The decoder.</param> /// <param name="count">The numbers of elements to read.</param> /// <typeparam name="TResult">The type of the result.</typeparam> /// <returns>The decoded value.</returns> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is zero.</exception> /// <exception cref="InternalBufferOverflowException"><paramref name="count"/> is greater than <see cref="RemainingCount"/>.</exception> [CLSCompliant(false)] public unsafe TResult Read<TResult>(delegate*<ReadOnlySpan<T>, TResult> reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (!TryRead(count, out var buffer)) throw new InternalBufferOverflowException(); return reader(buffer); } /// <summary> /// Attempts to decode the value from the block of memory. /// </summary> /// <param name="reader">The decoder.</param> /// <param name="count">The numbers of elements to read.</param> /// <param name="result">The decoded value.</param> /// <typeparam name="TResult">The type of the value to be decoded.</typeparam> /// <returns><see langword="true"/> if the value is decoded successfully; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="reader"/> is zero.</exception> [CLSCompliant(false)] public unsafe bool TryRead<TResult>(delegate*<ReadOnlySpan<T>, TResult> reader, int count, [MaybeNullWhen(false)] out TResult result) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (TryRead(count, out var buffer)) { result = reader(buffer); return true; } result = default; return false; } /// <summary> /// Reads the rest of the memory block. /// </summary> /// <returns>The rest of the memory block.</returns> public ReadOnlySpan<T> ReadToEnd() { var result = RemainingSpan; position = span.Length; return result; } /// <summary> /// Gets the textual representation of the written content. /// </summary> /// <returns>The textual representation of the written content.</returns> public readonly override string ToString() => ConsumedSpan.ToString(); }
37.038911
177
0.634625
[ "MIT" ]
dotnet/dotNext
src/DotNext/Buffers/SpanReader.cs
9,519
C#
using System.Diagnostics.CodeAnalysis; namespace WarpDeck.Presentation.Controllers.Models { [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class PropertyResponseModel { public string Name { get; set; } public string Value { get; set; } } }
27.272727
71
0.71
[ "MIT" ]
armunro/WarpDeck
WarpDeck.Presentation/Controllers/Models/PropertyResponseModel.cs
300
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ChangeVolume : MonoBehaviour { public Slider Volume; public AudioSource Music; private void Update() { Music.volume = Volume.value; } }
19.466667
44
0.684932
[ "MIT" ]
18-2-SKKU-OSS/2018-2-OSS-E2
Assets/Scripts/ChangeVolume.cs
294
C#
using System; using Foundatio.Repositories.Elasticsearch.Configuration; using Nest; namespace Exceptionless.Core.Repositories.Configuration { public sealed class EventIndex : DailyIndex { private const string EMAIL_TOKEN_FILTER = "email"; private const string TYPENAME_TOKEN_FILTER = "typename"; private const string VERSION_TOKEN_FILTER = "version"; private const string VERSION_PAD1_TOKEN_FILTER = "version_pad1"; private const string VERSION_PAD2_TOKEN_FILTER = "version_pad2"; private const string VERSION_PAD3_TOKEN_FILTER = "version_pad3"; private const string VERSION_PAD4_TOKEN_FILTER = "version_pad4"; internal const string COMMA_WHITESPACE_ANALYZER = "comma_whitespace"; internal const string EMAIL_ANALYZER = "email"; internal const string VERSION_INDEX_ANALYZER = "version_index"; internal const string VERSION_SEARCH_ANALYZER = "version_search"; internal const string WHITESPACE_LOWERCASE_ANALYZER = "whitespace_lower"; internal const string TYPENAME_ANALYZER = "typename"; internal const string STANDARDPLUS_ANALYZER = "standardplus"; internal const string COMMA_WHITESPACE_TOKENIZER = "comma_whitespace"; internal const string TYPENAME_HIERARCHY_TOKENIZER = "typename_hierarchy"; private readonly ExceptionlessElasticConfiguration _configuration; public EventIndex(ExceptionlessElasticConfiguration configuration) : base(configuration, configuration.Options.ScopePrefix + "events", 1) { _configuration = configuration; MaxIndexAge = TimeSpan.FromDays(180); AddType(Event = new EventIndexType(this)); AddAlias($"{Name}-today", TimeSpan.FromDays(1)); AddAlias($"{Name}-last3days", TimeSpan.FromDays(7)); AddAlias($"{Name}-last7days", TimeSpan.FromDays(7)); AddAlias($"{Name}-last30days", TimeSpan.FromDays(30)); AddAlias($"{Name}-last90days", TimeSpan.FromDays(90)); } public EventIndexType Event { get; } public override CreateIndexDescriptor ConfigureIndex(CreateIndexDescriptor idx) { return base.ConfigureIndex(idx.Settings(s => s .Analysis(BuildAnalysis) .NumberOfShards(_configuration.Options.NumberOfShards) .NumberOfReplicas(_configuration.Options.NumberOfReplicas) .Setting("index.mapping.total_fields.limit", _configuration.Options.FieldsLimit) .Priority(1))); } private AnalysisDescriptor BuildAnalysis(AnalysisDescriptor ad) { return ad.Analyzers(a => a .Pattern(COMMA_WHITESPACE_ANALYZER, p => p.Pattern(@"[,\s]+")) .Custom(EMAIL_ANALYZER, c => c.Filters(EMAIL_TOKEN_FILTER, "lowercase", "unique").Tokenizer("keyword")) .Custom(VERSION_INDEX_ANALYZER, c => c.Filters(VERSION_PAD1_TOKEN_FILTER, VERSION_PAD2_TOKEN_FILTER, VERSION_PAD3_TOKEN_FILTER, VERSION_PAD4_TOKEN_FILTER, VERSION_TOKEN_FILTER, "lowercase", "unique").Tokenizer("whitespace")) .Custom(VERSION_SEARCH_ANALYZER, c => c.Filters(VERSION_PAD1_TOKEN_FILTER, VERSION_PAD2_TOKEN_FILTER, VERSION_PAD3_TOKEN_FILTER, VERSION_PAD4_TOKEN_FILTER, "lowercase").Tokenizer("whitespace")) .Custom(WHITESPACE_LOWERCASE_ANALYZER, c => c.Filters("lowercase").Tokenizer("whitespace")) .Custom(TYPENAME_ANALYZER, c => c.Filters(TYPENAME_TOKEN_FILTER, "lowercase", "unique").Tokenizer(TYPENAME_HIERARCHY_TOKENIZER)) .Custom(STANDARDPLUS_ANALYZER, c => c.Filters("standard", TYPENAME_TOKEN_FILTER, "lowercase", "stop", "unique").Tokenizer(COMMA_WHITESPACE_TOKENIZER))) .TokenFilters(f => f .PatternCapture(EMAIL_TOKEN_FILTER, p => p.Patterns(@"(\w+)", @"(\p{L}+)", @"(\d+)", "(.+)@", "@(.+)")) .PatternCapture(TYPENAME_TOKEN_FILTER, p => p.Patterns(@"\.(\w+)", @"([^\()]+)")) .PatternCapture(VERSION_TOKEN_FILTER, p => p.Patterns(@"^(\d+)\.", @"^(\d+\.\d+)", @"^(\d+\.\d+\.\d+)")) .PatternReplace(VERSION_PAD1_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{1})(?=\.|-|$)").Replacement("$10000$2")) .PatternReplace(VERSION_PAD2_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{2})(?=\.|-|$)").Replacement("$1000$2")) .PatternReplace(VERSION_PAD3_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{3})(?=\.|-|$)").Replacement("$100$2")) .PatternReplace(VERSION_PAD4_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{4})(?=\.|-|$)").Replacement("$10$2"))) .Tokenizers(t => t .Pattern(COMMA_WHITESPACE_TOKENIZER, p => p.Pattern(@"[,\s]+")) .PathHierarchy(TYPENAME_HIERARCHY_TOKENIZER, p => p.Delimiter('.'))); } } }
66.260274
240
0.657226
[ "Apache-2.0" ]
Rainy99/Exceptionless
src/Exceptionless.Core/Repositories/Configuration/Indexes/EventIndex/EventIndex.cs
4,839
C#
using Newtonsoft.Json; namespace Core.aria2cNet.client.entity { [JsonObject] public class AriaShutdown { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("jsonrpc")] public string Jsonrpc { get; set; } [JsonProperty("result")] public string Result { get; set; } [JsonProperty("error")] public AriaError Error { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
21
53
0.57326
[ "Apache-2.0" ]
202094318/downkyi
src/Core/aria2cNet/client/entity/AriaShutdown.cs
548
C#
// <auto-generated /> using System; using CommunalPayments.DataAccess.Database; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CommunalPayments.DataAccess.Migrations { [DbContext(typeof(DataModel))] [Migration("20210527125813_AddCommission")] partial class AddCommission { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.5"); modelBuilder.Entity("CommunalPayments.Common.Account", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Apartment") .HasMaxLength(25) .HasColumnType("TEXT"); b.Property<string>("Building") .IsRequired() .HasMaxLength(25) .HasColumnType("TEXT"); b.Property<string>("City") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<int>("InternalId") .HasColumnType("INTEGER"); b.Property<string>("Key") .HasMaxLength(64) .HasColumnType("TEXT"); b.Property<long>("Number") .HasColumnType("INTEGER"); b.Property<int>("PersonId") .HasColumnType("INTEGER"); b.Property<string>("Street") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("PersonId"); b.ToTable("Accounts"); }); modelBuilder.Entity("CommunalPayments.Common.Bill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("CreateDate") .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<long>("ErcId") .HasColumnType("INTEGER"); b.Property<int>("ModeId") .HasColumnType("INTEGER"); b.Property<int>("StatusId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("ModeId"); b.HasIndex("StatusId"); b.ToTable("Bills"); }); modelBuilder.Entity("CommunalPayments.Common.PayMode", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("PayModes"); }); modelBuilder.Entity("CommunalPayments.Common.PayStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("PayStatuses"); }); modelBuilder.Entity("CommunalPayments.Common.Payment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("AccountId") .HasColumnType("INTEGER"); b.Property<string>("Bbl") .HasColumnType("TEXT"); b.Property<int?>("BillId") .HasColumnType("INTEGER"); b.Property<string>("Comment") .HasColumnType("TEXT"); b.Property<decimal>("Commission") .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<long>("ErcId") .HasColumnType("INTEGER"); b.Property<DateTime>("PaymentDate") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("AccountId"); b.HasIndex("BillId"); b.ToTable("Payments"); }); modelBuilder.Entity("CommunalPayments.Common.PaymentItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<decimal>("Amount") .HasColumnType("TEXT"); b.Property<decimal?>("CurrentIndication") .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<decimal?>("LastIndication") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Options") .HasColumnType("TEXT"); b.Property<int>("PaymentId") .HasColumnType("INTEGER"); b.Property<DateTime>("PeriodFrom") .HasColumnType("TEXT"); b.Property<DateTime>("PeriodTo") .HasColumnType("TEXT"); b.Property<int>("ServiceId") .HasColumnType("INTEGER"); b.Property<decimal?>("Value") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("PaymentId"); b.HasIndex("ServiceId"); b.ToTable("PaymentItems"); }); modelBuilder.Entity("CommunalPayments.Common.Person", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("SurName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("Persons"); }); modelBuilder.Entity("CommunalPayments.Common.Rate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("DateFrom") .HasColumnType("TEXT"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<string>("Measure") .IsRequired() .HasMaxLength(25) .HasColumnType("TEXT"); b.Property<int>("ServiceId") .HasColumnType("INTEGER"); b.Property<decimal>("Value") .HasPrecision(12, 5) .HasColumnType("TEXT"); b.Property<decimal>("VolumeFrom") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ServiceId"); b.ToTable("Rates"); }); modelBuilder.Entity("CommunalPayments.Common.Service", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<bool>("Enabled") .HasColumnType("INTEGER"); b.Property<int>("ErcId") .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("Services"); }); modelBuilder.Entity("CommunalPayments.Common.Account", b => { b.HasOne("CommunalPayments.Common.Person", "Person") .WithMany("Accounts") .HasForeignKey("PersonId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Person"); }); modelBuilder.Entity("CommunalPayments.Common.Bill", b => { b.HasOne("CommunalPayments.Common.PayMode", "Mode") .WithMany("Bills") .HasForeignKey("ModeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CommunalPayments.Common.PayStatus", "Status") .WithMany("Bills") .HasForeignKey("StatusId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Mode"); b.Navigation("Status"); }); modelBuilder.Entity("CommunalPayments.Common.Payment", b => { b.HasOne("CommunalPayments.Common.Account", "Account") .WithMany("Payments") .HasForeignKey("AccountId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CommunalPayments.Common.Bill", "Bill") .WithMany("Payments") .HasForeignKey("BillId"); b.Navigation("Account"); b.Navigation("Bill"); }); modelBuilder.Entity("CommunalPayments.Common.PaymentItem", b => { b.HasOne("CommunalPayments.Common.Payment", "Payment") .WithMany("PaymentItems") .HasForeignKey("PaymentId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CommunalPayments.Common.Service", "Service") .WithMany() .HasForeignKey("ServiceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Payment"); b.Navigation("Service"); }); modelBuilder.Entity("CommunalPayments.Common.Rate", b => { b.HasOne("CommunalPayments.Common.Service", "Service") .WithMany("Rates") .HasForeignKey("ServiceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Service"); }); modelBuilder.Entity("CommunalPayments.Common.Account", b => { b.Navigation("Payments"); }); modelBuilder.Entity("CommunalPayments.Common.Bill", b => { b.Navigation("Payments"); }); modelBuilder.Entity("CommunalPayments.Common.PayMode", b => { b.Navigation("Bills"); }); modelBuilder.Entity("CommunalPayments.Common.PayStatus", b => { b.Navigation("Bills"); }); modelBuilder.Entity("CommunalPayments.Common.Payment", b => { b.Navigation("PaymentItems"); }); modelBuilder.Entity("CommunalPayments.Common.Person", b => { b.Navigation("Accounts"); }); modelBuilder.Entity("CommunalPayments.Common.Service", b => { b.Navigation("Rates"); }); #pragma warning restore 612, 618 } } }
33.07601
75
0.414004
[ "MIT" ]
poimenov/CommunalPaymen
CommunalPayments.DataAccess/Migrations/20210527125813_AddCommission.Designer.cs
13,927
C#
namespace GerenciadorFC.Repositorio.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<GerenciadorFC.Repositorio.Contexto.Contexto> { public Configuration() { AutomaticMigrationsEnabled = false; SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator()); } protected override void Seed(GerenciadorFC.Repositorio.Contexto.Contexto context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
34.848485
112
0.588696
[ "Apache-2.0" ]
ribeiroalex/GerenciadorFC
GerenciadoFC.Crawler/GerenciadorFC.Repositorio/Migrations/Configuration.cs
1,150
C#
//#define VER_EQ_TEST //#define NVELOCITY_TEST //#define BASE_PAGE_TEST //#define WIN #if WIN using System.IO; using System.Reflection; using System; using JinianNet.JNTemplate.Test.Model; using System.Diagnostics; using Xunit; namespace JinianNet.JNTemplate.Test { /// <summary> /// 实际WEB页面模板测试 /// </summary> public class WebPageTests { const string HTML_RESULT = "<!DOCTYPEhtml><htmllang=\"zh-cn\"><head><title>jntemplate测试页</title><metacharset=\"utf-8\"><metahttp-equiv=\"X-UA-Compatible\"content=\"IE=edge\"/><metaname=\"viewport\"content=\"width=device-width,initial-scale=1\"/><metaname=\"description\"content=\"\"/><metaname=\"author\"content=\"\"/><linkhref=\"Library/bootstrap/css/bootstrap.min.css\"rel=\"stylesheet\"type=\"text/css\"/><linkhref=\"Library/bootstrap/css/bootstrap-theme.min.css\"rel=\"stylesheet\"type=\"text/css\"/><linkhref=\"css/layout.css\"rel=\"stylesheet\"type=\"text/css\"/></head><bodyrole=\"document\"><divclass=\"header\"><divclass=\"topbar\"><divclass=\"wrapper\"><ahref=\"/Login.aspx\">登录</a><ahref=\"/Register.aspx\">注册</a></div></div><divclass=\"head-hd\"><divclass=\"head-logo\"><imgsrc=\"http://www.jiniannet.com/Attachment/10017\"alt=\"\"/></div><divclass=\"head-banner\"><scripttype=\"text/javascript\">/*全部顶部广告*/varcpro_id=\"u1681269\";</script><scriptsrc=\"http://cpro.baidustatic.com/cpro/ui/c.js\"type=\"text/javascript\"></script></div><divclass=\"head-text\">.Net技术交流群(5089240)<br/><atarget=\"_blank\"href=\"http://bbs.jiniannet.com\">极念论坛</a><atarget=\"_blank\"href=\"http://www.jiniannet.com/Channel/jntemplate\"style=\"color:#f00\">JNTemplate手册</a><br/><atarget=\"_blank\"href=\"http://bbs.jiniannet.com/forum.php?mod=viewthread&tid=1\">ASP.NET模板引擎源码下载</a><br/></div></div><divclass=\"nav\"><ulclass=\"wrapper\"><liclass=\"active\"><ahref=\"/default.aspx\">首页</a></li><li><ahref=\"/Product/pro001.aspx\">产品1</a></li><li><ahref=\"/Product/pro001.aspx\">产品2</a></li><li><ahref=\"/Product/pro001.aspx\">产品3</a></li><li><ahref=\"/Product/pro001.aspx\">产品4</a></li><li><ahref=\"/Support.aspx\">服务支持</a></li></ul></div></div><divclass=\"wrapper\"><divclass=\"help-search\">快速帮助:<selectid=\"SearchProduct\"><optionvalue=\"201\">产品1</option><optionvalue=\"202\">产品2</option><optionvalue=\"203\">产品3</option><optionvalue=\"204\">产品4</option></select><inputtype=\"text\"value=\"\"id=\"SearchKey\"/><buttonclass=\"btnbtn-success\"id=\"btnSupportSearch\">搜索</button></div><divclass=\"help-sidebar\"><dl><dt><ahref=\"/Support.aspx?product=201\">产品1</a></dt><dd><ahref=\"/Category/001.aspx?product=201\">栏目1</a></dd><dd><ahref=\"/Category/002.aspx?product=201\">栏目2</a></dd><dd><ahref=\"/Category/003.aspx?product=201\">栏目3</a></dd><dd><ahref=\"/Category/004.aspx?product=201\">栏目4</a></dd><dd><ahref=\"/Category/005.aspx?product=201\">栏目5</a></dd><dd><ahref=\"/Category/006.aspx?product=201\">栏目6</a></dd></dl><dl><dt><ahref=\"/Support.aspx?product=202\">产品2</a></dt><dd><ahref=\"/Category/001.aspx?product=202\">栏目1</a></dd><dd><ahref=\"/Category/002.aspx?product=202\">栏目2</a></dd><dd><ahref=\"/Category/003.aspx?product=202\">栏目3</a></dd><dd><ahref=\"/Category/004.aspx?product=202\">栏目4</a></dd><dd><ahref=\"/Category/005.aspx?product=202\">栏目5</a></dd><dd><ahref=\"/Category/006.aspx?product=202\">栏目6</a></dd></dl><dl><dt><ahref=\"/Support.aspx?product=203\">产品3</a></dt><dd><ahref=\"/Category/001.aspx?product=203\">栏目1</a></dd><dd><ahref=\"/Category/002.aspx?product=203\">栏目2</a></dd><dd><ahref=\"/Category/003.aspx?product=203\">栏目3</a></dd><dd><ahref=\"/Category/004.aspx?product=203\">栏目4</a></dd><dd><ahref=\"/Category/005.aspx?product=203\">栏目5</a></dd><dd><ahref=\"/Category/006.aspx?product=203\">栏目6</a></dd></dl><dl><dt><ahref=\"/Support.aspx?product=204\">产品4</a></dt><dd><ahref=\"/Category/001.aspx?product=204\">栏目1</a></dd><dd><ahref=\"/Category/002.aspx?product=204\">栏目2</a></dd><dd><ahref=\"/Category/003.aspx?product=204\">栏目3</a></dd><dd><ahref=\"/Category/004.aspx?product=204\">栏目4</a></dd><dd><ahref=\"/Category/005.aspx?product=204\">栏目5</a></dd><dd><ahref=\"/Category/006.aspx?product=204\">栏目6</a></dd></dl></div><divclass=\"help-hd\"><divclass=\"hd-mod\"><h1>视频网站付费会员增长超700%苦熬7年再度掀付费潮</h1><dl><dt>功能模块:</dt><dd><ahref='4'>测试模块</a></dd><dd><ahref='4'>订单模块</a></dd><dd><ahref='4'>产品模块</a></dd><dd><ahref='4'>新闻模块</a></dd></dl></div><divclass=\"hd-tbl\"><ulclass=\"hd-tbl-head\"id=\"tblHead\"><li><ahref=\"?tag=1\">热门问题</a></li><li><ahref=\"?tag=2\">最新推荐</a></li><li><ahref=\"?tag=3\">最新提问</a></li></ul><divclass=\"help-items\"><ul><li><ahref=\"/Help/art001.aspx\">下单后可以修改订单吗?</a></li><li><ahref=\"/Help/art001.aspx\">无货商品几天可以到货?</a></li><li><ahref=\"/Help/art001.aspx\">合约机资费如何计算?</a></li><li><ahref=\"/Help/art001.aspx\">可以开发票吗?</a></li></ul></div></div><divclass=\"aspnet-pager\"><span>首页</span><span>上一页</span><span>1</span><span>下一页</span><span>末页</span></div></div><divclass=\"clearfix\"></div></div><divclass=\"help-modwrapper\"><dl><dt>新手帮助</dt><dd><ahref=\"/Article/art001.aspx\">购物流程</a></dd><dd><ahref=\"/Article/art001.aspx\">会员介绍</a></dd><dd><ahref=\"/Article/art001.aspx\">生活旅行/团购</a></dd><dd><ahref=\"/Article/art001.aspx\">常见问题</a></dd><dd><ahref=\"/Article/art001.aspx\">联系客服</a></dd></dl><dl><dt>极念网络</dt><dd><ahref=\"/Article/art001.aspx\">购物流程</a></dd><dd><ahref=\"/Article/art001.aspx\">会员介绍</a></dd><dd><ahref=\"/Article/art001.aspx\">生活旅行/团购</a></dd><dd><ahref=\"/Article/art001.aspx\">常见问题</a></dd><dd><ahref=\"/Article/art001.aspx\">联系客服</a></dd></dl><dl><dt>免费应用</dt><dd><ahref=\"/Article/art001.aspx\">购物流程</a></dd><dd><ahref=\"/Article/art001.aspx\">会员介绍</a></dd><dd><ahref=\"/Article/art001.aspx\">生活旅行/团购</a></dd><dd><ahref=\"/Article/art001.aspx\">常见问题</a></dd><dd><ahref=\"/Article/art001.aspx\">联系客服</a></dd></dl><dl><dt>其他服务</dt><dd><ahref=\"/Article/art001.aspx\">购物流程</a></dd><dd><ahref=\"/Article/art001.aspx\">会员介绍</a></dd><dd><ahref=\"/Article/art001.aspx\">生活旅行/团购</a></dd><dd><ahref=\"/Article/art001.aspx\">常见问题</a></dd><dd><ahref=\"/Article/art001.aspx\">联系客服</a></dd></dl><dl><dt>关于我们</dt><dd><ahref=\"/Article/art001.aspx\">购物流程</a></dd><dd><ahref=\"/Article/art001.aspx\">会员介绍</a></dd><dd><ahref=\"/Article/art001.aspx\">生活旅行/团购</a></dd><dd><ahref=\"/Article/art001.aspx\">常见问题</a></dd><dd><ahref=\"/Article/art001.aspx\">联系客服</a></dd></dl></div><divclass=\"footer\"><pclass=\"text-muted\">极念网络版权所有©2015</p></div></body></html>"; const int MAX_RUN_COUNT = 100; #if BASE_PAGE_TEST [Fact] public void TestILVsReflectionPage() { JinianNet.JNTemplate.TemplateContext ctx = new JinianNet.JNTemplate.TemplateContext(); ctx.TempData.Push("func", new TemplateMethod()); SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); ctx.TempData.Push("Site", site); string basePath = #if NET20 || NET40 System.Environment.CurrentDirectory; #else new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName; #endif string path = basePath + "\\templets\\default"; // JinianNet.JNTemplate.Dynamic.IDynamicHelpers h; Configuration.EngineConfig conf; string text1 = null, text2 = null; string result = ""; Stopwatch s = new Stopwatch(); s.Start(); s.Stop(); //////////////////////////////////////////////////////////////////////////////////// //h = new JinianNet.JNTemplate.Dynamic.ILHelpers(); conf = Configuration.EngineConfig.CreateDefault(); Engine.Configure(conf); s.Restart(); for (var i = 0; i < MAX_RUN_COUNT; i++) { JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(ctx, System.IO.File.ReadAllText(path + "\\questionlist.html")); t.Context.CurrentPath = path; text1 = t.Render(); } s.Stop(); result += "\r\n耗时:" + s.ElapsedMilliseconds + "毫秒 - 反射(" + MAX_RUN_COUNT + "次)运行"; //////////////////////////////////////////////////////////////////////////////////// GC.Collect(); //////////////////////////////////////////////////////////////////////////////////// //h = new JinianNet.JNTemplate.Dynamic.ReflectionHelpers(); conf = Configuration.EngineConfig.CreateDefault(); conf.CacheProvider = new UserCache(); Engine.Configure(conf); s.Restart(); for (var i = 0; i < MAX_RUN_COUNT; i++) { JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(ctx, System.IO.File.ReadAllText(path + "\\questionlist.html")); t.Context.CurrentPath = path; text2 = t.Render(); //h.ExcuteMethod(DateTime.Now, "AddDays", new object[] { 30 }); } s.Stop(); //////////////////////////////////////////////////////////////////////////////////// result += "\r\n耗时:" + s.ElapsedMilliseconds + "毫秒 - IL(" + MAX_RUN_COUNT + "次)运行"; System.IO.File.WriteAllText(basePath + "\\result\\ILVsReflection.txt", result); Assert.Equal(text1, text2); } [Fact] public void TestILage() { var c = Configuration.EngineConfig.CreateDefault(); //开始严格大小写模式 默认忽略大小写 //conf.IgnoreCase = false; Engine.Configure(c); JinianNet.JNTemplate.TemplateContext ctx = new JinianNet.JNTemplate.TemplateContext(); ctx.TempData.Push("func", new TemplateMethod()); SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); //ctx.TempData.Push("Model", ); ctx.TempData.Push("Site", site); string basePath = #if NET20 || NET40 System.Environment.CurrentDirectory; #else new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName; #endif string path = basePath + "\\templets\\default"; string html = null; var conf = Configuration.EngineConfig.CreateDefault(); conf.CacheProvider = new UserCache(); conf.DynamicProvider = new JinianNet.JNTemplate.Dynamic.ILDynamicProvider();// new TestExecutor(); Engine.Configure(conf); Stopwatch s = new Stopwatch(); s.Start(); for (var i = 0; i < MAX_RUN_COUNT; i++) { JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(ctx, System.IO.File.ReadAllText(path + "\\questionlist.html")); t.Context.CurrentPath = path; if (i == MAX_RUN_COUNT - 1) { System.IO.File.WriteAllText(basePath + "\\result\\IL.html", t.Render()); } else { html=t.Render(); } } s.Stop(); string result = "\r\n运行耗时:" + s.ElapsedMilliseconds + "毫秒 IL(" + MAX_RUN_COUNT + "次)"; System.IO.File.AppendAllText(basePath + "\\result\\ILVsReflection.txt", result); Assert.Equal(HTML_RESULT, html.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace(" ", "")); } [Fact] public void TestReflectionPage() { JinianNet.JNTemplate.TemplateContext ctx = new JinianNet.JNTemplate.TemplateContext(); ctx.TempData.Push("func", new TemplateMethod()); SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); //ctx.TempData.Push("Model", ); ctx.TempData.Push("Site", site); string basePath = #if NET20 || NET40 System.Environment.CurrentDirectory; #else new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName; #endif string path = basePath + "\\templets\\default"; string html = null; var conf = Configuration.EngineConfig.CreateDefault(); Engine.Configure(conf); Stopwatch s = new Stopwatch(); s.Start(); for (var i = 0; i < MAX_RUN_COUNT; i++) { JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(ctx, System.IO.File.ReadAllText(path + "\\questionlist.html")); t.Context.CurrentPath = path; if (i == MAX_RUN_COUNT - 1) { System.IO.File.WriteAllText(basePath + "\\result\\REFLECTION.html", t.Render()); } else { html=t.Render(); } } s.Stop(); string result = "\r\n运行耗时:" + s.ElapsedMilliseconds + "毫秒 反射(" + MAX_RUN_COUNT + "次)"; System.IO.File.AppendAllText(basePath + "\\result\\ILVsReflection.txt", result); Assert.Equal(HTML_RESULT, html.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace(" ", "")); } [Fact] public void TestPage() { var conf = Configuration.EngineConfig.CreateDefault(); Engine.Configure(conf); JinianNet.JNTemplate.TemplateContext ctx = new JinianNet.JNTemplate.TemplateContext(); ctx.TempData.Push("func", new TemplateMethod()); SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); //ctx.TempData.Push("Model", ); ctx.TempData.Push("Site", site); string basePath = #if NET20 || NET40 System.Environment.CurrentDirectory; #else new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName; #endif string path = basePath + "\\templets\\default"; JinianNet.JNTemplate.Template t = new JinianNet.JNTemplate.Template(ctx, System.IO.File.ReadAllText(path + "\\questionlist.html")); t.Context.CurrentPath = path; string result = t.Render(); //可直接查看项目录下的html/jnt.html 文件效果 System.IO.File.WriteAllText(basePath + "\\result\\jnt.html", result); Assert.Equal(HTML_RESULT, result.Replace("\r","").Replace("\t", "").Replace("\n", "").Replace(" ", "")); } #endif #if VER_EQ_TEST /// <summary> /// 多版本比较测试 /// </summary> [Fact] public void TestVER_EQ_TESTsion() { var tm = new TemplateMethod(); SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); string basePath = System.Environment.CurrentDirectory; string path = basePath + "\\templets\\default"; string content = System.IO.File.ReadAllText(path + "\\questionlist.html"); FileInfo[] assFlies = new DirectoryInfo(basePath + "\\dll").GetFiles("JinianNet.JNTemplate*.dll"); string result = DateTime.Now.ToString(); Stopwatch s = new Stopwatch(); for (int i = 0; i < assFlies.Length; i++) { Assembly ass = System.Reflection.Assembly.LoadFile(assFlies[i].FullName); object ctx = ass.CreateInstance("JinianNet.JNTemplate.TemplateContext"); object data = ctx.GetType().GetProperty("TempData").GetValue(ctx, null); MethodInfo mi = data.GetType().GetMethod("Push"); mi.Invoke(data, new object[] { "func", tm }); mi.Invoke(data, new object[] { "Site", site }); ctx.GetType().GetProperty("CurrentPath").SetValue(ctx, path, null); s.Restart(); for (int j = 0; j < MAX_RUN_COUNT; j++) { object t = ass.CreateInstance("JinianNet.JNTemplate.Template"); ; t.GetType().GetProperty("Context").SetValue(t, ctx, null); t.GetType().GetProperty("TemplateContent").SetValue(t, content, null); object r = t.GetType().GetMethod("Render", new Type[0]).Invoke(t, new object[0] { }); if (j == MAX_RUN_COUNT-1) { System.IO.File.WriteAllText(basePath + "\\result\\"+ assFlies[i].Name +".html", r.ToString()); } } s.Stop(); result += "\r\n:耗时:" + s.ElapsedMilliseconds.ToString() + "毫秒 次数:"+ MAX_RUN_COUNT + " 文件:" + assFlies[i].Name + " 版本号:" + ass.GetName().Version; System.Threading.Thread.Sleep(200); } if (System.IO.File.Exists(basePath + "\\result\\result.txt")) { if (System.IO.File.GetLastWriteTime(basePath + "\\result\\result.txt").Date == DateTime.Now.Date) { result = System.IO.File.ReadAllText(basePath + "\\result\\result.txt") + "\r\n" + result; } } System.IO.File.WriteAllText(basePath + "\\result\\result.txt", result); } #endif #if NVELOCITY_TEST [Fact] public void TestJuxtaposePage() { SiteInfo site = new SiteInfo(); site.Copyright = "&copy;2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); string basePath = System.Environment.CurrentDirectory; string path = basePath + "\\templets\\nv"; NVelocity.Context.IContext ctx = new NVelocity.VelocityContext(); ctx.Put("func", new TemplateMethod()); ctx.Put("Site", site); NVelocity.App.VelocityEngine velocity = new NVelocity.App.VelocityEngine(); Commons.Collections.ExtendedProperties props = new Commons.Collections.ExtendedProperties(); props.AddProperty(NVelocity.Runtime.RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path); props.AddProperty(NVelocity.Runtime.RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); NVelocity.Template t = velocity.GetTemplate("questionlist.html"); string result; using (System.IO.StringWriter write = new StringWriter()) { t.Merge(ctx, write); result = write.ToString(); } //可直接查看项目录下的html/nv.html 文件效果 System.IO.File.WriteAllText(basePath + "\\result\\nv.html", result); } #endif } } #endif
53.433649
6,016
0.555546
[ "MIT" ]
Zhou-zhi-peng/jntemplate
src/JinianNet.JNTemplate.Test/WebPageTests.cs
23,516
C#
using AnnoSavegameViewer.Serialization.Core; using System.Collections.Generic; namespace AnnoSavegameViewer.Structures.Savegame.Generated { public class VerticalEdgesListListOccupyTimesListTrainOwner { [BinaryContent(Name = "ObjectID", NodeType = BinaryContentTypes.Attribute)] public object ObjectID { get; set; } } }
27.833333
79
0.796407
[ "MIT" ]
brumiros/AnnoSavegameViewer
AnnoSavegameViewer/Structures/Savegame/Generated/Content/VerticalEdgesListListOccupyTimesListTrainOwner.cs
334
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; namespace ShereSoft { abstract class ClonerBase { protected static readonly MethodInfo ObjectDictionaryByObjectTryGetValueMethodInfo = typeof(Dictionary<object, object>).GetMethod("TryGetValue"); protected static readonly MethodInfo ObjectGetTypeMethodInfo = typeof(object).GetMethod("GetType"); protected static readonly MethodInfo TypeOpInequalityMethodInfo = typeof(Type).GetMethod("op_Inequality"); protected static readonly MethodInfo TypeConcurrentDictionaryByCloneObjectDelegateTryGetValueMethodInfo = typeof(ConcurrentDictionary<Type, CloneObjectDelegate>).GetMethod("TryGetValue"); protected static readonly MethodInfo TypeConcurrentDictionaryByCloneObjectDelegateTryAddMethodInfo = typeof(ConcurrentDictionary<Type, CloneObjectDelegate>).GetMethod("TryAdd"); protected static readonly MethodInfo CloneObjectDelegateInvokeMethodInfo = typeof(CloneObjectDelegate).GetMethod("Invoke"); protected static readonly MethodInfo DeepCloningBuildRedirectMethodInfo = typeof(DeepCloning).GetMethod("BuildRedirect", BindingFlags.NonPublic | BindingFlags.Static); protected static readonly MethodInfo DeepCloningOptionsGetDeepCloneSingletonsMethodInfo = typeof(DeepCloningOptions).GetProperty(nameof(DeepCloningOptions.None.DeepCloneSingletons)).GetGetMethod(); protected static readonly MethodInfo DeepCloningOptionsGetDeepCloneStringsMethodInfo = typeof(DeepCloningOptions).GetProperty(nameof(DeepCloningOptions.None.DeepCloneStrings)).GetGetMethod(); protected static readonly MethodInfo ObjectDictionaryByObjectAddMethodInfo = typeof(Dictionary<object, object>).GetMethod("Add"); protected static readonly MethodInfo StringToCharArrayMethodInfo = typeof(string).GetMethod(nameof(String.Empty.ToCharArray), Type.EmptyTypes); protected static readonly ConstructorInfo StringCtor = typeof(string).GetConstructor(new[] { typeof(char[]) }); } }
85.875
205
0.816109
[ "MIT" ]
ShereSoft/DeepCloning
src/DeepCloning/ShereSoft.DeepCloning/ClonerBase.cs
2,063
C#
namespace SampleSystem.WebApiCore.Controllers.Audit { using SampleSystem.Generated.DTO; [Microsoft.AspNetCore.Mvc.ApiControllerAttribute()] [Microsoft.AspNetCore.Mvc.ApiVersionAttribute("1.0")] [Microsoft.AspNetCore.Mvc.RouteAttribute("mainAuditApi/v{version:apiVersion}/[controller]")] public partial class BusinessUnitHrDepartmentController : Framework.DomainDriven.WebApiNetCore.ApiControllerBase<Framework.DomainDriven.ServiceModel.Service.IServiceEnvironment<SampleSystem.BLL.ISampleSystemBLLContext>, SampleSystem.BLL.ISampleSystemBLLContext, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService>> { public BusinessUnitHrDepartmentController(Framework.DomainDriven.ServiceModel.Service.IServiceEnvironment<SampleSystem.BLL.ISampleSystemBLLContext> serviceEnvironment, Framework.Exceptions.IExceptionProcessor exceptionProcessor) : base(serviceEnvironment, exceptionProcessor) { } /// <summary> /// Get BusinessUnitHrDepartment Property Revisions by period /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetBusinessUnitHrDepartmentPropertyRevisionByDateRange")] public virtual SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO GetBusinessUnitHrDepartmentPropertyRevisionByDateRange(GetBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest getBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest) { Framework.Core.Period? period = getBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest.period; string propertyName = getBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest.propertyName; SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity = getBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest.businessUnitHrDepartmentIdentity; return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetBusinessUnitHrDepartmentPropertyRevisionByDateRangeInternal(businessUnitHrDepartmentIdentity, propertyName, period, evaluateData)); } protected virtual SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO GetBusinessUnitHrDepartmentPropertyRevisionByDateRangeInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, string propertyName, Framework.Core.Period? period, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); return new Framework.DomainDriven.ServiceModel.Service.AuditService<System.Guid, SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.BLL.ISampleSystemBLLFactoryContainer, SampleSystem.BLL.ISampleSystemSecurityService, SampleSystem.SampleSystemSecurityOperationCode, SampleSystem.Domain.PersistentDomainObjectBase, SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO, SampleSystem.Generated.DTO.SampleSystemPropertyRevisionDTO>(evaluateData.Context).GetPropertyChanges<SampleSystem.Domain.BusinessUnitHrDepartment>(businessUnitHrDepartmentIdentity.Id, propertyName, period); } /// <summary> /// Get BusinessUnitHrDepartment Property Revisions /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetBusinessUnitHrDepartmentPropertyRevisions")] public virtual SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO GetBusinessUnitHrDepartmentPropertyRevisions(GetBusinessUnitHrDepartmentPropertyRevisionsAutoRequest getBusinessUnitHrDepartmentPropertyRevisionsAutoRequest) { string propertyName = getBusinessUnitHrDepartmentPropertyRevisionsAutoRequest.propertyName; SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity = getBusinessUnitHrDepartmentPropertyRevisionsAutoRequest.businessUnitHrDepartmentIdentity; return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetBusinessUnitHrDepartmentPropertyRevisionsInternal(businessUnitHrDepartmentIdentity, propertyName, evaluateData)); } protected virtual SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO GetBusinessUnitHrDepartmentPropertyRevisionsInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, string propertyName, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); return new Framework.DomainDriven.ServiceModel.Service.AuditService<System.Guid, SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.BLL.ISampleSystemBLLFactoryContainer, SampleSystem.BLL.ISampleSystemSecurityService, SampleSystem.SampleSystemSecurityOperationCode, SampleSystem.Domain.PersistentDomainObjectBase, SampleSystem.Generated.DTO.SampleSystemDomainObjectPropertiesRevisionDTO, SampleSystem.Generated.DTO.SampleSystemPropertyRevisionDTO>(evaluateData.Context).GetPropertyChanges<SampleSystem.Domain.BusinessUnitHrDepartment>(businessUnitHrDepartmentIdentity.Id, propertyName); } /// <summary> /// Get BusinessUnitHrDepartment revisions /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetBusinessUnitHrDepartmentRevisions")] public virtual Framework.DomainDriven.ServiceModel.IAD.DefaultDomainObjectRevisionDTO GetBusinessUnitHrDepartmentRevisions([Microsoft.AspNetCore.Mvc.FromBodyAttribute()] SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity) { return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetBusinessUnitHrDepartmentRevisionsInternal(businessUnitHrDepartmentIdentity, evaluateData)); } protected virtual Framework.DomainDriven.ServiceModel.IAD.DefaultDomainObjectRevisionDTO GetBusinessUnitHrDepartmentRevisionsInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); return new Framework.DomainDriven.ServiceModel.IAD.DefaultDomainObjectRevisionDTO(bll.GetObjectRevisions(businessUnitHrDepartmentIdentity.Id)); } protected override Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> GetEvaluatedData(Framework.DomainDriven.BLL.IDBSession session, SampleSystem.BLL.ISampleSystemBLLContext context) { return new Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService>(session, context, new SampleSystemServerPrimitiveDTOMappingService(context)); } /// <summary> /// Get BusinessUnitHrDepartment (FullDTO) by revision /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetFullBusinessUnitHrDepartmentWithRevision")] public virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentFullDTO GetFullBusinessUnitHrDepartmentWithRevision(GetFullBusinessUnitHrDepartmentWithRevisionAutoRequest getFullBusinessUnitHrDepartmentWithRevisionAutoRequest) { long revision = getFullBusinessUnitHrDepartmentWithRevisionAutoRequest.revision; SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity = getFullBusinessUnitHrDepartmentWithRevisionAutoRequest.businessUnitHrDepartmentIdentity; return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetFullBusinessUnitHrDepartmentWithRevisionInternal(businessUnitHrDepartmentIdentity, revision, evaluateData)); } protected virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentFullDTO GetFullBusinessUnitHrDepartmentWithRevisionInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, long revision, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); SampleSystem.Domain.BusinessUnitHrDepartment domainObject = bll.GetObjectByRevision(businessUnitHrDepartmentIdentity.Id, revision); return SampleSystem.Generated.DTO.LambdaHelper.ToFullDTO(domainObject, evaluateData.MappingService); } /// <summary> /// Get BusinessUnitHrDepartment (RichDTO) by revision /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetRichBusinessUnitHrDepartmentWithRevision")] public virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentRichDTO GetRichBusinessUnitHrDepartmentWithRevision(GetRichBusinessUnitHrDepartmentWithRevisionAutoRequest getRichBusinessUnitHrDepartmentWithRevisionAutoRequest) { long revision = getRichBusinessUnitHrDepartmentWithRevisionAutoRequest.revision; SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity = getRichBusinessUnitHrDepartmentWithRevisionAutoRequest.businessUnitHrDepartmentIdentity; return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetRichBusinessUnitHrDepartmentWithRevisionInternal(businessUnitHrDepartmentIdentity, revision, evaluateData)); } protected virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentRichDTO GetRichBusinessUnitHrDepartmentWithRevisionInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, long revision, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); SampleSystem.Domain.BusinessUnitHrDepartment domainObject = bll.GetObjectByRevision(businessUnitHrDepartmentIdentity.Id, revision); return SampleSystem.Generated.DTO.LambdaHelper.ToRichDTO(domainObject, evaluateData.MappingService); } /// <summary> /// Get BusinessUnitHrDepartment (SimpleDTO) by revision /// </summary> [Microsoft.AspNetCore.Mvc.HttpPostAttribute()] [Microsoft.AspNetCore.Mvc.RouteAttribute("GetSimpleBusinessUnitHrDepartmentWithRevision")] public virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentSimpleDTO GetSimpleBusinessUnitHrDepartmentWithRevision(GetSimpleBusinessUnitHrDepartmentWithRevisionAutoRequest getSimpleBusinessUnitHrDepartmentWithRevisionAutoRequest) { long revision = getSimpleBusinessUnitHrDepartmentWithRevisionAutoRequest.revision; SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity = getSimpleBusinessUnitHrDepartmentWithRevisionAutoRequest.businessUnitHrDepartmentIdentity; return this.Evaluate(Framework.DomainDriven.BLL.DBSessionMode.Read, evaluateData => this.GetSimpleBusinessUnitHrDepartmentWithRevisionInternal(businessUnitHrDepartmentIdentity, revision, evaluateData)); } protected virtual SampleSystem.Generated.DTO.BusinessUnitHrDepartmentSimpleDTO GetSimpleBusinessUnitHrDepartmentWithRevisionInternal(SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity, long revision, Framework.DomainDriven.ServiceModel.Service.EvaluatedData<SampleSystem.BLL.ISampleSystemBLLContext, SampleSystem.Generated.DTO.ISampleSystemDTOMappingService> evaluateData) { SampleSystem.BLL.IBusinessUnitHrDepartmentBLL bll = evaluateData.Context.Logics.BusinessUnitHrDepartmentFactory.Create(Framework.SecuritySystem.BLLSecurityMode.View); SampleSystem.Domain.BusinessUnitHrDepartment domainObject = bll.GetObjectByRevision(businessUnitHrDepartmentIdentity.Id, revision); return SampleSystem.Generated.DTO.LambdaHelper.ToSimpleDTO(domainObject, evaluateData.MappingService); } } [System.Runtime.Serialization.DataContractAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestAttribute()] public partial class GetBusinessUnitHrDepartmentPropertyRevisionByDateRangeAutoRequest { [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=0)] public SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=1)] public string propertyName; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=2)] public Framework.Core.Period? period; } [System.Runtime.Serialization.DataContractAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestAttribute()] public partial class GetBusinessUnitHrDepartmentPropertyRevisionsAutoRequest { [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=0)] public SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=1)] public string propertyName; } [System.Runtime.Serialization.DataContractAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestAttribute()] public partial class GetFullBusinessUnitHrDepartmentWithRevisionAutoRequest { [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=0)] public SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=1)] public long revision; } [System.Runtime.Serialization.DataContractAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestAttribute()] public partial class GetRichBusinessUnitHrDepartmentWithRevisionAutoRequest { [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=0)] public SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=1)] public long revision; } [System.Runtime.Serialization.DataContractAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestAttribute()] public partial class GetSimpleBusinessUnitHrDepartmentWithRevisionAutoRequest { [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=0)] public SampleSystem.Generated.DTO.BusinessUnitHrDepartmentIdentityDTO businessUnitHrDepartmentIdentity; [System.Runtime.Serialization.DataMemberAttribute()] [Framework.DomainDriven.ServiceModel.IAD.AutoRequestPropertyAttribute(OrderIndex=1)] public long revision; } }
85.801932
610
0.801813
[ "MIT" ]
Luxoft/BSSFramework
src/_SampleSystem/SampleSystem.WebApiCore/Controllers/_Generated/Audit/BusinessUnitHrDepartmentService.Generated.cs
17,557
C#
using System; namespace ChakraCore.NET.DebugAdapter2.VSCode.Managed { public class VSCodeChakraDebugger2Managed : IDisposable { private VSCodeChakraDebugger2 _nativeDebugger; public VSCodeChakraDebugger2Managed(object runtimeHandle) { _nativeDebugger = new VSCodeChakraDebugger2(runtimeHandle); } public bool IsRunning => _nativeDebugger.IsRunning; public void Start(string runtimeName, bool breakOnNextLine, int port) { _nativeDebugger.Start(runtimeName, breakOnNextLine, port); } public void Stop() { _nativeDebugger.Stop(); } public void WaitForDebugger() { _nativeDebugger.WaitForDebugger(); } public void Dispose() { _nativeDebugger.Dispose(); } } }
24.416667
77
0.608646
[ "MIT" ]
fsdsabel/ChakraCore.NET
source/ChakraCore.NET.DebugAdapter2.VSCode.Managed/VSCodeChakraDebugger2Managed.cs
881
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SCDN相关接口 * Openapi For JCLOUD cdn * * OpenAPI spec version: v1 * Contact: pid-cdn@jd.com * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Cdn.Apis { /// <summary> /// 修改指定的白名单规则 /// </summary> public class UpdateWafWhiteRuleResponse : JdcloudResponse<UpdateWafWhiteRuleResult> { } }
26
87
0.723265
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cdn/Apis/UpdateWafWhiteRuleResponse.cs
1,094
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// ResourceLimits Marshaller /// </summary> public class ResourceLimitsMarshaller : IRequestMarshaller<ResourceLimits, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(ResourceLimits requestObject, JsonMarshallerContext context) { if(requestObject.IsSetMaxNumberOfTrainingJobs()) { context.Writer.WritePropertyName("MaxNumberOfTrainingJobs"); context.Writer.Write(requestObject.MaxNumberOfTrainingJobs); } if(requestObject.IsSetMaxParallelTrainingJobs()) { context.Writer.WritePropertyName("MaxParallelTrainingJobs"); context.Writer.Write(requestObject.MaxParallelTrainingJobs); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static ResourceLimitsMarshaller Instance = new ResourceLimitsMarshaller(); } }
34.147059
107
0.683032
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/ResourceLimitsMarshaller.cs
2,322
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 Csharp_e_MYSQL.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.6
151
0.583333
[ "MIT" ]
petersonstadler/Csharp-e-MYSQL
Csharp e MYSQL/Properties/Settings.Designer.cs
1,070
C#
namespace Papagei { public interface IScopeEvaluator { bool Evaluate(Event evnt); bool Evaluate(Entity entity, int ticksSinceSend, out float priority); } public class DefaultScopeEvaluator : IScopeEvaluator { public bool Evaluate(Event evnt) { return true; } public bool Evaluate(Entity entity, int ticksSinceSend, out float priority) { priority = 0.0f; return true; } } }
21.73913
83
0.584
[ "MIT" ]
slango0513/Papagei
Papagei/IScopeEvaluator.cs
502
C#
using System; using Serilog.Formatting; using Serilog.Sinks.MSSqlServer.Output; using Serilog.Sinks.MSSqlServer.Platform; using Serilog.Sinks.MSSqlServer.Sinks.MSSqlServer.Options; namespace Serilog.Sinks.MSSqlServer.Dependencies { internal static class SinkDependenciesFactory { internal static SinkDependencies Create( string connectionString, SinkOptions sinkOptions, IFormatProvider formatProvider, ColumnOptions columnOptions, ITextFormatter logEventFormatter) { columnOptions = columnOptions ?? new ColumnOptions(); columnOptions.FinalizeConfigurationForSinkConstructor(); var sqlConnectionFactory = new SqlConnectionFactory(connectionString, sinkOptions?.UseAzureManagedIdentity ?? default, new AzureManagedServiceAuthenticator( sinkOptions?.UseAzureManagedIdentity ?? default, sinkOptions.AzureServiceTokenProviderResource)); var logEventDataGenerator = new LogEventDataGenerator(columnOptions, new StandardColumnDataGenerator(columnOptions, formatProvider, new XmlPropertyFormatter(), logEventFormatter), new PropertiesColumnDataGenerator(columnOptions)); var sinkDependencies = new SinkDependencies { SqlTableCreator = new SqlTableCreator( sinkOptions.TableName, sinkOptions.SchemaName, columnOptions, new SqlCreateTableWriter(), sqlConnectionFactory), DataTableCreator = new DataTableCreator(sinkOptions.TableName, columnOptions), SqlBulkBatchWriter = new SqlBulkBatchWriter( sinkOptions.TableName, sinkOptions.SchemaName, columnOptions.DisableTriggers, sqlConnectionFactory, logEventDataGenerator), SqlLogEventWriter = new SqlLogEventWriter( sinkOptions.TableName, sinkOptions.SchemaName, sqlConnectionFactory, logEventDataGenerator) }; return sinkDependencies; } } }
43.634615
96
0.639929
[ "Apache-2.0" ]
stedel/serilog-sinks-mssqlserver
src/Serilog.Sinks.MSSqlServer/Sinks/MSSqlServer/Dependencies/SinkDependenciesFactory.cs
2,271
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unicode_example { class Program { static void Main(string[] args) { char unicode = '\u0023'; // # Console.WriteLine(unicode); } } }
16.894737
41
0.604361
[ "MIT" ]
SimeonShterev/2016.12.10-2017.03.23-ProgramingBasics
2017.01 - function examples from the book/Unicode example/Program.cs
323
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent { using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent; using Microsoft.Azure.Management.Msi.Fluent; using Models; using Network.Fluent; using ResourceManager.Fluent; using ResourceManager.Fluent.Core; using ResourceManager.Fluent.Core.ResourceActions; using Storage.Fluent; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using VirtualMachineScaleSet.DefinitionManaged; using VirtualMachineScaleSet.DefinitionManagedOrUnmanaged; using VirtualMachineScaleSet.DefinitionUnmanaged; using VirtualMachineScaleSet.Update; /// <summary> /// Implementation of VirtualMachineScaleSet. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVTY2FsZVNldEltcGw= internal partial class VirtualMachineScaleSetImpl : GroupableParentResource<IVirtualMachineScaleSet, Models.VirtualMachineScaleSetInner, VirtualMachineScaleSetImpl, IComputeManager, VirtualMachineScaleSet.Definition.IWithGroup, VirtualMachineScaleSet.Definition.IWithSku, VirtualMachineScaleSet.Definition.IWithCreate, VirtualMachineScaleSet.Update.IWithApply>, IVirtualMachineScaleSet, IDefinitionManagedOrUnmanaged, IDefinitionManaged, IDefinitionUnmanaged, IUpdate, VirtualMachineScaleSet.Definition.IWithSystemAssignedIdentityBasedAccessOrCreate, VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply { // Clients private IStorageManager storageManager; private INetworkManager networkManager; private IGraphRbacManager rbacManager; // used to generate unique name for any dependency resources private IResourceNamer namer; private bool isMarketplaceLinuxImage = false; // name of an existing subnet in the primary network to use private string existingPrimaryNetworkSubnetNameToAssociate; // unique key of a creatable storage accounts to be used for virtual machines child resources that // requires storage [OS disk] private List<string> creatableStorageAccountKeys = new List<string>(); // reference to an existing storage account to be used for virtual machines child resources that // requires storage [OS disk] private List<IStorageAccount> existingStorageAccountsToAssociate = new List<IStorageAccount>(); // Name of the container in the storage account to use to store the disks private string vhdContainerName; // the child resource extensions private IDictionary<string, IVirtualMachineScaleSetExtension> extensions; // reference to the primary and internal internet facing load balancer private ILoadBalancer primaryInternetFacingLoadBalancer; private ILoadBalancer primaryInternalLoadBalancer; // Load balancer specific variables used during update private bool removePrimaryInternetFacingLoadBalancerOnUpdate; private bool removePrimaryInternalLoadBalancerOnUpdate; private ILoadBalancer primaryInternetFacingLoadBalancerToAttachOnUpdate; private ILoadBalancer primaryInternalLoadBalancerToAttachOnUpdate; private List<string> primaryInternetFacingLBBackendsToRemoveOnUpdate = new List<string>(); private List<string> primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate = new List<string>(); private List<string> primaryInternalLBBackendsToRemoveOnUpdate = new List<string>(); private List<string> primaryInternalLBInboundNatPoolsToRemoveOnUpdate = new List<string>(); private List<string> primaryInternetFacingLBBackendsToAddOnUpdate = new List<string>(); private List<string> primaryInternetFacingLBInboundNatPoolsToAddOnUpdate = new List<string>(); private List<string> primaryInternalLBBackendsToAddOnUpdate = new List<string>(); private List<string> primaryInternalLBInboundNatPoolsToAddOnUpdate = new List<string>(); private bool isUnmanagedDiskSelected; private ManagedDataDiskCollection managedDataDisks; private VirtualMachineScaleSetMsiHelper virtualMachineScaleSetMsiHelper; // To manage boot diagnostics specific operations private BootDiagnosticsHandler bootDiagnosticsHandler; // Name of the new proximity placement group private String newProximityPlacementGroupName; // Type fo the new proximity placement group private ProximityPlacementGroupType newProximityPlacementGroupType; ///GENMHASH:F0C80BE7722CB6620CCF10F060FE486B:C5CB976F0B76FD0A094017AD226F4439 internal VirtualMachineScaleSetImpl( string name, VirtualMachineScaleSetInner innerModel, IComputeManager computeManager, IStorageManager storageManager, INetworkManager networkManager, IGraphRbacManager rbacManager) : base(name, innerModel, computeManager) { this.storageManager = storageManager; this.networkManager = networkManager; this.rbacManager = rbacManager; this.namer = SdkContext.CreateResourceNamer(this.Name); this.managedDataDisks = new ManagedDataDiskCollection(this); this.virtualMachineScaleSetMsiHelper = new VirtualMachineScaleSetMsiHelper(rbacManager, this); this.bootDiagnosticsHandler = new BootDiagnosticsHandler(this); this.newProximityPlacementGroupName = null; this.newProximityPlacementGroupType = null; } private VirtualMachineScaleSetUpdate PreparePatchPayload() { var updateParameter = new VirtualMachineScaleSetUpdate { Identity = this.Inner.Identity, Overprovision = this.Inner.Overprovision, Plan = this.Inner.Plan, SinglePlacementGroup = this.Inner.SinglePlacementGroup, Sku = this.Inner.Sku, Tags = this.Inner.Tags, UpgradePolicy = this.Inner.UpgradePolicy, AdditionalCapabilities = this.Inner.AdditionalCapabilities }; if (this.Inner.VirtualMachineProfile != null) { // -- var updateVMProfile = new VirtualMachineScaleSetUpdateVMProfile { DiagnosticsProfile = this.Inner.VirtualMachineProfile.DiagnosticsProfile, ExtensionProfile = this.Inner.VirtualMachineProfile.ExtensionProfile, LicenseType = this.Inner.VirtualMachineProfile.LicenseType, BillingProfile = this.Inner.VirtualMachineProfile.BillingProfile }; // if (this.Inner.VirtualMachineProfile.StorageProfile != null) { // -- -- var storageProfile = new VirtualMachineScaleSetUpdateStorageProfile { DataDisks = this.Inner.VirtualMachineProfile.StorageProfile.DataDisks, ImageReference = this.Inner.VirtualMachineProfile.StorageProfile.ImageReference }; if (this.Inner.VirtualMachineProfile.StorageProfile.OsDisk != null) { var osDisk = new VirtualMachineScaleSetUpdateOSDisk { Caching = this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.Caching, Image = this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.Image, ManagedDisk = this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk, VhdContainers = this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers, WriteAcceleratorEnabled = this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.WriteAcceleratorEnabled }; storageProfile.OsDisk = osDisk; } updateVMProfile.StorageProfile = storageProfile; // -- -- } if (this.Inner.VirtualMachineProfile.OsProfile != null) { // -- -- var osProfile = new VirtualMachineScaleSetUpdateOSProfile { CustomData = this.Inner.VirtualMachineProfile.OsProfile.CustomData, LinuxConfiguration = this.Inner.VirtualMachineProfile.OsProfile.LinuxConfiguration, Secrets = this.Inner.VirtualMachineProfile.OsProfile.Secrets, WindowsConfiguration = this.Inner.VirtualMachineProfile.OsProfile.WindowsConfiguration }; updateVMProfile.OsProfile = osProfile; // -- -- } if (this.Inner.VirtualMachineProfile.NetworkProfile != null) { // -- -- var networkProfile = new VirtualMachineScaleSetUpdateNetworkProfile(); if (this.Inner.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations != null) { networkProfile.NetworkInterfaceConfigurations = new List<VirtualMachineScaleSetUpdateNetworkConfigurationInner>(); foreach (var nicConfig in this.Inner.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations) { var nicPatchConfig = new VirtualMachineScaleSetUpdateNetworkConfigurationInner { DnsSettings = nicConfig.DnsSettings, EnableAcceleratedNetworking = nicConfig.EnableAcceleratedNetworking, EnableIPForwarding = nicConfig.EnableIPForwarding, Name = nicConfig.Name, NetworkSecurityGroup = nicConfig.NetworkSecurityGroup, Primary = nicConfig.Primary, Id = nicConfig.Id }; if (nicConfig.IpConfigurations != null) { nicPatchConfig.IpConfigurations = new List<VirtualMachineScaleSetUpdateIPConfigurationInner>(); foreach (var ipConfig in nicConfig.IpConfigurations) { var patchIpConfig = new VirtualMachineScaleSetUpdateIPConfigurationInner { ApplicationGatewayBackendAddressPools = ipConfig.ApplicationGatewayBackendAddressPools, LoadBalancerBackendAddressPools = ipConfig.LoadBalancerBackendAddressPools, LoadBalancerInboundNatPools = ipConfig.LoadBalancerInboundNatPools, Name = ipConfig.Name, Primary = ipConfig.Primary, PrivateIPAddressVersion = ipConfig.PrivateIPAddressVersion, Subnet = ipConfig.Subnet, Id = ipConfig.Id }; if (ipConfig.PublicIPAddressConfiguration != null) { patchIpConfig.PublicIPAddressConfiguration = new VirtualMachineScaleSetUpdatePublicIPAddressConfiguration() { DnsSettings = ipConfig.PublicIPAddressConfiguration.DnsSettings, IdleTimeoutInMinutes = ipConfig.PublicIPAddressConfiguration.IdleTimeoutInMinutes, Name = ipConfig.PublicIPAddressConfiguration.Name }; } if (ipConfig.ApplicationSecurityGroups != null) { patchIpConfig.ApplicationSecurityGroups = new List<SubResource>(); foreach (var asg in ipConfig.ApplicationSecurityGroups) { patchIpConfig.ApplicationSecurityGroups.Add(new SubResource { Id = asg.Id }); } } nicPatchConfig.IpConfigurations.Add(patchIpConfig); } } networkProfile.NetworkInterfaceConfigurations.Add(nicPatchConfig); } } updateVMProfile.NetworkProfile = networkProfile; // -- -- } updateParameter.VirtualMachineProfile = updateVMProfile; // -- } // return updateParameter; } public IReadOnlyList<string> ApplicationGatewayBackendAddressPoolsIds() { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); var backendPools = nicIpConfig.ApplicationGatewayBackendAddressPools; if (backendPools != null) { return backendPools.Select(bp => bp.Id).ToList(); } return new List<string>(); } public IReadOnlyList<string> ApplicationSecurityGroupIds() { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.ApplicationSecurityGroups != null) { return nicIpConfig.ApplicationSecurityGroups.Select(asg => asg.Id).ToList(); } return new List<string>(); } public bool? DoNotRunExtensionsOnOverprovisionedVMs() { return this.Inner.DoNotRunExtensionsOnOverprovisionedVMs; } public IProximityPlacementGroup ProximityPlacementGroup() { if (Inner.ProximityPlacementGroup == null) { return null; } ResourceId id = ResourceId.FromString(Inner.ProximityPlacementGroup.Id); ProximityPlacementGroupInner plgInner = Microsoft.Azure.Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Manager.Inner.ProximityPlacementGroups.GetAsync(this.ResourceGroupName, id.Name)); if (plgInner == null) { return null; } else { return new ProximityPlacementGroupImpl(plgInner); } } public AdditionalCapabilities AdditionalCapabilities() { return this.Inner.AdditionalCapabilities; } public bool IsAcceleratedNetworkingEnabled() { var nicConfig = PrimaryNicConfiguration(); if (nicConfig.EnableAcceleratedNetworking != null) { return nicConfig.EnableAcceleratedNetworking.Value; } return false; } public bool IsIpForwardingEnabled() { var nicConfig = PrimaryNicConfiguration(); if (nicConfig.EnableIPForwarding != null) { return nicConfig.EnableIPForwarding.Value; } return false; } private VirtualMachineScaleSetNetworkConfigurationInner PrimaryNicConfiguration() { var nicConfigurations = this.Inner?.VirtualMachineProfile?.NetworkProfile?.NetworkInterfaceConfigurations; if (nicConfigurations != null) { foreach (var nicConfiguration in nicConfigurations) { if (nicConfiguration.Primary != null && nicConfiguration.Primary.Value) { return nicConfiguration; } } } throw new InvalidOperationException("Could not find the primary nic configuration"); } public bool IsSinglePlacementGroupEnabled() { if (this.Inner.SinglePlacementGroup != null) { return this.Inner.SinglePlacementGroup.Value; } return false; } public string NetworkSecurityGroupId() { var nicConfig = PrimaryNicConfiguration(); if (nicConfig.NetworkSecurityGroup != null) { return nicConfig.NetworkSecurityGroup.Id; } return null; } public VirtualMachineScaleSetPublicIPAddressConfiguration VirtualMachinePublicIpConfig() { var nicConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicConfig != null) { return nicConfig.PublicIPAddressConfiguration; } return null; } public RunCommandResultInner RunCommandInVMInstance(string vmId, RunCommandInput inputCommand) { return Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => RunCommandVMInstanceAsync(vmId, inputCommand)); } public async Task<Models.RunCommandResultInner> RunCommandVMInstanceAsync(string vmId, RunCommandInput inputCommand, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachineScaleSets.RunCommandVMInstanceAsync(this.ResourceGroupName, this.Name, vmId, inputCommand, cancellationToken); } public RunCommandResultInner RunPowerShellScriptInVMInstance(string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => RunPowerShellScriptInVMInstanceAsync(vmId, scriptLines, scriptParameters)); } public async Task<Models.RunCommandResultInner> RunPowerShellScriptInVMInstanceAsync(string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachineScaleSets.RunPowerShellScriptInVMInstanceAsync(this.ResourceGroupName, this.Name, vmId, scriptLines, scriptParameters, cancellationToken); } public RunCommandResultInner RunShellScriptInVMInstance(string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => RunShellScriptInVMInstanceAsync(vmId, scriptLines, scriptParameters)); } public async Task<Models.RunCommandResultInner> RunShellScriptInVMInstanceAsync(string vmId, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken = default(CancellationToken)) { return await this.Manager.VirtualMachineScaleSets.RunShellScriptInVMInstanceAsync(this.ResourceGroupName, this.Name, vmId, scriptLines, scriptParameters, cancellationToken); } public VirtualMachineScaleSetImpl WithAcceleratedNetworking() { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.EnableAcceleratedNetworking = true; return this; } public VirtualMachineScaleSetImpl WithExistingApplicationGatewayBackendPool(string backendPoolId) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.ApplicationGatewayBackendAddressPools == null) { nicIpConfig.ApplicationGatewayBackendAddressPools = new List<SubResource>(); } bool found = false; foreach (var backendPool in nicIpConfig.ApplicationGatewayBackendAddressPools) { if (backendPool.Id.Equals(backendPoolId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { nicIpConfig.ApplicationGatewayBackendAddressPools.Add(new SubResource { Id = backendPoolId }); } return this; } public VirtualMachineScaleSetImpl WithExistingApplicationSecurityGroup(IApplicationSecurityGroup applicationSecurityGroup) { return WithExistingApplicationSecurityGroupId(applicationSecurityGroup.Id); } public VirtualMachineScaleSetImpl WithExistingApplicationSecurityGroupId(string applicationSecurityGroupId) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.ApplicationSecurityGroups == null) { nicIpConfig.ApplicationSecurityGroups = new List<SubResource>(); } bool found = false; foreach (var asg in nicIpConfig.ApplicationSecurityGroups) { if (asg.Id.Equals(applicationSecurityGroupId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { nicIpConfig.ApplicationSecurityGroups.Add(new SubResource { Id = applicationSecurityGroupId }); } return this; } public VirtualMachineScaleSetImpl WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup) { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.NetworkSecurityGroup = new SubResource { Id = networkSecurityGroup.Id }; return this; } public VirtualMachineScaleSetImpl WithExistingNetworkSecurityGroupId(string networkSecurityGroupId) { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.NetworkSecurityGroup = new SubResource { Id = networkSecurityGroupId }; return this; } public VirtualMachineScaleSetImpl WithIpForwarding() { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.EnableIPForwarding = true; return this; } public VirtualMachineScaleSetImpl WithoutAcceleratedNetworking() { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.EnableAcceleratedNetworking = false; return this; } public VirtualMachineScaleSetImpl WithoutApplicationGatewayBackendPool(string backendPoolId) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.ApplicationGatewayBackendAddressPools == null) { return this; } int foundIndex = -1; int index = -1; foreach (var backendPool in nicIpConfig.ApplicationGatewayBackendAddressPools) { index = index + 1; if (backendPool.Id.Equals(backendPoolId, StringComparison.OrdinalIgnoreCase)) { foundIndex = index; break; } } if (foundIndex != -1) { nicIpConfig.ApplicationGatewayBackendAddressPools.RemoveAt(foundIndex); } return this; } public VirtualMachineScaleSetImpl WithoutApplicationSecurityGroup(string applicationSecurityGroupId) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.ApplicationSecurityGroups == null) { return this; } int foundIndex = -1; int index = -1; foreach (var asg in nicIpConfig.ApplicationSecurityGroups) { index = index + 1; if (asg.Id.Equals(applicationSecurityGroupId, StringComparison.OrdinalIgnoreCase)) { foundIndex = index; break; } } if (foundIndex != -1) { nicIpConfig.ApplicationSecurityGroups.RemoveAt(foundIndex); } return this; } public VirtualMachineScaleSetImpl WithoutIpForwarding() { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.EnableIPForwarding = false; return this; } public VirtualMachineScaleSetImpl WithoutNetworkSecurityGroup() { var nicConfig = this.PrimaryNicConfiguration(); nicConfig.NetworkSecurityGroup = null; return this; } public VirtualMachineScaleSetImpl WithoutSinglePlacementGroup() { this.Inner.SinglePlacementGroup = false; return this; } public VirtualMachineScaleSetImpl WithSinglePlacementGroup() { this.Inner.SinglePlacementGroup = true; return this; } public VirtualMachineScaleSetImpl WithVirtualMachinePublicIp() { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.PublicIPAddressConfiguration != null) { return this; } var pipConfig = new VirtualMachineScaleSetPublicIPAddressConfiguration(); pipConfig.Name = "pip1"; pipConfig.IdleTimeoutInMinutes = 15; // nicIpConfig.PublicIPAddressConfiguration = pipConfig; return this; } public VirtualMachineScaleSetImpl WithVirtualMachinePublicIp(string leafDomainLabel) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); if (nicIpConfig.PublicIPAddressConfiguration != null) { if (nicIpConfig.PublicIPAddressConfiguration.DnsSettings != null) { nicIpConfig.PublicIPAddressConfiguration.DnsSettings.DomainNameLabel = leafDomainLabel; } else { nicIpConfig.PublicIPAddressConfiguration.DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings(); nicIpConfig.PublicIPAddressConfiguration.DnsSettings.DomainNameLabel = leafDomainLabel; } } else { var pipConfig = new VirtualMachineScaleSetPublicIPAddressConfiguration { Name = "pip1", IdleTimeoutInMinutes = 15, DnsSettings = new VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings { DomainNameLabel = leafDomainLabel } }; nicIpConfig.PublicIPAddressConfiguration = pipConfig; } return this; } public VirtualMachineScaleSetImpl WithVirtualMachinePublicIp(VirtualMachineScaleSetPublicIPAddressConfiguration pipConfig) { var nicIpConfig = this.PrimaryNicDefaultIPConfiguration(); nicIpConfig.PublicIPAddressConfiguration = pipConfig; return this; } public VirtualMachineScaleSetImpl WithoutSystemAssignedManagedServiceIdentity() { this.virtualMachineScaleSetMsiHelper.WithoutLocalManagedServiceIdentity(); return this; } ///GENMHASH:AAC1F72971316317A21BEC14F977DEDE:ABC059395726B5D6BEB36206C2DDA144 public VirtualMachineScaleSetImpl WithPrimaryInternetFacingLoadBalancerBackends(params string[] backendNames) { if (this.IsInCreateMode) { VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIPConfig = this.PrimaryNicDefaultIPConfiguration(); RemoveAllBackendAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancer, defaultPrimaryIPConfig); AssociateBackEndsToIPConfiguration(this.primaryInternetFacingLoadBalancer.Id, defaultPrimaryIPConfig, backendNames); } else { AddToList(this.primaryInternetFacingLBBackendsToAddOnUpdate, backendNames); } return this; } ///GENMHASH:42E5559F93A5ECA057CA5F045A1C8057:C9C1A747426C7D8AEF7280B613F858AE public IEnumerable<IVirtualMachineScaleSetNetworkInterface> ListNetworkInterfacesByInstanceId(string virtualMachineInstanceId) { return this.networkManager.NetworkInterfaces.ListByVirtualMachineScaleSetInstanceId(this.ResourceGroupName, this.Name, virtualMachineInstanceId); } ///GENMHASH:99E12A9D1F6C67E6350163C75A02C0CF:EB015A0D5BB20773EED2BA22F09DBFE4 private static void RemoveLoadBalancerAssociationFromIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { RemoveAllBackendAssociationFromIPConfiguration(loadBalancer, ipConfig); RemoveAllInboundNatPoolAssociationFromIPConfiguration(loadBalancer, ipConfig); } ///GENMHASH:0B86CB1DFA370E0EF503AA943BA12699:72153688799C022C061CCB2A43E36DC0 public VirtualMachineScaleSetImpl WithoutPrimaryInternetFacingLoadBalancer() { if (this.IsInUpdateMode()) { this.removePrimaryInternetFacingLoadBalancerOnUpdate = true; } return this; } ///GENMHASH:8761D0D225B7C49A7A5025186E94B263:21AAF0008CE6CF3F9846F2DFE1CBEBCB public void PowerOff() { Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.PowerOffAsync(ResourceGroupName, Name)); } public async Task PowerOffAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachineScaleSets.PowerOffAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:976BC0FCB9812014FA27474FCF6A694F:51AD565B2270FC1F9104F1A5BC632E24 public VirtualMachineScaleSetImpl WithStoredLinuxImage(string imageUrl) { VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.Uri = imageUrl; Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.OsDisk.Image = userImageVhd; // For platform image osType will be null, azure will pick it from the image metadata. Inner .VirtualMachineProfile .StorageProfile.OsDisk.OsType = OperatingSystemTypes.Linux; Inner .VirtualMachineProfile .OsProfile.LinuxConfiguration = new LinuxConfiguration(); return this; } ///GENMHASH:667E734583F577A898C6389A3D9F4C09:B1A3725E3B60B26D7F37CA7ABFE371B0 public void Deallocate() { Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.DeallocateAsync(this.ResourceGroupName, this.Name)); Refresh(); } public async Task DeallocateAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachineScaleSets.DeallocateAsync(this.ResourceGroupName, this.Name, cancellationToken: cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:5C1E5D4B34E988B57615D99543B65A28:FA6DEF6159D987B906C75A28496BD099 public VirtualMachineScaleSetImpl WithOSDiskCaching(CachingTypes cachingType) { Inner .VirtualMachineProfile .StorageProfile.OsDisk.Caching = cachingType; return this; } ///GENMHASH:C8D0FD360C8F8A611F6F85F99CDE83D0:C73CD8C0F99ACCAB4E6C5579E1D974E4 private static void RemoveAllInboundNatPoolAssociationFromIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { List<SubResource> toRemove = new List<SubResource>(); foreach (SubResource subResource in ipConfig.LoadBalancerInboundNatPools) { if (subResource.Id.ToLower().StartsWith(loadBalancer.Id.ToLower() + "/")) { toRemove.Add(subResource); } } foreach (SubResource subResource in toRemove) { ipConfig.LoadBalancerInboundNatPools.Remove(subResource); } } ///GENMHASH:FD824AC9D26C404162A9EEEE0B9A4489:B9DC6752667EC750602BB3CBA2F9F1A0 public VirtualMachineScaleSetImpl WithPrimaryInternetFacingLoadBalancerInboundNatPools(params string[] natPoolNames) { if (this.IsInCreateMode) { VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIPConfig = this.PrimaryNicDefaultIPConfiguration(); RemoveAllInboundNatPoolAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancer, defaultPrimaryIPConfig); AssociateInboundNatPoolsToIPConfiguration(this.primaryInternetFacingLoadBalancer.Id, defaultPrimaryIPConfig, natPoolNames); } else { AddToList(this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate, natPoolNames); } return this; } ///GENMHASH:2E38406EB22698CAE339875C7D4BDD7E:258FD1D5537E0DC025DC120D7BC231E2 internal VirtualMachineScaleSetImpl WithUnmanagedDataDisk(VirtualMachineScaleSetUnmanagedDataDiskImpl unmanagedDisk) { if (Inner.VirtualMachineProfile.StorageProfile.DataDisks == null) { Inner .VirtualMachineProfile .StorageProfile .DataDisks = new List<VirtualMachineScaleSetDataDisk>(); } IList<VirtualMachineScaleSetDataDisk> dataDisks = Inner .VirtualMachineProfile .StorageProfile .DataDisks; dataDisks.Add(unmanagedDisk.Inner); return this; } ///GENMHASH:123FF0223083F789E78E45771A759A9C:FFF894943EBDE56EEC0675ADF0891867 public CachingTypes OSDiskCachingType() { return Inner.VirtualMachineProfile.StorageProfile.OsDisk.Caching.Value; } ///GENMHASH:C5EB453493B1100152604C49B4350246:13A96702474EC693EFE5444489CDEDCC public VirtualMachineScaleSetImpl WithOSDiskName(string name) { Inner .VirtualMachineProfile .StorageProfile.OsDisk.Name = name; return this; } ///GENMHASH:F792F6C8C594AA68FA7A0FCA92F55B55:CEAEE81352B41505EB71BF5E42D2A3B6 public VirtualMachineScaleSetSkuTypes Sku() { return VirtualMachineScaleSetSkuTypes.FromSku(Inner.Sku); } ///GENMHASH:B2876749E60D892750D75C97943BBB13:00E375F5DFA1F92EE59D32432D8BB9AD public VirtualMachineScaleSetImpl WithSpecificLinuxImageVersion(ImageReference imageReference) { Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.ImageReference = imageReference.Inner; Inner .VirtualMachineProfile .OsProfile.LinuxConfiguration = new LinuxConfiguration(); this.isMarketplaceLinuxImage = true; return this; } ///GENMHASH:1E53238DF79E665335390B7452E9A04C:341F8A896942EC0102DC34824A8AED9B public VirtualMachineScaleSetImpl WithoutExtension(string name) { if (this.extensions.ContainsKey(name)) { this.extensions.Remove(name); } return this; } /// <summary> /// Checks whether the OS disk is based on a stored image ('captured' or 'bring your own feature'). /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to use custom image ('captured' or 'bring your own feature').</return> ///GENMHASH:013BB4FB645C080F536E8E117C28F1AD:B153E6EE63AB77BCE2C751BD7243E659 private bool IsOSDiskFromStoredImage(VirtualMachineScaleSetStorageProfile storageProfile) { VirtualMachineScaleSetOSDisk osDisk = storageProfile.OsDisk; return IsOSDiskFromImage(osDisk) && osDisk.Image != null && osDisk.Image.Uri != null; } ///GENMHASH:E7610DABE1E75344D9E0DBC0332E7F96:92F04FC0178BF91F20DF542F454DC302 public VirtualMachineScaleSetExtensionImpl UpdateExtension(string name) { IVirtualMachineScaleSetExtension value = null; if (!this.extensions.TryGetValue(name, out value)) { throw new ArgumentException("Extension with name '" + name + "' not found"); } return (VirtualMachineScaleSetExtensionImpl)value; } ///GENMHASH:F16446581B25DFD00E74CB1193EBF605:438AB79E7DABFF084F3F25050C0B0DCB public VirtualMachineScaleSetImpl WithoutVMAgent() { Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.ProvisionVMAgent = true; return this; } ///GENMHASH:ACFF159DD59B63FA783C8B3D4A7A36F5:86B1B0C90A3820575D5746DAF454199B public VirtualMachineScaleSetImpl WithExistingPrimaryNetworkSubnet(INetwork network, string subnetName) { this.existingPrimaryNetworkSubnetNameToAssociate = MergePath(network.Id, "subnets", subnetName); return this; } ///GENMHASH:C7EEDB0D031020E6FE0ADF5003AD9EF3:08412BF58A15F18D9122928A38242D9E public VirtualMachineScaleSetImpl WithoutPrimaryInternalLoadBalancer() { if (this.IsInUpdateMode()) { this.removePrimaryInternalLoadBalancerOnUpdate = true; } return this; } ///GENMHASH:6E6D232E3678D03B3716EA09F0ADD0A9:660BA6BD38564D432FD56906D5F71954 private static void RemoveBackendsFromIPConfiguration(string loadBalancerId, VirtualMachineScaleSetIPConfigurationInner ipConfig, params string[] backendNames) { List<SubResource> toRemove = new List<SubResource>(); foreach (string backendName in backendNames) { string backendPoolId = MergePath(loadBalancerId, "backendAddressPools", backendName); foreach (SubResource subResource in ipConfig.LoadBalancerBackendAddressPools) { if (subResource.Id.Equals(backendPoolId, StringComparison.OrdinalIgnoreCase)) { toRemove.Add(subResource); break; } } } foreach (SubResource subResource in toRemove) { ipConfig.LoadBalancerBackendAddressPools.Remove(subResource); } } /// <summary> /// Checks whether the OS disk is based on an platform image (image in PIR). /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to be based on platform image.</return> ///GENMHASH:B4160179254ABD9C885CF5B824F69A10:8A0B58C5E0133CF29412CD658BAF8289 private bool IsOSDiskFromPlatformImage(VirtualMachineScaleSetStorageProfile storageProfile) { ImageReferenceInner imageReference = storageProfile.ImageReference; return IsOSDiskFromImage(storageProfile.OsDisk) && imageReference != null && imageReference.Publisher != null && imageReference.Offer != null && imageReference.Sku != null && imageReference.Version != null; } ///GENMHASH:CD7DD8B4BD138F5F21FC2A082781B05E:DF7F973BA6DA44DB874A039E8656D907 private void ThrowIfManagedDiskDisabled(string message) { if (!this.IsManagedDiskEnabled()) { throw new NotSupportedException(message); } } ///GENMHASH:EC363135C0A3366C1FA98226F4AE5D05:894AACC37E5DFF8EECFF47C4ACFBFB70 public IReadOnlyDictionary<string, Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension> Extensions() { return this.extensions as IReadOnlyDictionary<string, Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSetExtension>; } ///GENMHASH:EB45314951D6F0A225DF2E0CC4444647:31CE7DD3ED015A2C03AF72E95A38202E internal VirtualMachineScaleSetImpl WithExtension(VirtualMachineScaleSetExtensionImpl extension) { this.extensions.Add(extension.Name(), extension); return this; } ///GENMHASH:85147EF10797D4C57F7D765BDFEAE89E:65DEB6D772EFEFA23B2E9C18CCAB48DC public IReadOnlyList<string> PrimaryPublicIPAddressIds() { ILoadBalancer loadBalancer = (this as Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet).GetPrimaryInternetFacingLoadBalancer(); if (loadBalancer != null) { return loadBalancer.PublicIPAddressIds; } return new List<string>(); } /// <summary> /// Checks whether the OS disk is based on an image (image from PIR or custom image [captured, bringYourOwnFeature]). /// </summary> /// <param name="osDisk">The osDisk value in the storage profile.</param> /// <return>True if the OS disk is configured to use image from PIR or custom image.</return> ///GENMHASH:B97D8C3B1AC557A077AC173B1DB0B348:4CD85EE98AD4F7CBC33994D722986AE5 private bool IsOSDiskFromImage(VirtualMachineScaleSetOSDisk osDisk) { return osDisk.CreateOption == DiskCreateOptionTypes.FromImage; } public UpgradeMode UpgradeMode() { return (Inner.UpgradePolicy != null) ? Inner.UpgradePolicy.Mode.Value : Microsoft.Azure.Management.Compute.Fluent.Models.UpgradeMode.Automatic; } ///GENMHASH:B56D58DDB3B4EFB6D2FB8BFF6488E3FF:48A72DF34AA591EEC3FD96876F4C2258 public IEnumerable<IVirtualMachineScaleSetNetworkInterface> ListNetworkInterfaces() { return this.networkManager.NetworkInterfaces.ListByVirtualMachineScaleSet(this.ResourceGroupName, this.Name); } ///GENMHASH:ADE83EE6665AFEEF1CA076067FC2BAB1:901C9A9B6E5CC49CB120EDA00E46E94E public IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerInboundNatPool> ListPrimaryInternalLoadBalancerInboundNatPools() { if ((this as Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet).GetPrimaryInternalLoadBalancer() != null) { return GetInboundNatPoolsAssociatedWithIPConfiguration(this.primaryInternalLoadBalancer, PrimaryNicDefaultIPConfiguration()); } return new Dictionary<string, ILoadBalancerInboundNatPool>(); } ///GENMHASH:F0B439C5B2A4923B3B36B77503386DA7:B38C06867B5D878680004A07BD077546 public int Capacity() { return (int)Inner.Sku.Capacity.Value; } ///GENMHASH:5357697C243DBDD2060BF2C164461C10:CCFD65A9998AF06471C50E7F44A70A67 public VirtualMachineScaleSetImpl WithExistingPrimaryInternetFacingLoadBalancer(ILoadBalancer loadBalancer) { if (loadBalancer.PublicIPAddressIds.Count == 0) { throw new ArgumentException("Parameter loadBalancer must be an internet facing load balancer"); } if (this.IsInCreateMode) { this.primaryInternetFacingLoadBalancer = loadBalancer; AssociateLoadBalancerToIPConfiguration(this.primaryInternetFacingLoadBalancer, this.PrimaryNicDefaultIPConfiguration()); } else { this.primaryInternetFacingLoadBalancerToAttachOnUpdate = loadBalancer; } return this; } ///GENMHASH:D7A14F2EFF1E4165DA55EF07B6C19534:7212B561D81BB0678D70A3F6EF38FA07 public VirtualMachineScaleSetExtensionImpl DefineNewExtension(string name) { return new VirtualMachineScaleSetExtensionImpl(new Models.VirtualMachineScaleSetExtensionInner { Name = name }, this); } ///GENMHASH:F2FFAF5448D7DFAFBE00130C62E87053:F7407CEA3D12779F169A4F2984ACFC2B public VirtualMachineScaleSetImpl WithRootPassword(string password) { Inner .VirtualMachineProfile .OsProfile .AdminPassword = password; return this; } /// <summary> /// Checks whether the OS disk is based on a CustomImage. /// A custom image is represented by com.microsoft.azure.management.compute.VirtualMachineCustomImage. /// </summary> /// <param name="storageProfile">The storage profile.</param> /// <return>True if the OS disk is configured to be based on custom image.</return> ///GENMHASH:F53D85CC99C2482FBAB2FEB42F5A129A:F979E27E10A5C3D262E33101E3EF232A private bool IsOsDiskFromCustomImage(VirtualMachineScaleSetStorageProfile storageProfile) { ImageReferenceInner imageReference = storageProfile.ImageReference; return IsOSDiskFromImage(storageProfile.OsDisk) && imageReference != null && imageReference.Id != null; } ///GENMHASH:0ACBCB3C1F81BA37F134262122B79DA2:A4F154B483C36885CF45861AA9C1885F private void LoadCurrentPrimaryLoadBalancersIfAvailable() { if (this.primaryInternetFacingLoadBalancer != null && this.primaryInternalLoadBalancer != null) { return; } string firstLoadBalancerId = null; VirtualMachineScaleSetIPConfigurationInner ipConfig = PrimaryNicDefaultIPConfiguration(); if (ipConfig.LoadBalancerBackendAddressPools.Count > 0) { firstLoadBalancerId = ResourceUtils .ParentResourcePathFromResourceId(ipConfig.LoadBalancerBackendAddressPools.ElementAt(0).Id); } if (firstLoadBalancerId == null && ipConfig.LoadBalancerInboundNatPools.Count > 0) { firstLoadBalancerId = ResourceUtils .ParentResourcePathFromResourceId(ipConfig.LoadBalancerInboundNatPools.ElementAt(0).Id); } if (firstLoadBalancerId == null) { return; } ILoadBalancer loadBalancer1 = this.networkManager .LoadBalancers .GetById(firstLoadBalancerId); if (loadBalancer1.PublicIPAddressIds != null && loadBalancer1.PublicIPAddressIds.Count > 0) { this.primaryInternetFacingLoadBalancer = loadBalancer1; } else { this.primaryInternalLoadBalancer = loadBalancer1; } string secondLoadBalancerId = null; foreach (SubResource subResource in ipConfig.LoadBalancerBackendAddressPools) { if (!subResource.Id.ToLower().StartsWith(firstLoadBalancerId.ToLower())) { secondLoadBalancerId = ResourceUtils .ParentResourcePathFromResourceId(subResource.Id); break; } } if (secondLoadBalancerId == null) { foreach (SubResource subResource in ipConfig.LoadBalancerInboundNatPools) { if (!subResource.Id.ToLower().StartsWith(firstLoadBalancerId.ToLower())) { secondLoadBalancerId = ResourceUtils .ParentResourcePathFromResourceId(subResource.Id); break; } } } if (secondLoadBalancerId == null) { return; } ILoadBalancer loadBalancer2 = this.networkManager .LoadBalancers .GetById(secondLoadBalancerId); if (loadBalancer2.PublicIPAddressIds != null && loadBalancer2.PublicIPAddressIds.Count > 0) { this.primaryInternetFacingLoadBalancer = loadBalancer2; } else { this.primaryInternalLoadBalancer = loadBalancer2; } } ///GENMHASH:C9A8EFD03D810995DC8CE56B0EFD441D:E7976D224D54D6C1BB8B22CE27B71F44 public VirtualMachineScaleSetImpl WithOverProvision(bool enabled) { Inner .Overprovision = enabled; return this; } ///GENMHASH:54F48C4A15522D8E87E76E69BFD089CA:67C5008B7D86A1EA0300776CDD220599 public ISet<string> UserAssignedManagedServiceIdentityIds() { if (this.Inner.Identity != null && this.Inner.Identity.UserAssignedIdentities != null) { return new HashSet<string>(this.Inner.Identity.UserAssignedIdentities.Keys); } return new HashSet<string>(); } ///GENMHASH:BC4103A90A606609FAB346997701A4DE:F96317098E1E2EA0D5CD8D759145745A public ResourceIdentityType? ManagedServiceIdentityType() { return VirtualMachineScaleSetMsiHelper.ManagedServiceIdentityType(this.Inner); } ///GENMHASH:D8D324B42ED7B0976032110E0D5D3320:9939C56F8394598297EC15BC4F6CCF06 public bool IsBootDiagnosticsEnabled() { return this.bootDiagnosticsHandler.IsBootDiagnosticsEnabled(); } ///GENMHASH:F842C1987E811B219C87CFA14349A00B:AA3FE04060414CB0A10C5B6C55E7EC2B public string BootDiagnosticsStorageUri() { return this.bootDiagnosticsHandler.BootDiagnosticsStorageUri(); } ///GENMHASH:C5E4011AAE57A5F6132092A4B8B874FF:36531E34809D3A8C9FAE365A128266D5 public VirtualMachinePriorityTypes VirtualMachinePriority() { return this.Inner.VirtualMachineProfile?.Priority; } public VirtualMachineEvictionPolicyTypes VirtualMachineEvictionPolicy() { return this.Inner.VirtualMachineProfile?.EvictionPolicy; } public BillingProfile BillingProfile() { return this.Inner.VirtualMachineProfile?.BillingProfile; } ///GENMHASH:02A68214692E8DA4CC34E5FE55E3C918:150375C199EA874367AE081B87D5F2FD public StorageAccountTypes ManagedOSDiskStorageAccountType() { if (this.Inner.VirtualMachineProfile != null && this.Inner.VirtualMachineProfile.StorageProfile != null && this.Inner.VirtualMachineProfile.StorageProfile.OsDisk != null && this.Inner.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk != null) { var accountType = this.Inner .VirtualMachineProfile .StorageProfile .OsDisk .ManagedDisk .StorageAccountType; if (accountType != null) { return accountType; } } return null; } ///GENMHASH:1D38DD2A6D3BB89ECF81A51A4906BE8C:412BD8EB9EA1AA5A85C0515A53ACF43C public string SystemAssignedManagedServiceIdentityPrincipalId() { if (this.Inner.Identity != null) { return this.Inner.Identity.PrincipalId; } return null; } ///GENMHASH:9019C44FB9C28F62603D9972D45A9522:04EA2CF2FF84B5C44179285E14BA0FF0 public bool IsManagedServiceIdentityEnabled() { ResourceIdentityType? type = this.ManagedServiceIdentityType(); if (type == null) { return false; } else { return !type.Value.Equals(ResourceIdentityType.None); } } ///GENMHASH:D19E7D61822C4048249EC4B57FA6F59B:E55E888BE3583ADCF1863F5A9DC47299 public string SystemAssignedManagedServiceIdentityTenantId() { if (this.Inner.Identity != null) { return this.Inner.Identity.TenantId; } return null; } ///GENMHASH:F856C02184EB290DC74E5823D4280D7C:C06C8F12A2F1E86C908BE0388D483D06 public ISet<Microsoft.Azure.Management.ResourceManager.Fluent.Core.AvailabilityZoneId> AvailabilityZones() { var zones = new HashSet<Microsoft.Azure.Management.ResourceManager.Fluent.Core.AvailabilityZoneId>(); if (this.Inner.Zones != null) { foreach (var zone in this.Inner.Zones) { zones.Add(AvailabilityZoneId.Parse(zone)); } } return zones; } ///GENMHASH:E059E91FE0CBE4B6875986D1B46994D2:DAA85BBA01C168FF877DF34933F404C0 public VirtualMachineScaleSetImpl WithSystemAssignedManagedServiceIdentity() { this.virtualMachineScaleSetMsiHelper.WithLocalManagedServiceIdentity(); return this; } ///GENMHASH:DEF511724D2CC8CA91F24E084BC9AA22:B156E25B8F4ADB8DA7E762E9B3B26AA3 public VirtualMachineScaleSetImpl WithSystemAssignedIdentityBasedAccessTo(string resourceId, string roleDefinitionId) { this.virtualMachineScaleSetMsiHelper.WithAccessTo(resourceId, roleDefinitionId); return this; } ///GENMHASH:F6C5721A84FA825F62951BE51537DD36:F9981224C9274380FA869CF773AE86FA public VirtualMachineScaleSetImpl WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role) { this.virtualMachineScaleSetMsiHelper.WithAccessToCurrentResourceGroup(role); return this; } ///GENMHASH:EFFF7ECD982913DB369E1EF1644031CB:818B408B1CD54C896CA7BA8C333687D3 public VirtualMachineScaleSetImpl WithSystemAssignedIdentityBasedAccessTo(string resourceId, BuiltInRole role) { this.virtualMachineScaleSetMsiHelper.WithAccessTo(resourceId, role); return this; } ///GENMHASH:5FD7E26022EAFDACD062A87DDA8FD39A:D4ED935DBBDA2F0DA85365422E2FFCA8 public VirtualMachineScaleSetImpl WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(string roleDefinitionId) { this.virtualMachineScaleSetMsiHelper.WithAccessToCurrentResourceGroup(roleDefinitionId); return this; } ///GENMHASH:8239AEDA70F925E7A1DCD8BDB2803956:6A2804975F58F97B4F610E2DE8E8AACA public VirtualMachineScaleSetImpl WithNewUserAssignedManagedServiceIdentity(ICreatable<IIdentity> creatableIdentity) { this.virtualMachineScaleSetMsiHelper.WithNewExternalManagedServiceIdentity(creatableIdentity); return this; } ///GENMHASH:77198B23BCB8BA2F0DDF3A8A0E85805C:F68FE87A8E9ADCA783F40FB45364544F public VirtualMachineScaleSetImpl WithoutUserAssignedManagedServiceIdentity(string identityId) { this.virtualMachineScaleSetMsiHelper.WithoutExternalManagedServiceIdentity(identityId); return this; } ///GENMHASH:6836D267A7B5AB07D80A2EFAF13B9F3E:8504B108F30E0AC9DC210A1D9CFA85F3 public VirtualMachineScaleSetImpl WithExistingUserAssignedManagedServiceIdentity(IIdentity identity) { this.virtualMachineScaleSetMsiHelper.WithExistingExternalManagedServiceIdentity(identity); return this; } ///GENMHASH:801A53D3DABA33CC92425D2203FD9242:023B6E0293C3EE52841DA58E9038A4E6 private static IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerInboundNatPool> GetInboundNatPoolsAssociatedWithIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { String loadBalancerId = loadBalancer.Id; Dictionary<string, ILoadBalancerInboundNatPool> attachedInboundNatPools = new Dictionary<string, ILoadBalancerInboundNatPool>(); var lbInboundNatPools = loadBalancer.InboundNatPools; foreach (ILoadBalancerInboundNatPool lbInboundNatPool in lbInboundNatPools.Values) { String inboundNatPoolId = MergePath(loadBalancerId, "inboundNatPools", lbInboundNatPool.Name); foreach (SubResource subResource in ipConfig.LoadBalancerInboundNatPools) { if (subResource.Id.Equals(inboundNatPoolId, StringComparison.OrdinalIgnoreCase)) { attachedInboundNatPools.Add(lbInboundNatPool.Name, lbInboundNatPool); } } } return attachedInboundNatPools; } ///GENMHASH:98B10909018928720DBCCEBE53E08820:75A4D7D6FD5B54E56A4949AE30530D27 public VirtualMachineScaleSetImpl WithoutAutoUpdate() { Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.EnableAutomaticUpdates = false; return this; } ///GENMHASH:AD16DA08B5E002AC14DA8E4DF1A29686:7CAC61F59FB870FA1BA64452A78CD17B private static void RemoveAllBackendAssociationFromIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { List<SubResource> toRemove = new List<SubResource>(); foreach (SubResource subResource in ipConfig.LoadBalancerBackendAddressPools) { if (subResource.Id.ToLower().StartsWith(loadBalancer.Id.ToLower() + "/")) { toRemove.Add(subResource); } } foreach (SubResource subResource in toRemove) { ipConfig.LoadBalancerBackendAddressPools.Remove(subResource); } } ///GENMHASH:27AD431A042600C45C4C0CA529477319:47186F09CC543669168F4089A11F6E5E private static void AssociateInboundNatPoolsToIPConfiguration(string loadBalancerId, VirtualMachineScaleSetIPConfigurationInner ipConfig, params string[] inboundNatPools) { List<SubResource> inboundNatPoolSubResourcesToAssociate = new List<SubResource>(); foreach (string inboundNatPool in inboundNatPools) { string inboundNatPoolId = MergePath(loadBalancerId, "inboundNatPools", inboundNatPool); bool found = false; foreach (SubResource subResource in ipConfig.LoadBalancerInboundNatPools) { if (subResource.Id.Equals(inboundNatPoolId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { inboundNatPoolSubResourcesToAssociate.Add(new SubResource { Id = inboundNatPoolId }); } } foreach (SubResource backendSubResource in inboundNatPoolSubResourcesToAssociate) { ipConfig.LoadBalancerInboundNatPools.Add(backendSubResource); } } ///GENMHASH:5DCF4E29F6EA4E300D272317D5090075:2CECE7F3DC203120ADD63663E7930758 private static void RemoveInboundNatPoolsFromIPConfiguration(string loadBalancerId, VirtualMachineScaleSetIPConfigurationInner ipConfig, params string[] inboundNatPoolNames) { List<SubResource> toRemove = new List<SubResource>(); foreach (string natPoolName in inboundNatPoolNames) { string inboundNatPoolId = MergePath(loadBalancerId, "inboundNatPools", natPoolName); foreach (SubResource subResource in ipConfig.LoadBalancerInboundNatPools) { if (subResource.Id.Equals(inboundNatPoolId, StringComparison.OrdinalIgnoreCase)) { toRemove.Add(subResource); break; } } } foreach (SubResource subResource in toRemove) { ipConfig.LoadBalancerInboundNatPools.Remove(subResource); } } ///GENMHASH:08CFC096AC6388D1C0E041ECDF099E3D:4479808A1E2B2A23538E662AD3F721EE public void Restart() { Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.RestartAsync(this.ResourceGroupName, this.Name)); } public async Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachineScaleSets.RestartAsync(this.ResourceGroupName, this.Name, cancellationToken: cancellationToken); } ///GENMHASH:5880487AA9218E8DF536932A49A0ACDD:35850B81E88D88D68766589B9671E590 public VirtualMachineScaleSetImpl WithNewStorageAccount(string name) { Storage.Fluent.StorageAccount.Definition.IWithGroup definitionWithGroup = this.storageManager .StorageAccounts .Define(name) .WithRegion(this.RegionName); ICreatable<IStorageAccount> definitionAfterGroup; if (this.newGroup != null) { definitionAfterGroup = definitionWithGroup.WithNewResourceGroup(this.newGroup); } else { definitionAfterGroup = definitionWithGroup.WithExistingResourceGroup(this.ResourceGroupName); } return WithNewStorageAccount(definitionAfterGroup); } ///GENMHASH:2DC51FEC3C45675856B4AC1D97BECBFD:625251347BC517ED9D6E5D9755FBF00B public VirtualMachineScaleSetImpl WithNewStorageAccount(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatable) { this.creatableStorageAccountKeys.Add(creatable.Key); this.AddCreatableDependency(creatable as IResourceCreator<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId>); return this; } ///GENMHASH:F91F57741BB7E185BF012523964DEED0:89445F7853BF795F5610E29A0AD00373 protected override void AfterCreating() { this.ClearCachedProperties(); this.InitializeChildrenFromInner(); this.virtualMachineScaleSetMsiHelper.Clear(); } ///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:9A047B4B22E09AEB6344D4F23EC361E5 public override async Task<IVirtualMachineScaleSet> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { var response = await GetInnerAsync(cancellationToken); SetInner(response); ClearCachedProperties(); InitializeChildrenFromInner(); return this; } protected override async Task<VirtualMachineScaleSetInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.VirtualMachineScaleSets.GetAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:0B0C2470711F6450D4872789FDEB62A0:27733295CC242C366636316AC58FC2D3 private VirtualMachineScaleSetDataDisk GetDataDiskInner(int lun) { VirtualMachineScaleSetStorageProfile storageProfile = this .Inner .VirtualMachineProfile .StorageProfile; IList<VirtualMachineScaleSetDataDisk> dataDisks = storageProfile .DataDisks; if (dataDisks == null) { return null; } foreach (var dataDisk in dataDisks) { if (dataDisk.Lun == lun) { return dataDisk; } } return null; } ///GENMHASH:F074773AE211BBEB7F46B598EA72155B:7704FB8C0D7ED4D767CE8138EA441588 public VirtualMachineScaleSetImpl WithExistingPrimaryInternalLoadBalancer(ILoadBalancer loadBalancer) { if (loadBalancer.PublicIPAddressIds.Count != 0) { throw new ArgumentException("Parameter loadBalancer must be an internal load balancer"); } string lbNetworkId = null; foreach (ILoadBalancerPrivateFrontend frontEnd in loadBalancer.PrivateFrontends.Values) { if (frontEnd.NetworkId != null) { lbNetworkId = frontEnd.NetworkId; } } if (this.IsInCreateMode) { string vmNICNetworkId = ResourceUtils.ParentResourcePathFromResourceId(this.existingPrimaryNetworkSubnetNameToAssociate); // Azure has a really wired BUG that - it throws exception when vnet of VMSS and LB are not same // (code: NetworkInterfaceAndInternalLoadBalancerMustUseSameVnet) but at the same time Azure update // the VMSS's network section to refer this invalid internal LB. This makes VMSS un-usable and portal // will show a error above VMSS profile page. // if (!vmNICNetworkId.Equals(lbNetworkId, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Virtual network associated with scale set virtual machines" + " and internal load balancer must be same. " + "'" + vmNICNetworkId + "'" + "'" + lbNetworkId); } this.primaryInternalLoadBalancer = loadBalancer; AssociateLoadBalancerToIPConfiguration(this.primaryInternalLoadBalancer, this.PrimaryNicDefaultIPConfiguration()); } else { string vmNicVnetId = ResourceUtils.ParentResourcePathFromResourceId(PrimaryNicDefaultIPConfiguration() .Subnet .Id); if (!vmNicVnetId.Equals(lbNetworkId, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Virtual network associated with scale set virtual machines" + " and internal load balancer must be same. " + "'" + vmNicVnetId + "'" + "'" + lbNetworkId); } this.primaryInternalLoadBalancerToAttachOnUpdate = loadBalancer; } return this; } ///GENMHASH:89EFB8F9AFBDF98FFAD5606983F59A03:E986803721702DC6EF28DDC04CC96CD1 public VirtualMachineScaleSetImpl WithNewDataDiskFromImage(int imageLun) { this.managedDataDisks.newDisksFromImage.Add(new VirtualMachineScaleSetDataDisk() { Lun = imageLun }); return this; } ///GENMHASH:92519C2F478984EF05C22A5573361AFE:D60066031CF6D3EF0D84A196BD186C4C public VirtualMachineScaleSetImpl WithNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType) { this.managedDataDisks.newDisksFromImage.Add(new VirtualMachineScaleSetDataDisk() { Lun = imageLun, DiskSizeGB = newSizeInGB, Caching = cachingType }); return this; } ///GENMHASH:BABD7F4E5FDF4ECA60DB2F163B33F4C7:70147D65554CF848675D35124D742DB0 public VirtualMachineScaleSetImpl WithNewDataDiskFromImage(int imageLun, int newSizeInGB, CachingTypes cachingType, StorageAccountTypes storageAccountType) { VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters(); managedDiskParameters.StorageAccountType = storageAccountType; this.managedDataDisks.newDisksFromImage.Add(new VirtualMachineScaleSetDataDisk() { Lun = imageLun, DiskSizeGB = newSizeInGB, ManagedDisk = managedDiskParameters, Caching = cachingType }); return this; } ///GENMHASH:7F0A9CB4CB6BBC98F72CF50A81EBFBF4:3C12806E439FD7F02ABD5EEE521A9AB0 public VirtualMachineScaleSetStorageProfile StorageProfile() { return Inner.VirtualMachineProfile.StorageProfile; } ///GENMHASH:3874257232804C74BD7501DE2BE2F0E9:D48844CD7D7EEEF909BD7006D3A7E439 public VirtualMachineScaleSetImpl WithLatestWindowsImage(string publisher, string offer, string sku) { ImageReference imageReference = new ImageReference() { Publisher = publisher, Offer = offer, Sku = sku, Version = "latest" }; return WithSpecificWindowsImageVersion(imageReference); } ///GENMHASH:2127E32A8F02C513138DB1208F98C806:1DD59433AF6ED9834170252D06569286 public IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerInboundNatPool> ListPrimaryInternetFacingLoadBalancerInboundNatPools() { if ((this as Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet).GetPrimaryInternetFacingLoadBalancer() != null) { return GetInboundNatPoolsAssociatedWithIPConfiguration(this.primaryInternetFacingLoadBalancer, PrimaryNicDefaultIPConfiguration()); } return new Dictionary<string, ILoadBalancerInboundNatPool>(); } ///GENMHASH:8CB9B7EEE4A4226A6F5BBB2958CC5E81:A9181EF01C6B9C8C3CB92E9F535B6236 public VirtualMachineScaleSetImpl WithExistingStorageAccount(IStorageAccount storageAccount) { this.existingStorageAccountsToAssociate.Add(storageAccount); return this; } ///GENMHASH:3DF1B6140B6B4ECBFA96FE642F2CD144:CCED3778DD625697E59E50F8F58EAFD7 public VirtualMachineScaleSetImpl WithPrimaryInternalLoadBalancerBackends(params string[] backendNames) { if (this.IsInCreateMode) { VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIPConfig = PrimaryNicDefaultIPConfiguration(); RemoveAllBackendAssociationFromIPConfiguration(this.primaryInternalLoadBalancer, defaultPrimaryIPConfig); AssociateBackEndsToIPConfiguration(this.primaryInternalLoadBalancer.Id, defaultPrimaryIPConfig, backendNames); } else { AddToList(this.primaryInternalLBBackendsToAddOnUpdate, backendNames); } return this; } ///GENMHASH:F24EFD30F0D04113B41EA2C36B55F059:9662F39CFDAE2D5E028F6D055A529B1F public VirtualMachineScaleSetImpl WithWindowsCustomImage(string customImageId) { ImageReferenceInner imageReferenceInner = new ImageReferenceInner(); imageReferenceInner.Id = customImageId; Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.ImageReference = imageReferenceInner; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(Custom)Image" or "VM(Platform)Image" Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:C1CAA1ACCAE5C80BBC73F38DBB8A24DB:A5BEB46443374AE5FC100EE84133951F public VirtualMachineScaleSetImpl WithWindowsGalleryImageVersion(string galleryImageVersionId) { return this.WithWindowsCustomImage(galleryImageVersionId); } ///GENMHASH:90924DCFADE551C6E90B738982E6C2F7:8E8BCFD08143E85B586E9D48D32AF4E0 public VirtualMachineScaleSetImpl WithOSDiskStorageAccountType(StorageAccountTypes accountType) { // withers is limited to VMSS based on ManagedDisk. this.Inner .VirtualMachineProfile .StorageProfile .OsDisk .ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters { StorageAccountType = accountType }; return this; } ///GENMHASH:1BBF95374A03EFFD0583730762AB8753:657393D43CB30B9E2DA291459E17BAD9 public VirtualMachineScaleSetImpl WithTimeZone(string timeZone) { Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.TimeZone = timeZone; return this; } ///GENMHASH:E50F40651A5B1AF20BC79D94DD871BC0:8D097652777E7CA886C41C25ADBEAA28 private static string MergePath(params string[] segments) { StringBuilder builder = new StringBuilder(); foreach (string segment in segments) { string tmp = segment; while (tmp.Length > 1 && tmp.EndsWith("/")) { tmp = tmp.Substring(0, tmp.Length - 1); } if (tmp.Length > 0) { builder.Append(tmp); builder.Append("/"); } } string merged = builder.ToString(); if (merged.EndsWith("/")) { merged = merged.Substring(0, merged.Length - 1); } return merged; } ///GENMHASH:CE03CDBD07CA3BD7500B36B206A91A4A:592F5357F294A567BF101FAB341C6CCA public VirtualMachineScaleSetImpl WithLinuxCustomImage(string customImageId) { ImageReferenceInner imageReferenceInner = new ImageReferenceInner(); imageReferenceInner.Id = customImageId; Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.ImageReference = imageReferenceInner; Inner .VirtualMachineProfile .OsProfile.LinuxConfiguration = new LinuxConfiguration(); this.isMarketplaceLinuxImage = true; return this; } ///GENMHASH:2B8B909D235B7D7AC3C105F6B606E684:7BC43BF2B183D2EF2284A56184ECD541 public VirtualMachineScaleSetImpl WithLinuxGalleryImageVersion(string galleryImageVersionId) { return this.WithLinuxCustomImage(galleryImageVersionId); } ///GENMHASH:2582ED197AB392F5EC837F6BC8FE2FF0:29B4432F98CD641D0280C31D00CAFB2D private void SetPrimaryIPConfigurationBackendsAndInboundNatPools() { if (this.IsInCreateMode) { return; } this.LoadCurrentPrimaryLoadBalancersIfAvailable(); VirtualMachineScaleSetIPConfigurationInner primaryIPConfig = PrimaryNicDefaultIPConfiguration(); if (this.primaryInternetFacingLoadBalancer != null) { RemoveBackendsFromIPConfiguration(this.primaryInternetFacingLoadBalancer.Id, primaryIPConfig, this.primaryInternetFacingLBBackendsToRemoveOnUpdate.ToArray()); AssociateBackEndsToIPConfiguration(primaryInternetFacingLoadBalancer.Id, primaryIPConfig, this.primaryInternetFacingLBBackendsToAddOnUpdate.ToArray()); RemoveInboundNatPoolsFromIPConfiguration(this.primaryInternetFacingLoadBalancer.Id, primaryIPConfig, this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.ToArray()); AssociateInboundNatPoolsToIPConfiguration(primaryInternetFacingLoadBalancer.Id, primaryIPConfig, this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.ToArray()); } if (this.primaryInternalLoadBalancer != null) { RemoveBackendsFromIPConfiguration(this.primaryInternalLoadBalancer.Id, primaryIPConfig, this.primaryInternalLBBackendsToRemoveOnUpdate.ToArray()); AssociateBackEndsToIPConfiguration(primaryInternalLoadBalancer.Id, primaryIPConfig, this.primaryInternalLBBackendsToAddOnUpdate.ToArray()); RemoveInboundNatPoolsFromIPConfiguration(this.primaryInternalLoadBalancer.Id, primaryIPConfig, this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.ToArray()); AssociateInboundNatPoolsToIPConfiguration(primaryInternalLoadBalancer.Id, primaryIPConfig, this.primaryInternalLBInboundNatPoolsToAddOnUpdate.ToArray()); } if (this.removePrimaryInternetFacingLoadBalancerOnUpdate) { if (this.primaryInternetFacingLoadBalancer != null) { RemoveLoadBalancerAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancer, primaryIPConfig); } } if (this.removePrimaryInternalLoadBalancerOnUpdate) { if (this.primaryInternalLoadBalancer != null) { RemoveLoadBalancerAssociationFromIPConfiguration(this.primaryInternalLoadBalancer, primaryIPConfig); } } if (this.primaryInternetFacingLoadBalancerToAttachOnUpdate != null) { if (this.primaryInternetFacingLoadBalancer != null) { RemoveLoadBalancerAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancer, primaryIPConfig); } AssociateLoadBalancerToIPConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIPConfig); if (this.primaryInternetFacingLBBackendsToAddOnUpdate.Count > 0) { RemoveAllBackendAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIPConfig); AssociateBackEndsToIPConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.Id, primaryIPConfig, this.primaryInternetFacingLBBackendsToAddOnUpdate.ToArray()); } if (this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.Count > 0) { RemoveAllInboundNatPoolAssociationFromIPConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate, primaryIPConfig); AssociateInboundNatPoolsToIPConfiguration(this.primaryInternetFacingLoadBalancerToAttachOnUpdate.Id, primaryIPConfig, this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.ToArray()); } } if (this.primaryInternalLoadBalancerToAttachOnUpdate != null) { if (this.primaryInternalLoadBalancer != null) { RemoveLoadBalancerAssociationFromIPConfiguration(this.primaryInternalLoadBalancer, primaryIPConfig); } AssociateLoadBalancerToIPConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIPConfig); if (this.primaryInternalLBBackendsToAddOnUpdate.Count > 0) { RemoveAllBackendAssociationFromIPConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIPConfig); AssociateBackEndsToIPConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.Id, primaryIPConfig, this.primaryInternalLBBackendsToAddOnUpdate.ToArray()); } if (this.primaryInternalLBInboundNatPoolsToAddOnUpdate.Count > 0) { RemoveAllInboundNatPoolAssociationFromIPConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate, primaryIPConfig); AssociateInboundNatPoolsToIPConfiguration(this.primaryInternalLoadBalancerToAttachOnUpdate.Id, primaryIPConfig, this.primaryInternalLBInboundNatPoolsToAddOnUpdate.ToArray()); } } this.removePrimaryInternetFacingLoadBalancerOnUpdate = false; this.removePrimaryInternalLoadBalancerOnUpdate = false; this.primaryInternetFacingLoadBalancerToAttachOnUpdate = null; this.primaryInternalLoadBalancerToAttachOnUpdate = null; this.primaryInternetFacingLBBackendsToRemoveOnUpdate.Clear(); this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate.Clear(); this.primaryInternalLBBackendsToRemoveOnUpdate.Clear(); this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate.Clear(); this.primaryInternetFacingLBBackendsToAddOnUpdate.Clear(); this.primaryInternetFacingLBInboundNatPoolsToAddOnUpdate.Clear(); this.primaryInternalLBBackendsToAddOnUpdate.Clear(); this.primaryInternalLBInboundNatPoolsToAddOnUpdate.Clear(); } ///GENMHASH:B532EFEBE670EE3FA1185DA0A91F40B5:4C1AD969AF53405CB7FB7BF930887497 private void ClearCachedProperties() { this.primaryInternetFacingLoadBalancer = null; this.primaryInternalLoadBalancer = null; } ///GENMHASH:33905CDEAEEF3BB750202A2D6D557629:DB1E6EAD0CBA02A64BE5E2EE1AE862FC public bool OverProvisionEnabled() { return Inner.Overprovision.Value; } ///GENMHASH:AFF08018A4055EA21949F6479B3BCCA0:4175296A99E4DC787679DF89D1FABCD5 public VirtualMachineScaleSetNetworkProfile NetworkProfile() { return Inner.VirtualMachineProfile.NetworkProfile; } ///GENMHASH:408E3AC8FC1959B99618665484BFE199:6DCFB156DC060B1BEBD0F007DDD76D62 private void SetOSDiskDefault() { if (IsInUpdateMode()) { return; } VirtualMachineScaleSetStorageProfile storageProfile = Inner.VirtualMachineProfile.StorageProfile; VirtualMachineScaleSetOSDisk osDisk = storageProfile.OsDisk; if (IsOSDiskFromImage(osDisk)) { // ODDisk CreateOption: FROM_IMAGE // if (IsManagedDiskEnabled()) { // Note: // Managed disk // Supported: PlatformImage and CustomImage // UnSupported: StoredImage // if (osDisk.ManagedDisk == null) { osDisk.ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters(); } if (osDisk.ManagedDisk.StorageAccountType == null) { osDisk.ManagedDisk .StorageAccountType = StorageAccountTypes.StandardLRS; } osDisk.VhdContainers = null; // We won't set osDisk.Name() explicitly for managed disk, if it is null CRP generates unique // name for the disk resource within the resource group. } else { // Note: // Native (un-managed) disk // Supported: PlatformImage and StoredImage // UnSupported: CustomImage // osDisk.ManagedDisk = null; if (osDisk.Name == null) { WithOSDiskName(this.Name + "-os-disk"); } } } else { // NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS] } if (Inner.VirtualMachineProfile.StorageProfile.OsDisk.Caching == null) { WithOSDiskCaching(CachingTypes.ReadWrite); } } ///GENMHASH:8FDBCB5DF6AFD1594DF170521CE46D5F:4DF21C8BC272D1C368C4F1F79237B3D0 public VirtualMachineScaleSetImpl WithPopularWindowsImage(KnownWindowsVirtualMachineImage knownImage) { return WithSpecificWindowsImageVersion(knownImage.ImageReference()); } ///GENMHASH:8371720B72164AB21B88202FD4561610:9ECD956712FBC7CB9A976884F3BEAB45 public IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerBackend> ListPrimaryInternetFacingLoadBalancerBackends() { if ((this as Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet).GetPrimaryInternetFacingLoadBalancer() != null) { return GetBackendsAssociatedWithIPConfiguration(this.primaryInternetFacingLoadBalancer, PrimaryNicDefaultIPConfiguration()); } return new Dictionary<string, ILoadBalancerBackend>(); } ///GENMHASH:5810786355B161A5CD254C9E3BE76524:F7407CEA3D12779F169A4F2984ACFC2B public VirtualMachineScaleSetImpl WithAdminPassword(string password) { Inner .VirtualMachineProfile .OsProfile .AdminPassword = password; return this; } ///GENMHASH:83A8BCB96B7881DAF693D324E0E9BAAE:83FB521120A40493EBC9C3BFCC730829 public ILoadBalancer GetPrimaryInternetFacingLoadBalancer() { if (this.primaryInternetFacingLoadBalancer == null) { LoadCurrentPrimaryLoadBalancersIfAvailable(); } return this.primaryInternetFacingLoadBalancer; } ///GENMHASH:B899054CADDD4C764670C53E2A300590:038D6D03640016D71036DDBF325D8E0F public VirtualMachineScaleSetImpl WithoutPrimaryInternetFacingLoadBalancerNatPools(params string[] natPoolNames) { AddToList(this.primaryInternetFacingLBInboundNatPoolsToRemoveOnUpdate, natPoolNames); return this; } ///GENMHASH:9BBA27913235B4504FD9F07549E645CC:0BF9F49BB572288259C5C2CF97915D33 public VirtualMachineScaleSetImpl WithSsh(string publicKeyData) { VirtualMachineScaleSetOSProfile osProfile = Inner .VirtualMachineProfile .OsProfile; if (osProfile.LinuxConfiguration.Ssh == null) { SshConfiguration sshConfiguration = new SshConfiguration(); sshConfiguration.PublicKeys = new List<SshPublicKeyInner>(); osProfile.LinuxConfiguration.Ssh = sshConfiguration; } SshPublicKeyInner sshPublicKey = new SshPublicKeyInner(); sshPublicKey.KeyData = publicKeyData; sshPublicKey.Path = "/home/" + osProfile.AdminUsername + "/.ssh/authorized_keys"; osProfile.LinuxConfiguration.Ssh.PublicKeys.Add(sshPublicKey); return this; } ///GENMHASH:864D8E4C8CD2E86906490FEDA8FB3F2B:8DBC7BDC302D2B4665D3623CB5CE6F9B private static IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerBackend> GetBackendsAssociatedWithIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { string loadBalancerId = loadBalancer.Id; Dictionary<string, ILoadBalancerBackend> attachedBackends = new Dictionary<string, ILoadBalancerBackend>(); var lbBackends = loadBalancer.Backends; foreach (ILoadBalancerBackend lbBackend in lbBackends.Values) { string backendId = MergePath(loadBalancerId, "backendAddressPools", lbBackend.Name); foreach (SubResource subResource in ipConfig.LoadBalancerBackendAddressPools) { if (subResource.Id.Equals(backendId, StringComparison.OrdinalIgnoreCase)) { attachedBackends.Add(lbBackend.Name, lbBackend); } } } return attachedBackends; } ///GENMHASH:38EF4A7AB82168A6DD38F533747DA9D5:362113C4E307F07B620E363B30115839 public string ComputerNamePrefix() { return Inner.VirtualMachineProfile.OsProfile.ComputerNamePrefix; } ///GENMHASH:44218FC054E9DD430ECE7417A9705EB2:2DB39ADE66ABE6DB110EEDB9C63E2DB3 public VirtualMachineScaleSetImpl WithPrimaryInternalLoadBalancerInboundNatPools(params string[] natPoolNames) { if (this.IsInCreateMode) { VirtualMachineScaleSetIPConfigurationInner defaultPrimaryIPConfig = this.PrimaryNicDefaultIPConfiguration(); RemoveAllInboundNatPoolAssociationFromIPConfiguration(this.primaryInternalLoadBalancer, defaultPrimaryIPConfig); AssociateInboundNatPoolsToIPConfiguration(this.primaryInternalLoadBalancer.Id, defaultPrimaryIPConfig, natPoolNames); } else { AddToList(this.primaryInternalLBInboundNatPoolsToAddOnUpdate, natPoolNames); } return this; } ///GENMHASH:0B0B068704882D0210B822A215F5536D:243E7BC061CB4C21AF430343B3ACCDAA public VirtualMachineScaleSetImpl WithStoredWindowsImage(string imageUrl) { VirtualHardDisk userImageVhd = new VirtualHardDisk(); userImageVhd.Uri = imageUrl; Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.OsDisk.Image = userImageVhd; // For platform image osType will be null, azure will pick it from the image metadata. Inner .VirtualMachineProfile .StorageProfile.OsDisk.OsType = OperatingSystemTypes.Windows; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(Custom)Image" or "VM(Platform)Image" Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:CAFE3044E63DB355E0097F6FD22A0282:600739A4DD068DBA0CF85CC076E9111F public IEnumerable<IVirtualMachineScaleSetSku> ListAvailableSkus() { return Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.ListSkusAsync(ResourceGroupName, Name)) .AsContinuousCollection(link => Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.ListSkusNextAsync(link))) .Select(inner => new VirtualMachineScaleSetSkuImpl(inner)); } ///GENMHASH:B521ECE36A8645ACCD4603A46DF73D20:6C43F204834714CB74740068BED95D98 private bool IsInUpdateMode() { return !this.IsInCreateMode; } ///GENMHASH:CE408710AAEBD9F32D9AA9DB3280112C:DE7951813645A18DB8AC5B2A48405BD0 public VirtualMachineScaleSetImpl WithSku(VirtualMachineScaleSetSkuTypes skuType) { Inner.Sku = skuType.Sku; return this; } ///GENMHASH:C28C7D09D57FFF72FA8A6AEC7292936E:58BB80E4580D65A5E408E4BA250168E1 public VirtualMachineScaleSetImpl WithSku(IVirtualMachineScaleSetSku sku) { return this.WithSku(sku.SkuType); } ///GENMHASH:9177073080371FB82A479834DA14F493:CB0A5903865A994CFC26F01586B9FD22 public VirtualMachineScaleSetImpl WithPopularLinuxImage(KnownLinuxVirtualMachineImage knownImage) { return WithSpecificLinuxImageVersion(knownImage.ImageReference()); } ///GENMHASH:6D51A334B57DF882E890FEBA9887BE77:7C195F155B243BEB1BF2C9C922692404 public VirtualMachineScaleSetImpl WithLatestLinuxImage(string publisher, string offer, string sku) { ImageReference imageReference = new ImageReference(); imageReference.Publisher = publisher; imageReference.Offer = offer; imageReference.Sku = sku; imageReference.Version = "latest"; return WithSpecificLinuxImageVersion(imageReference); } ///GENMHASH:CBF523A860AE839D0C4D7384E636EA3A:FBFD113A504A5E7AC32C778EDF3C9726 public VirtualMachineScaleSetImpl WithoutOverProvisioning() { return this.WithOverProvision(false); } ///GENMHASH:7CC775D2FD3FE91AF2002BEF58F09719:99855FF2EE95AA6F2863BA16C5E195B6 public VirtualMachineScaleSetImpl WithoutPrimaryInternetFacingLoadBalancerBackends(params string[] backendNames) { AddToList(this.primaryInternetFacingLBBackendsToRemoveOnUpdate, backendNames); return this; } ///GENMHASH:4A7665D6C5D507E115A9A8E551801DB6:2F9DC0F45AE7B5E40E42D209F813E9DD public VirtualMachineScaleSetImpl WithSpecificWindowsImageVersion(ImageReference imageReference) { Inner .VirtualMachineProfile .StorageProfile.OsDisk.CreateOption = DiskCreateOptionTypes.FromImage; Inner .VirtualMachineProfile .StorageProfile.ImageReference = imageReference.Inner; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration = new WindowsConfiguration(); // sets defaults for "Stored(Custom)Image" or "VM(Platform)Image" Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.ProvisionVMAgent = true; Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } ///GENMHASH:8EC66BEFDF0AB45D9707306C2856E7C8:31CFCE6190972DAB49A6CC439CE9500F private void SetPrimaryIPConfigurationSubnet() { if (this.IsInUpdateMode()) { return; } VirtualMachineScaleSetIPConfigurationInner ipConfig = this.PrimaryNicDefaultIPConfiguration(); ipConfig.Subnet = new ApiEntityReference { Id = this.existingPrimaryNetworkSubnetNameToAssociate }; this.existingPrimaryNetworkSubnetNameToAssociate = null; } ///GENMHASH:C81171F34FA85CED80852E725FF8B7A4:8AADBD78C0C1C88EB899BC43FF6E8A1E public bool IsManagedDiskEnabled() { VirtualMachineScaleSetStorageProfile storageProfile = Inner.VirtualMachineProfile.StorageProfile; if (IsOsDiskFromCustomImage(storageProfile)) { return true; } if (IsOSDiskFromStoredImage(storageProfile)) { return false; } if (IsOSDiskFromPlatformImage(storageProfile)) { if (this.isUnmanagedDiskSelected) { return false; } } if (IsInCreateMode) { return true; } else { var vhdContainers = storageProfile .OsDisk .VhdContainers; return vhdContainers == null || vhdContainers.Count == 0; } } ///GENMHASH:B37B5DD609CF1DB836ABB9CBB32E93E3:EBFBB1CB0457C2978B29376127013BE6 public VirtualMachineScaleSetImpl WithDataDiskDefaultStorageAccountType(StorageAccountTypes storageAccountType) { this.managedDataDisks.SetDefaultStorageAccountType(storageAccountType); return this; } ///GENMHASH:938517A3FC2059570C8EA6BFD0A7E151:78F7A73923F62410889B71C234EDE483 private VirtualMachineScaleSetIPConfigurationInner PrimaryNicDefaultIPConfiguration() { IList<VirtualMachineScaleSetNetworkConfigurationInner> nicConfigurations = Inner .VirtualMachineProfile .NetworkProfile .NetworkInterfaceConfigurations; foreach (VirtualMachineScaleSetNetworkConfigurationInner nicConfiguration in nicConfigurations) { if (nicConfiguration.Primary.HasValue && nicConfiguration.Primary == true) { if (nicConfiguration.IpConfigurations.Count > 0) { VirtualMachineScaleSetIPConfigurationInner ipConfig = nicConfiguration.IpConfigurations.ElementAt(0); if (ipConfig.LoadBalancerBackendAddressPools == null) { ipConfig.LoadBalancerBackendAddressPools = new List<SubResource>(); } if (ipConfig.LoadBalancerInboundNatPools == null) { ipConfig.LoadBalancerInboundNatPools = new List<SubResource>(); } return ipConfig; } } } throw new Exception("Could not find the primary nic configuration or an IP configuration in it"); } ///GENMHASH:AC21A10EE2E745A89E94E447800452C1:B5D7FA290CD4B78F425E5D837D1426C5 protected override void BeforeCreating() { if (this.extensions.Count > 0) { Inner.VirtualMachineProfile .ExtensionProfile = new VirtualMachineScaleSetExtensionProfile { Extensions = new List<Models.VirtualMachineScaleSetExtensionInner>() }; foreach (IVirtualMachineScaleSetExtension extension in this.extensions.Values) { Inner.VirtualMachineProfile .ExtensionProfile .Extensions.Add(extension.Inner); } } } ///GENMHASH:FD4CE9D235CA642C8185D0844177DDFB:D7E2129941B29E412D9F2124F2BAE432 public IReadOnlyList<string> VhdContainers() { if (Inner.VirtualMachineProfile.StorageProfile != null && Inner.VirtualMachineProfile.StorageProfile.OsDisk != null && Inner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers != null) { return Inner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers?.ToList(); } return new List<string>(); } ///GENMHASH:67723971057BB45E3F0FFEB5B7B65F34:314C13CB065F185378CB337F9FEEC400 private void SetOSProfileDefaults() { if (IsInUpdateMode()) { return; } if (Inner.Sku.Capacity == null) { this.WithCapacity(2); } if (Inner.UpgradePolicy == null || Inner.UpgradePolicy.Mode == null) { Inner.UpgradePolicy = new UpgradePolicy(); Inner.UpgradePolicy.Mode = Microsoft.Azure.Management.Compute.Fluent.Models.UpgradeMode.Automatic; } VirtualMachineScaleSetOSProfile osProfile = Inner .VirtualMachineProfile .OsProfile; VirtualMachineScaleSetOSDisk osDisk = Inner.VirtualMachineProfile.StorageProfile.OsDisk; if (IsOSDiskFromImage(osDisk)) { // ODDisk CreateOption: FROM_IMAGE // if (this.OSType() == OperatingSystemTypes.Linux || this.isMarketplaceLinuxImage) { if (osProfile.LinuxConfiguration == null) { osProfile.LinuxConfiguration = new LinuxConfiguration(); } osProfile .LinuxConfiguration .DisablePasswordAuthentication = osProfile.AdminPassword == null; } if (this.ComputerNamePrefix() == null) { // VM name cannot contain only numeric values and cannot exceed 15 chars if ((new Regex(@"^\d+$")).IsMatch(this.Name)) { this.WithComputerNamePrefix(SdkContext.RandomResourceName("vmss-vm", 12)); } else if (this.Name.Length <= 12) { this.WithComputerNamePrefix(this.Name + "-vm"); } else { this.WithComputerNamePrefix(SdkContext.RandomResourceName("vmss-vm", 12)); } } } else { // NOP [ODDisk CreateOption: ATTACH, ATTACH is not supported for VMSS] Inner .VirtualMachineProfile .OsProfile = null; } } ///GENMHASH:A890CDCD402F1815F0ACD6293C3C115C:8FEE8350E44B2F78F72EE527639CDC76 public INetwork GetPrimaryNetwork() { string subnetId = PrimaryNicDefaultIPConfiguration().Subnet.Id; string virtualNetworkId = ResourceUtils.ParentResourcePathFromResourceId(subnetId); return this.networkManager .Networks .GetById(virtualNetworkId); } ///GENMHASH:8E925C4949ADC5B976067DDC58BE3E3C:D2243C739D20D636DF7C32705C2B6CAF public IVirtualMachineScaleSetVMs VirtualMachines() { return new VirtualMachineScaleSetVMsImpl(this, Manager); } ///GENMHASH:D5F141800B409906045662B0DD536DE4:26BA1C1FFB483992498725C1ED900BA1 public VirtualMachineScaleSetImpl WithRootUsername(string rootUserName) { Inner .VirtualMachineProfile .OsProfile .AdminUsername = rootUserName; return this; } ///GENMHASH:D7FDEEE05B0AD7938194763373E58DCF:B966166E0B6ED23B8FE875ADCB3E96A7 public VirtualMachineScaleSetImpl WithUpgradeMode(UpgradeMode upgradeMode) { if (Inner.UpgradePolicy == null) { Inner.UpgradePolicy = new UpgradePolicy(); } Inner .UpgradePolicy .Mode = upgradeMode; return this; } ///GENMHASH:EBD956A6D9170606742388660BDAF883:0632C1C1A1EE3CCF1E3F260984431012 private static void AddToList<T>(List<T> list, params T[] items) { foreach (T item in items) { list.Add(item); } } ///GENMHASH:1E2CA1FC9878A5C0B08DAAE75CBAD541:CA4C4022D33F6F7487EF6C4ECA5FF3D3 public IReadOnlyDictionary<string, Microsoft.Azure.Management.Network.Fluent.ILoadBalancerBackend> ListPrimaryInternalLoadBalancerBackends() { if ((this as Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet).GetPrimaryInternalLoadBalancer() != null) { return GetBackendsAssociatedWithIPConfiguration(this.primaryInternalLoadBalancer, PrimaryNicDefaultIPConfiguration()); } return new Dictionary<string, ILoadBalancerBackend>(); } ///GENMHASH:DB561BC9EF939094412065B65EB3D2EA:323D5930D438D7B746B03A2AB231B061 public void Reimage() { Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.ReimageAsync(ResourceGroupName, Name)); } public async Task ReimageAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachineScaleSets.ReimageAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:7BA741621F15820BA59476A9CFEBBD88:395C45C93AFFE4737734EBBF09A6B2AF public VirtualMachineScaleSetImpl WithComputerNamePrefix(string namePrefix) { Inner .VirtualMachineProfile .OsProfile .ComputerNamePrefix = namePrefix; return this; } ///GENMHASH:A50ABE2E1C931A4A3E6C46728ECA9763:0D2CCE10FD77C080849AE0BE069DCC7D public VirtualMachineScaleSetImpl WithAutoUpdate() { Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.EnableAutomaticUpdates = true; return this; } private async Task HandleOSDiskContainersAsync(CancellationToken cancellationToken = default(CancellationToken)) { VirtualMachineScaleSetStorageProfile storageProfile = Inner .VirtualMachineProfile .StorageProfile; if (IsManagedDiskEnabled()) { storageProfile.OsDisk.VhdContainers = null; return; } if (IsOSDiskFromStoredImage(storageProfile)) { // There is a restriction currently that virtual machine's disk cannot be stored in multiple storage // accounts if scale set is based on stored image. Remove this check once azure start supporting it. // if (storageProfile.OsDisk.VhdContainers != null) { storageProfile.OsDisk .VhdContainers .Clear(); } return; } if (this.IsInCreateMode && this.creatableStorageAccountKeys.Count == 0 && this.existingStorageAccountsToAssociate.Count == 0) { IStorageAccount storageAccount = await this.storageManager.StorageAccounts .Define(this.namer.RandomName("stg", 24).Replace("-", "")) .WithRegion(this.RegionName) .WithExistingResourceGroup(this.ResourceGroupName) .CreateAsync(cancellationToken); String containerName = vhdContainerName; if (containerName == null) { containerName = "vhds"; } storageProfile.OsDisk .VhdContainers .Add(MergePath(storageAccount.EndPoints.Primary.Blob, containerName)); vhdContainerName = null; creatableStorageAccountKeys.Clear(); existingStorageAccountsToAssociate.Clear(); return; } else { string containerName = this.vhdContainerName; if (containerName == null) { foreach (string containerUrl in storageProfile.OsDisk.VhdContainers) { containerName = containerUrl.Substring(containerUrl.LastIndexOf("/") + 1); break; } } if (containerName == null) { containerName = "vhds"; } foreach (string storageAccountKey in this.creatableStorageAccountKeys) { IStorageAccount storageAccount = (IStorageAccount)CreatedResource(storageAccountKey); storageProfile.OsDisk .VhdContainers .Add(MergePath(storageAccount.EndPoints.Primary.Blob, containerName)); } foreach (IStorageAccount storageAccount in this.existingStorageAccountsToAssociate) { storageProfile.OsDisk .VhdContainers .Add(MergePath(storageAccount.EndPoints.Primary.Blob, containerName)); } this.vhdContainerName = null; this.creatableStorageAccountKeys.Clear(); this.existingStorageAccountsToAssociate.Clear(); } } ///GENMHASH:15C87FF18F2D92A7CA828FB69E15D8F4:FAB35812CDE5256B5EEDB90655E51B75 private void ThrowIfManagedDiskEnabled(string message) { if (this.IsManagedDiskEnabled()) { throw new NotSupportedException(message); } } ///GENMHASH:39841E710EB7DD7AE8E99B918CA0EEEA:C48030ECFE011DCB363EBC211AAE918D public string OSDiskName() { return Inner.VirtualMachineProfile.StorageProfile.OsDisk.Name; } ///GENMHASH:1BAF4F1B601F89251ABCFE6CC4867026:637A809EDFD013CAD03D1C7CE71A5FD8 public OperatingSystemTypes OSType() { return Inner.VirtualMachineProfile.StorageProfile.OsDisk.OsType.GetValueOrDefault(); } ///GENMHASH:F7E8AD723108078BE0FE19CD860DD3D3:78969D0BA29AFC39123F017955CEE8EE public VirtualMachineScaleSetImpl WithWinRM(WinRMListener listener) { if (Inner.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM == null) { WinRMConfiguration winRMConfiguration = new WinRMConfiguration(); Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.WinRM = winRMConfiguration; } if (Inner.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM.Listeners == null) { Inner .VirtualMachineProfile .OsProfile .WindowsConfiguration.WinRM .Listeners = new List<WinRMListener>(); } Inner .VirtualMachineProfile .OsProfile .WindowsConfiguration .WinRM .Listeners .Add(listener); return this; } ///GENMHASH:E8024524BA316DC9DEEB983B272ABF81:35404321E1B27D532B34DF57EB311A9E public VirtualMachineScaleSetImpl WithCustomData(string base64EncodedCustomData) { Inner .VirtualMachineProfile .OsProfile .CustomData = base64EncodedCustomData; return this; } ///GENMHASH:7AD7A06F139BA844A9B0CC9596C66F00:6CC5B2412B485510418552D419E955F9 private static void AssociateLoadBalancerToIPConfiguration(ILoadBalancer loadBalancer, VirtualMachineScaleSetIPConfigurationInner ipConfig) { var backends = loadBalancer.Backends.Values; string[] backendNames = new string[backends.Count()]; int i = 0; foreach (ILoadBalancerBackend backend in backends) { backendNames[i] = backend.Name; i++; } AssociateBackEndsToIPConfiguration(loadBalancer.Id, ipConfig, backendNames); var inboundNatPools = loadBalancer.InboundNatPools.Values; string[] natPoolNames = new string[inboundNatPools.Count()]; i = 0; foreach (ILoadBalancerInboundNatPool inboundNatPool in inboundNatPools) { natPoolNames[i] = inboundNatPool.Name; i++; } AssociateInboundNatPoolsToIPConfiguration(loadBalancer.Id, ipConfig, natPoolNames); } ///GENMHASH:359B78C1848B4A526D723F29D8C8C558:B8E11C7D3FD0F8058EC1203B18D3671D protected async override Task<VirtualMachineScaleSetInner> CreateInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (IsInCreateMode) { this.SetOSProfileDefaults(); this.SetOSDiskDefault(); this.SetPrimaryIPConfigurationSubnet(); this.SetPrimaryIPConfigurationBackendsAndInboundNatPools(); if (IsManagedDiskEnabled()) { this.managedDataDisks.SetDataDisksDefaults(); } else { IList<VirtualMachineScaleSetDataDisk> dataDisks = Inner .VirtualMachineProfile .StorageProfile .DataDisks; VirtualMachineScaleSetUnmanagedDataDiskImpl.SetDataDisksDefaults(dataDisks, Name); } await HandleOSDiskContainersAsync(cancellationToken); await this.bootDiagnosticsHandler.HandleDiagnosticsSettingsAsync(cancellationToken); virtualMachineScaleSetMsiHelper.ProcessCreatedExternalIdentities(); virtualMachineScaleSetMsiHelper.HandleExternalIdentities(); CreateNewProximityPlacementGroup(); var scalesetInner = await Manager.Inner.VirtualMachineScaleSets.CreateOrUpdateAsync(ResourceGroupName, Name, Inner, cancellationToken); this.SetInner(scalesetInner); await virtualMachineScaleSetMsiHelper.CommitsRoleAssignmentsPendingActionAsync(cancellationToken); return scalesetInner; } else { if (this.Extensions().Count > 0) { this.Inner .VirtualMachineProfile .ExtensionProfile = new VirtualMachineScaleSetExtensionProfile { Extensions = InnersFromWrappers<VirtualMachineScaleSetExtensionInner, IVirtualMachineScaleSetExtension>(this.Extensions().Values.ToArray()) }; } this.SetPrimaryIPConfigurationSubnet(); this.SetPrimaryIPConfigurationBackendsAndInboundNatPools(); if (IsManagedDiskEnabled()) { this.managedDataDisks.SetDataDisksDefaults(); } else { IList<VirtualMachineScaleSetDataDisk> dataDisks = Inner .VirtualMachineProfile .StorageProfile .DataDisks; VirtualMachineScaleSetUnmanagedDataDiskImpl.SetDataDisksDefaults(dataDisks, Name); } await HandleOSDiskContainersAsync(cancellationToken); await this.bootDiagnosticsHandler.HandleDiagnosticsSettingsAsync(cancellationToken); virtualMachineScaleSetMsiHelper.ProcessCreatedExternalIdentities(); VirtualMachineScaleSetUpdate updateParameter = this.PreparePatchPayload(); virtualMachineScaleSetMsiHelper.HandleExternalIdentities(updateParameter); var scalesetInner = await Manager.Inner.VirtualMachineScaleSets.UpdateAsync(ResourceGroupName, Name, updateParameter, cancellationToken); this.SetInner(scalesetInner); await virtualMachineScaleSetMsiHelper.CommitsRoleAssignmentsPendingActionAsync(cancellationToken); this.ClearCachedProperties(); this.InitializeChildrenFromInner(); this.virtualMachineScaleSetMsiHelper.Clear(); return scalesetInner; } } private void CreateNewProximityPlacementGroup() { if (IsInCreateMode) { if (!String.IsNullOrWhiteSpace(this.newProximityPlacementGroupName)) { ProximityPlacementGroupInner plgInner = new ProximityPlacementGroupInner() { ProximityPlacementGroupType = this.newProximityPlacementGroupType, Location = this.Inner.Location }; plgInner = Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => this.Manager.Inner.ProximityPlacementGroups.CreateOrUpdateAsync(this.ResourceGroupName, newProximityPlacementGroupName, plgInner)); this.Inner.ProximityPlacementGroup = new SubResource() { Id = plgInner.Id }; } } } ///GENMHASH:621A22301B3EB5233E9DB4ED5BEC5735:E8427EEC4ACC25554660EF889ECD07A2 public VirtualMachineScaleSetImpl WithDataDiskDefaultCachingType(CachingTypes cachingType) { this.managedDataDisks.SetDefaultCachingType(cachingType); return this; } ///GENMHASH:BC7873AAD73CC4C7525B7C9F39F3F121:A055D9C6DB5164F68AE250D30F989A3F public VirtualMachineScaleSetImpl WithoutPrimaryInternalLoadBalancerBackends(params string[] backendNames) { AddToList(this.primaryInternalLBBackendsToRemoveOnUpdate, backendNames); return this; } ///GENMHASH:085C052B5E99B190740EE6AF70CF4D53:4F450AB75A3E01A0CCB9AFBF4F23BE28 public VirtualMachineScaleSetImpl WithCapacity(int capacity) { Inner .Sku.Capacity = capacity; return this; } ///GENMHASH:ED2B5B9A3A19B5A8C2C3E6E1CDBF9402:6A6DEBF76624FF70612A6981A86CC468 public VirtualMachineScaleSetImpl WithUnmanagedDisks() { this.isUnmanagedDiskSelected = true; return this; } ///GENMHASH:6D9F740D6D73C56877B02D9F1C96F6E7:3AA1543C2E39D6E6D148C51D89E3B4C6 protected override void InitializeChildrenFromInner() { this.extensions = new Dictionary<string, IVirtualMachineScaleSetExtension>(); if (Inner.VirtualMachineProfile.ExtensionProfile != null && Inner.VirtualMachineProfile.ExtensionProfile.Extensions != null) { foreach (var innerExtenison in Inner.VirtualMachineProfile.ExtensionProfile.Extensions) { this.extensions.Add(innerExtenison.Name, new VirtualMachineScaleSetExtensionImpl(innerExtenison, this)); } } } ///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:5723E041D4826DFBE50B8B49C31EAF08 public void Start() { Management.ResourceManager.Fluent.Core.Extensions.Synchronize(() => Manager.Inner.VirtualMachineScaleSets.StartAsync(ResourceGroupName, Name)); } public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.VirtualMachineScaleSets.StartAsync(ResourceGroupName, Name, cancellationToken: cancellationToken); } ///GENMHASH:E3A33B29616A6EAF518CC10EA90B45C7:191C8844004D95B6F7362BD81543FE33 public ILoadBalancer GetPrimaryInternalLoadBalancer() { if (this.primaryInternalLoadBalancer == null) { LoadCurrentPrimaryLoadBalancersIfAvailable(); } return this.primaryInternalLoadBalancer; } ///GENMHASH:674F68CEE727AFB7E6F6D9C7FADE1175:9D8CEFD984A116AE33BB221254786FA5 public VirtualMachineScaleSetImpl WithNewDataDisk(int sizeInGB) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_Both_Unmanaged_And_Managed_Disk_Not_Aallowed); this.managedDataDisks.implicitDisksToAssociate.Add(new VirtualMachineScaleSetDataDisk() { Lun = -1, DiskSizeGB = sizeInGB }); return this; } ///GENMHASH:B213E98FA6979257F6E6F61C9B5E550B:AAA573249324CF7B1EBD45AD10721744 public VirtualMachineScaleSetImpl WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_Both_Unmanaged_And_Managed_Disk_Not_Aallowed); this.managedDataDisks.implicitDisksToAssociate.Add(new VirtualMachineScaleSetDataDisk() { Lun = lun, DiskSizeGB = sizeInGB, Caching = cachingType }); return this; } ///GENMHASH:1D3A0A89681FFD35007B24FCED6BF299:96D67639BA263640D554DB8A3CC5D75C public VirtualMachineScaleSetImpl WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType) { ThrowIfManagedDiskDisabled(ManagedUnmanagedDiskErrors.VMSS_Both_Unmanaged_And_Managed_Disk_Not_Aallowed); VirtualMachineScaleSetManagedDiskParameters managedDiskParameters = new VirtualMachineScaleSetManagedDiskParameters(); managedDiskParameters.StorageAccountType = storageAccountType; this.managedDataDisks.implicitDisksToAssociate.Add(new VirtualMachineScaleSetDataDisk() { Lun = lun, DiskSizeGB = sizeInGB, Caching = cachingType, ManagedDisk = managedDiskParameters }); return this; } ///GENMHASH:3CAA43EAEEB81309EADF54AA78725296:E14EB64EB306A8F5A0DF21CD2E85782B public VirtualMachineScaleSetImpl WithVMAgent() { Inner .VirtualMachineProfile .OsProfile.WindowsConfiguration.ProvisionVMAgent = true; return this; } ///GENMHASH:9E11BB028D83D0EF7340685F19FBA340:E9A91314DAD8267710EFDE4AAE671CCF public IVirtualMachineScaleSetNetworkInterface GetNetworkInterfaceByInstanceId(string instanceId, string name) { return this.networkManager.NetworkInterfaces.GetByVirtualMachineScaleSetInstanceId(this.ResourceGroupName, this.Name, instanceId, name); } ///GENMHASH:BF5FD367567995AC0C50DACEDECE61BD:6FB961EBF4FEC9C5343282A34D18848B public VirtualMachineScaleSetImpl WithoutPrimaryInternalLoadBalancerNatPools(params string[] natPoolNames) { AddToList(this.primaryInternalLBInboundNatPoolsToRemoveOnUpdate, natPoolNames); return this; } ///GENMHASH:0E3F9BC2C5C0DB936DBA634A972BC916:26BA1C1FFB483992498725C1ED900BA1 public VirtualMachineScaleSetImpl WithAdminUsername(string adminUserName) { Inner .VirtualMachineProfile .OsProfile .AdminUsername = adminUserName; return this; } ///GENMHASH:D05B148D26960ED1D8EF344B16F36F78:00EC0F6EA3A819049F5C89068A74593C public VirtualMachineScaleSetImpl WithOverProvisioning() { return this.WithOverProvision(true); } ///GENMHASH:5D8D71845C83EB59F52EB2C4B1C05618:8669839F7D5CF9000DF1C6A1D335E292 public VirtualMachineScaleSetImpl WithAvailabilityZone(AvailabilityZoneId zoneId) { // Note: Only for virtual machine scale set, new zone can be specified, hence // this option is available for both definition and update cases. // // if (this.Inner.Zones == null) { this.Inner.Zones = new List<string>(); } this.Inner.Zones.Add(zoneId.ToString()); return this; } public VirtualMachineScaleSetImpl WithBootDiagnostics() { this.bootDiagnosticsHandler.WithBootDiagnostics(); return this; } public VirtualMachineScaleSetImpl WithBootDiagnostics(ICreatable<IStorageAccount> creatable) { this.bootDiagnosticsHandler.WithBootDiagnostics(creatable); return this; } public VirtualMachineScaleSetImpl WithBootDiagnostics(IStorageAccount storageAccount) { this.bootDiagnosticsHandler.WithBootDiagnostics(storageAccount); return this; } public VirtualMachineScaleSetImpl WithBootDiagnostics(string storageAccountBlobEndpointUri) { this.bootDiagnosticsHandler.WithBootDiagnostics(storageAccountBlobEndpointUri); return this; } public VirtualMachineScaleSetImpl WithoutBootDiagnostics() { this.bootDiagnosticsHandler.WithoutBootDiagnostics(); return this; } ///GENMHASH:6519A067F8EC19017417E77E98CBFAB4:29848F9AE1C8DDE847A8C3F172BFE8CE public VirtualMachineScaleSetImpl WithVirtualMachinePriority(VirtualMachinePriorityTypes priority) { this.Inner.VirtualMachineProfile.Priority = priority; return this; } public VirtualMachineScaleSetImpl WithLowPriorityVirtualMachine() { this.WithVirtualMachinePriority(VirtualMachinePriorityTypes.Low); return this; } public VirtualMachineScaleSetImpl WithMaxPrice(double? maxPrice) { this.Inner.VirtualMachineProfile.BillingProfile = new BillingProfile(maxPrice); return this; } public VirtualMachineScaleSetImpl WithLowPriorityVirtualMachine(VirtualMachineEvictionPolicyTypes policy) { this.WithLowPriorityVirtualMachine(); this.Inner.VirtualMachineProfile.EvictionPolicy = policy; return this; } ///GENMHASH:9C4A541B9A2E22540116BFA125189F57:2F8856B5F0BA5E1B741D68C6CED48D9A public VirtualMachineScaleSetImpl WithoutDataDisk(int lun) { if (!IsManagedDiskEnabled()) { return this; } this.managedDataDisks.diskLunsToRemove.Add(lun); return this; } public VirtualMachineScaleSetImpl WithProximityPlacementGroup(string proximityPlacementGroupId) { this.newProximityPlacementGroupName = null; this.newProximityPlacementGroupType = null; this.Inner.ProximityPlacementGroup = new SubResource() { Id = proximityPlacementGroupId }; return this; } public VirtualMachineScaleSetImpl WithNewProximityPlacementGroup(String proximityPlacementGroupName, ProximityPlacementGroupType type) { this.newProximityPlacementGroupName = proximityPlacementGroupName; this.newProximityPlacementGroupType = type; this.Inner.ProximityPlacementGroup = null; return this; } public VirtualMachineScaleSetImpl WithDoNotRunExtensionsOnOverprovisionedVMs(bool doNotRunExtensionsOnOverprovisionedVMs) { this.Inner.DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs; return this; } public VirtualMachineScaleSetImpl WithAdditionalCapabilities(AdditionalCapabilities additionalCapabilities) { this.Inner.AdditionalCapabilities = additionalCapabilities; return this; } ///GENMHASH:C4918DA109F597102F1B013B0137F3A2:671581C8F41182347B219436B693EB8A private static void AssociateBackEndsToIPConfiguration(string loadBalancerId, VirtualMachineScaleSetIPConfigurationInner ipConfig, params string[] backendNames) { List<SubResource> backendSubResourcesToAssociate = new List<SubResource>(); foreach (string backendName in backendNames) { String backendPoolId = MergePath(loadBalancerId, "backendAddressPools", backendName); bool found = false; foreach (SubResource subResource in ipConfig.LoadBalancerBackendAddressPools) { if (subResource.Id.Equals(backendPoolId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { backendSubResourcesToAssociate.Add(new SubResource { Id = backendPoolId }); } } foreach (SubResource backendSubResource in backendSubResourcesToAssociate) { ipConfig.LoadBalancerBackendAddressPools.Add(backendSubResource); } } VirtualMachineScaleSet.Update.IWithPrimaryLoadBalancer IUpdatable<VirtualMachineScaleSet.Update.IWithPrimaryLoadBalancer>.Update() { return this; } ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVTY2FsZVNldEltcGwuTWFuYWdlZERhdGFEaXNrQ29sbGVjdGlvbg== internal partial class ManagedDataDiskCollection { public IList<Models.VirtualMachineScaleSetDataDisk> implicitDisksToAssociate; public IList<int> diskLunsToRemove; public IList<Models.VirtualMachineScaleSetDataDisk> newDisksFromImage; private VirtualMachineScaleSetImpl vmss; private CachingTypes? defaultCachingType; private StorageAccountTypes defaultStorageAccountType; internal ManagedDataDiskCollection(VirtualMachineScaleSetImpl vmss) { this.vmss = vmss; this.implicitDisksToAssociate = new List<VirtualMachineScaleSetDataDisk>(); this.diskLunsToRemove = new List<int>(); this.newDisksFromImage = new List<VirtualMachineScaleSetDataDisk>(); } ///GENMHASH:E896A9714FD3ED579D3A806B2D670211:9EC21D752F2334263B0BF51F5BEF2FE2 internal void SetDefaultStorageAccountType(StorageAccountTypes defaultStorageAccountType) { this.defaultStorageAccountType = defaultStorageAccountType; } ///GENMHASH:CA7F491172B86E1C8B0D8508E4161245:48D903B27EEF73A7FA2C1B3E0E47B216 internal void SetDataDisksDefaults() { VirtualMachineScaleSetStorageProfile storageProfile = this.vmss .Inner .VirtualMachineProfile .StorageProfile; if (IsPending()) { if (storageProfile.DataDisks == null) { storageProfile.DataDisks = new List<VirtualMachineScaleSetDataDisk>(); } var dataDisks = storageProfile.DataDisks; HashSet<int> usedLuns = new HashSet<int>(); // Get all used luns // foreach (var dataDisk in dataDisks) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.implicitDisksToAssociate) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } foreach (var dataDisk in this.newDisksFromImage) { if (dataDisk.Lun != -1) { usedLuns.Add(dataDisk.Lun); } } // Func to get the next available lun // Func<int> nextLun = () => { int l = 0; while (usedLuns.Contains(l)) { l++; } usedLuns.Add(l); return l; }; SetImplicitDataDisks(nextLun); SetImageBasedDataDisks(); RemoveDataDisks(); } if (storageProfile.DataDisks != null && storageProfile.DataDisks.Count == 0) { if (vmss.IsInCreateMode) { // If there is no data disks at all, then setting it to null rather than [] is necessary. // This is for take advantage of CRP's implicit creation of the data disks if the image has // more than one data disk image(s). // storageProfile.DataDisks = null; } } this.Clear(); } ///GENMHASH:77E6B131587760C1313B68052BA1F959:3583CA6C895B07FD3877A9CFC685B07B private CachingTypes GetDefaultCachingType() { if (defaultCachingType == null || !defaultCachingType.HasValue) { return CachingTypes.ReadWrite; } return defaultCachingType.Value; } ///GENMHASH:B33308470B073DF5A31970C4C53291A4:3ED328226BD857CB73174798CB8638CC private void SetImageBasedDataDisks() { VirtualMachineScaleSetStorageProfile storageProfile = this.vmss .Inner .VirtualMachineProfile .StorageProfile; var dataDisks = storageProfile.DataDisks; foreach (var dataDisk in this.newDisksFromImage) { dataDisk.CreateOption = DiskCreateOptionTypes.FromImage; // Don't set default caching type for the disk, either user has to specify it explicitly or let CRP pick // it from the image dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:BDEEEC08EF65465346251F0F99D16258:7FA0EAA436FE9B4E519F2A6F85491919 private void Clear() { implicitDisksToAssociate.Clear(); diskLunsToRemove.Clear(); newDisksFromImage.Clear(); } ///GENMHASH:C474BAF5F2762CA941D8C01DC8F0A2CB:123893CCEC4625CDE4B7BCBFC68DCF5B internal void SetDefaultCachingType(CachingTypes cachingType) { this.defaultCachingType = cachingType; } ///GENMHASH:8F31500456F297BA5B51A162318FE60B:B2C684FBABF2AB3AFDFCC790ACB99D8C private void RemoveDataDisks() { VirtualMachineScaleSetStorageProfile storageProfile = this.vmss .Inner .VirtualMachineProfile .StorageProfile; var dataDisks = storageProfile.DataDisks; foreach (var lun in this.diskLunsToRemove) { int indexToRemove = 0; foreach (var dataDisk in dataDisks) { if (dataDisk.Lun == lun) { dataDisks.RemoveAt(indexToRemove); break; } indexToRemove++; } } } ///GENMHASH:647794DB64052F8555CB8ABDABF9F24D:419FDCEEC4AAB55470C80A42C1D69868 private StorageAccountTypes GetDefaultStorageAccountType() { if (defaultStorageAccountType == null) { return StorageAccountTypes.StandardLRS; } return defaultStorageAccountType; } ///GENMHASH:0E80C978BE389A20F8B9BDDCBC308EBF:0EC63377965A94AB9FD183B5A71C65E2 private void SetImplicitDataDisks(Func<int> nextLun) { VirtualMachineScaleSetStorageProfile storageProfile = this.vmss .Inner .VirtualMachineProfile .StorageProfile; var dataDisks = storageProfile.DataDisks; foreach (var dataDisk in this.implicitDisksToAssociate) { dataDisk.CreateOption = DiskCreateOptionTypes.Empty; if (dataDisk.Lun == -1) { dataDisk.Lun = nextLun(); } if (dataDisk.Caching == null) { dataDisk.Caching = GetDefaultCachingType(); } if (dataDisk.ManagedDisk == null) { dataDisk.ManagedDisk = new VirtualMachineScaleSetManagedDiskParameters(); } if (dataDisk.ManagedDisk.StorageAccountType == null) { dataDisk.ManagedDisk.StorageAccountType = GetDefaultStorageAccountType(); } dataDisk.Name = null; dataDisks.Add(dataDisk); } } ///GENMHASH:EC209EBA0DF87A8C3CEA3D68742EA90D:99000851407BA5F5FA9785B299474B9E private bool IsPending() { return implicitDisksToAssociate.Count > 0 || diskLunsToRemove.Count > 0 || newDisksFromImage.Count > 0; } } /// <summary> /// Class to manage VMSS boot diagnostics settings. /// </summary> internal partial class BootDiagnosticsHandler { private readonly VirtualMachineScaleSetImpl vmssImpl; private string creatableDiagnosticsStorageAccountKey; private string creatableStorageAccountKey; private IStorageAccount existingStorageAccountToAssociate; internal BootDiagnosticsHandler(VirtualMachineScaleSetImpl vmssImpl) { this.vmssImpl = vmssImpl; } internal bool IsBootDiagnosticsEnabled() { DiagnosticsProfile diagnosticsProfile = this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile; if (diagnosticsProfile != null && diagnosticsProfile.BootDiagnostics != null && diagnosticsProfile.BootDiagnostics.Enabled != null) { return diagnosticsProfile.BootDiagnostics.Enabled.Value; } return false; } internal String BootDiagnosticsStorageUri() { DiagnosticsProfile diagnosticsProfile = this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile; // Even though diagnostics can disabled azure still keep the storage uri if (diagnosticsProfile != null && diagnosticsProfile.BootDiagnostics != null) { return diagnosticsProfile.BootDiagnostics.StorageUri; } return null; } internal BootDiagnosticsHandler WithBootDiagnostics() { // Diagnostics storage uri will be set later by this.handleDiagnosticsSettings(..) // this.EnableDisable(true); return this; } internal BootDiagnosticsHandler WithBootDiagnostics(ICreatable<IStorageAccount> creatable) { // Diagnostics storage uri will be set later by this.handleDiagnosticsSettings(..) // this.EnableDisable(true); this.creatableDiagnosticsStorageAccountKey = creatable.Key; this.vmssImpl.AddCreatableDependency(creatable as IResourceCreator<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId>); return this; } internal BootDiagnosticsHandler WithBootDiagnostics(String storageAccountBlobEndpointUri) { this.EnableDisable(true); this.VMSSInner .VirtualMachineProfile .DiagnosticsProfile .BootDiagnostics .StorageUri = storageAccountBlobEndpointUri; return this; } internal BootDiagnosticsHandler WithBootDiagnostics(IStorageAccount storageAccount) { return this.WithBootDiagnostics(storageAccount.EndPoints.Primary.Blob); } internal BootDiagnosticsHandler WithoutBootDiagnostics() { this.EnableDisable(false); return this; } internal async Task HandleDiagnosticsSettingsAsync(CancellationToken cancellation) { DiagnosticsProfile diagnosticsProfile = this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile; if (diagnosticsProfile == null || diagnosticsProfile.BootDiagnostics == null || diagnosticsProfile.BootDiagnostics.StorageUri != null) { return; } bool enableBD = diagnosticsProfile.BootDiagnostics.Enabled == null ? false : diagnosticsProfile.BootDiagnostics.Enabled.Value; if (!enableBD) { return; } string bootDiagnosticsStorageUri = null; if (creatableDiagnosticsStorageAccountKey != null) { IStorageAccount storageAccount = (IStorageAccount)this.vmssImpl.CreatedResource(creatableDiagnosticsStorageAccountKey); bootDiagnosticsStorageUri = storageAccount.EndPoints.Primary.Blob; } else if (this.VMSSInner.VirtualMachineProfile.StorageProfile != null && this.VMSSInner.VirtualMachineProfile.StorageProfile.OsDisk != null && this.VMSSInner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers != null && this.VMSSInner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers.Count > 0) { var firstVhdContainer = this.VMSSInner.VirtualMachineProfile.StorageProfile.OsDisk.VhdContainers[0]; var url = new Uri(firstVhdContainer); var host = url.Host; bootDiagnosticsStorageUri = url.Scheme + "://" + url.Host; } else { var accountName = this.vmssImpl.namer.RandomName("stg", 24).Replace("-", ""); IStorageAccount storageAccount = await this.vmssImpl.storageManager.StorageAccounts .Define(accountName) .WithRegion(this.vmssImpl.Region) .WithExistingResourceGroup(this.vmssImpl.ResourceGroupName) .CreateAsync(cancellation); bootDiagnosticsStorageUri = storageAccount.EndPoints.Primary.Blob; } VMSSInner .VirtualMachineProfile .DiagnosticsProfile .BootDiagnostics .StorageUri = bootDiagnosticsStorageUri; } private VirtualMachineScaleSetInner VMSSInner { get { // Inner cannot be cached as parent VirtualMachineScaleSetImpl can refresh the inner in various cases // return this.vmssImpl.Inner; } } private void EnableDisable(bool enable) { if (this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile == null) { this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile = new DiagnosticsProfile(); } if (this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics == null) { this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = new BootDiagnostics(); } if (enable) { this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = true; } else { this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.Enabled = false; this.VMSSInner.VirtualMachineProfile.DiagnosticsProfile.BootDiagnostics.StorageUri = null; } } } internal class IdProvider : IIdProvider { private readonly VirtualMachineScaleSetImpl vmss; internal IdProvider(VirtualMachineScaleSetImpl vmss) { this.vmss = vmss; } public string PrincipalId { get { if (this.vmss.Inner != null && this.vmss.Inner.Identity != null) { return this.vmss.Inner.Identity.PrincipalId; } else { return null; } } } public string ResourceId { get { if (this.vmss.Inner != null) { return this.vmss.Inner.Id; } else { return null; } } } } } }
44.200413
255
0.610987
[ "MIT" ]
Azure/azure-libraries-for-net
src/ResourceManagement/Compute/VirtualMachineScaleSetImpl.cs
149,974
C#
/* * MIT License * * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs * * 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 ShiftOS.Engine; using ShiftOS.WinForms.Tools; namespace ShiftOS.WinForms { partial class WindowBorder { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pnltitle = new System.Windows.Forms.Panel(); this.pnlicon = new System.Windows.Forms.Panel(); this.pnlminimize = new System.Windows.Forms.Panel(); this.pnlmaximize = new System.Windows.Forms.Panel(); this.pnlclose = new System.Windows.Forms.Panel(); this.pnltitleleft = new System.Windows.Forms.Panel(); this.pnltitleright = new System.Windows.Forms.Panel(); this.lbtitletext = new System.Windows.Forms.Label(); this.pnlbottom = new System.Windows.Forms.Panel(); this.pnlbottomr = new System.Windows.Forms.Panel(); this.pnlbottoml = new System.Windows.Forms.Panel(); this.pnlleft = new System.Windows.Forms.Panel(); this.pnlright = new System.Windows.Forms.Panel(); this.pnlcontents = new System.Windows.Forms.Panel(); this.pnltitle.SuspendLayout(); this.pnlbottom.SuspendLayout(); this.SuspendLayout(); // // pnltitle // this.pnltitle.BackColor = System.Drawing.Color.Black; this.pnltitle.Controls.Add(this.pnlicon); this.pnltitle.Controls.Add(this.pnlminimize); this.pnltitle.Controls.Add(this.pnlmaximize); this.pnltitle.Controls.Add(this.pnlclose); this.pnltitle.Controls.Add(this.pnltitleleft); this.pnltitle.Controls.Add(this.pnltitleright); this.pnltitle.Controls.Add(this.lbtitletext); this.pnltitle.Dock = System.Windows.Forms.DockStyle.Top; this.pnltitle.Location = new System.Drawing.Point(0, 0); this.pnltitle.Name = "pnltitle"; this.pnltitle.Size = new System.Drawing.Size(730, 30); this.pnltitle.TabIndex = 0; this.pnltitle.Paint += new System.Windows.Forms.PaintEventHandler(this.pnltitle_Paint); this.pnltitle.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnltitle_MouseMove); // // pnlicon // this.pnlicon.Location = new System.Drawing.Point(9, -76); this.pnlicon.Name = "pnlicon"; this.pnlicon.Size = new System.Drawing.Size(200, 100); this.pnlicon.TabIndex = 6; // // pnlminimize // this.pnlminimize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pnlminimize.BackColor = System.Drawing.Color.Green; this.pnlminimize.Location = new System.Drawing.Point(649, 3); this.pnlminimize.Name = "pnlminimize"; this.pnlminimize.Size = new System.Drawing.Size(24, 24); this.pnlminimize.TabIndex = 3; this.pnlminimize.Click += new System.EventHandler(this.pnlminimize_Click); this.pnlminimize.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlminimize_MouseDown); this.pnlminimize.MouseEnter += new System.EventHandler(this.pnlminimize_MouseEnter); this.pnlminimize.MouseLeave += new System.EventHandler(this.pnlminimize_MouseLeave); this.pnlminimize.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlminimize_MouseUp); // // pnlmaximize // this.pnlmaximize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pnlmaximize.BackColor = System.Drawing.Color.Yellow; this.pnlmaximize.Location = new System.Drawing.Point(676, 3); this.pnlmaximize.Name = "pnlmaximize"; this.pnlmaximize.Size = new System.Drawing.Size(24, 24); this.pnlmaximize.TabIndex = 2; this.pnlmaximize.Click += new System.EventHandler(this.pnlmaximize_Click); this.pnlmaximize.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlmaximize_MouseDown); this.pnlmaximize.MouseEnter += new System.EventHandler(this.pnlmaximize_MouseEnter); this.pnlmaximize.MouseLeave += new System.EventHandler(this.pnlmaximize_MouseLeave); this.pnlmaximize.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlmaximize_MouseUp); // // pnlclose // this.pnlclose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pnlclose.BackColor = System.Drawing.Color.Red; this.pnlclose.Location = new System.Drawing.Point(703, 3); this.pnlclose.Name = "pnlclose"; this.pnlclose.Size = new System.Drawing.Size(24, 24); this.pnlclose.TabIndex = 1; this.pnlclose.Click += new System.EventHandler(this.pnlclose_Click); this.pnlclose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlclose_MouseDown); this.pnlclose.MouseEnter += new System.EventHandler(this.pnlclose_MouseEnter); this.pnlclose.MouseLeave += new System.EventHandler(this.pnlclose_MouseLeave); this.pnlclose.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlclose_MouseUp); // // pnltitleleft // this.pnltitleleft.Dock = System.Windows.Forms.DockStyle.Left; this.pnltitleleft.Location = new System.Drawing.Point(0, 0); this.pnltitleleft.Name = "pnltitleleft"; this.pnltitleleft.Size = new System.Drawing.Size(2, 30); this.pnltitleleft.TabIndex = 4; // // pnltitleright // this.pnltitleright.Dock = System.Windows.Forms.DockStyle.Right; this.pnltitleright.Location = new System.Drawing.Point(728, 0); this.pnltitleright.Name = "pnltitleright"; this.pnltitleright.Size = new System.Drawing.Size(2, 30); this.pnltitleright.TabIndex = 5; // // lbtitletext // this.lbtitletext.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbtitletext.AutoSize = true; this.lbtitletext.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.lbtitletext.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Bold); this.lbtitletext.ForeColor = System.Drawing.Color.White; this.lbtitletext.Location = new System.Drawing.Point(75, 9); this.lbtitletext.Name = "lbtitletext"; this.lbtitletext.Size = new System.Drawing.Size(77, 14); this.lbtitletext.TabIndex = 0; this.lbtitletext.Text = "Title text"; this.lbtitletext.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.lbtitletext.UseMnemonic = false; this.lbtitletext.Click += new System.EventHandler(this.lbtitletext_Click); this.lbtitletext.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lbtitletext_MouseMove); // // pnlbottom // this.pnlbottom.BackColor = System.Drawing.Color.Black; this.pnlbottom.Controls.Add(this.pnlbottomr); this.pnlbottom.Controls.Add(this.pnlbottoml); this.pnlbottom.Dock = System.Windows.Forms.DockStyle.Bottom; this.pnlbottom.Location = new System.Drawing.Point(0, 491); this.pnlbottom.Name = "pnlbottom"; this.pnlbottom.Size = new System.Drawing.Size(730, 2); this.pnlbottom.TabIndex = 1; this.pnlbottom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseDown); this.pnlbottom.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlbottom_MouseMove); this.pnlbottom.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseUp); // // pnlbottomr // this.pnlbottomr.Dock = System.Windows.Forms.DockStyle.Right; this.pnlbottomr.Location = new System.Drawing.Point(728, 0); this.pnlbottomr.Name = "pnlbottomr"; this.pnlbottomr.Size = new System.Drawing.Size(2, 2); this.pnlbottomr.TabIndex = 3; this.pnlbottomr.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseDown); this.pnlbottomr.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlbottomr_MouseMove); this.pnlbottomr.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseUp); // // pnlbottoml // this.pnlbottoml.Dock = System.Windows.Forms.DockStyle.Left; this.pnlbottoml.Location = new System.Drawing.Point(0, 0); this.pnlbottoml.Name = "pnlbottoml"; this.pnlbottoml.Size = new System.Drawing.Size(2, 2); this.pnlbottoml.TabIndex = 2; this.pnlbottoml.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseDown); this.pnlbottoml.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlbottoml_MouseMove); this.pnlbottoml.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseUp); // // pnlleft // this.pnlleft.BackColor = System.Drawing.Color.Black; this.pnlleft.Dock = System.Windows.Forms.DockStyle.Left; this.pnlleft.Location = new System.Drawing.Point(0, 30); this.pnlleft.Name = "pnlleft"; this.pnlleft.Size = new System.Drawing.Size(2, 461); this.pnlleft.TabIndex = 2; this.pnlleft.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseDown); this.pnlleft.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlleft_MouseMove); this.pnlleft.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseUp); // // pnlright // this.pnlright.BackColor = System.Drawing.Color.Black; this.pnlright.Dock = System.Windows.Forms.DockStyle.Right; this.pnlright.Location = new System.Drawing.Point(728, 30); this.pnlright.Name = "pnlright"; this.pnlright.Size = new System.Drawing.Size(2, 461); this.pnlright.TabIndex = 3; this.pnlright.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseDown); this.pnlright.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseMove); this.pnlright.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlright_MouseUp); // // pnlcontents // this.pnlcontents.BackColor = System.Drawing.Color.Black; this.pnlcontents.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlcontents.ForeColor = System.Drawing.Color.White; this.pnlcontents.Location = new System.Drawing.Point(2, 30); this.pnlcontents.Name = "pnlcontents"; this.pnlcontents.Size = new System.Drawing.Size(726, 461); this.pnlcontents.TabIndex = 4; // // WindowBorder // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(730, 493); this.Controls.Add(this.pnlcontents); this.Controls.Add(this.pnlright); this.Controls.Add(this.pnlleft); this.Controls.Add(this.pnlbottom); this.Controls.Add(this.pnltitle); this.Name = "WindowBorder"; this.Load += new System.EventHandler(this.WindowBorder_Load); this.pnltitle.ResumeLayout(false); this.pnltitle.PerformLayout(); this.pnlbottom.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel pnltitle; private System.Windows.Forms.Label lbtitletext; private System.Windows.Forms.Panel pnlminimize; private System.Windows.Forms.Panel pnlmaximize; private System.Windows.Forms.Panel pnlclose; private System.Windows.Forms.Panel pnlbottom; private System.Windows.Forms.Panel pnlbottomr; private System.Windows.Forms.Panel pnlbottoml; private System.Windows.Forms.Panel pnlleft; private System.Windows.Forms.Panel pnlright; private System.Windows.Forms.Panel pnlcontents; private System.Windows.Forms.Panel pnltitleright; private System.Windows.Forms.Panel pnltitleleft; private System.Windows.Forms.Panel pnlicon; } }
53.719298
160
0.642391
[ "MIT" ]
Gamer-Gaming/shiftos
ShiftOS.WinForms/WindowBorder.Designer.cs
15,310
C#
using System; using System.IO; using System.Net; namespace xpm.Utils { internal class Package { public static void UninstallPackage(string query, bool askYN) { if (Directory.Exists(Config.installFolder + @"\packages\" + query)) { if (askYN) { Console.Write(Config.messageStart + " Package found, would you like to uninstall? (y/n): "); ConsoleKeyInfo keypress = Console.ReadKey(true); Console.WriteLine(keypress.KeyChar); if (keypress.KeyChar == 'y') { Console.WriteLine(" Removing program files"); Directory.Delete(Config.installFolder + @"\packages\" + query, true); Console.WriteLine(" Removing start menu shortcut"); File.Delete(@"C:\Users\" + Environment.UserName + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\" + query + ".lnk"); Console.WriteLine(" Removing path variable"); var currentValue = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User); var newValue = currentValue .Replace(";" + Config.installFolder + @"\packages\" + query + @"\bin\", string.Empty) .Replace(";" + Config.installFolder + @"\packages\" + query, string.Empty); Environment.SetEnvironmentVariable("Path", newValue, EnvironmentVariableTarget.User); Console.WriteLine(Config.messageStart + " Done"); } else { Environment.Exit(1); Console.WriteLine("Operation cancelled."); } } else { Console.WriteLine(Config.messageStart + " Uninstalling package"); Console.WriteLine(" Removing program files"); Directory.Delete(Config.installFolder + @"\packages\" + query, true); Console.WriteLine(" Removing start menu shortcut"); File.Delete(@"C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\" + query + ".lnk"); Console.WriteLine(" Removing path variable"); var currentValue = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User); var newValue = currentValue .Replace(";" + Config.installFolder + @"\packages\" + query + @"\bin\", string.Empty) .Replace(";" + Config.installFolder + @"\packages\" + query, string.Empty); Environment.SetEnvironmentVariable("Path", newValue, EnvironmentVariableTarget.User); Console.WriteLine(" Done"); } } } public static void InstallPackage(string query, bool askYN) { Utils.Mirror.UpdateMirrors(); string[] mirrors = Directory.GetFiles(Config.installFolder + @"\mirrors"); foreach (string mirror in mirrors) { string[] mirrorContent = File.ReadAllLines(mirror); foreach (string line in mirrorContent) { string[] lineSplit = line.Split(new string[] { ";;;" }, StringSplitOptions.None); if (lineSplit[0] == query) { var client = new WebClient(); client.DownloadFile(lineSplit[1], Config.installFolder + @"\cache\" + lineSplit[0] + ".pkg"); //Config.installFolder + @"\cache\" + lineSplit[1] + ".pkg" Extra.ParsePKG(Config.installFolder + @"\cache\" + lineSplit[0] + ".pkg", true); Console.WriteLine(Config.messageStart + " Package Details"); Console.WriteLine(" Name: " + lineSplit[0]); Console.WriteLine(" Made by: " + Utils.Extra.AUTHOR); Console.WriteLine(" Desc: " + Extra.DESC); Console.WriteLine(" License: " + Extra.LICENSE); Console.Write(Config.messageStart + " Would you like to proceed? (y/n): "); if (askYN) { ConsoleKeyInfo keypress = Console.ReadKey(true); Console.WriteLine(keypress.KeyChar); if (keypress.KeyChar == 'y') { Extra.ParsePKG(Config.installFolder + @"\cache\" + lineSplit[0] + ".pkg", false); } else { Console.WriteLine("Operation cancelled."); Environment.Exit(1); } } else { Extra.ParsePKG(Config.installFolder + @"\cache\" + lineSplit[0] + ".pkg", false); } } } } // CommitPackage(Extra.METANAME, Extra.METAAUTHOR); } public static void CommitPackage(string name, string author) { if (!File.Exists(Config.installFolder + @"\packages.txt")) { File.WriteAllText(Config.installFolder + @"\packages.txt", ""); // Creates file without locking it with a fstream; } File.AppendAllText(Config.installFolder + @"\packages.txt", "\n" + name + ";" + author); } public static void ListInstalledPackages() { string[] packages = Directory.GetDirectories(Config.installFolder + @"\packages\"); Console.Write(Config.messageStart + " Listing all installed packages\n"); foreach (string package in packages) { string packageTrimmed = package.Replace(Config.installFolder + @"\packages\", string.Empty); Console.WriteLine(" " + packageTrimmed); } } public static void ListInstallablePackages() { Console.Write(Config.messageStart + " Listing available packages\n"); string[] mirrors = Directory.GetFiles(Config.installFolder + @"\mirrors\"); foreach (string mirror in mirrors) { string[] mirrorContent = File.ReadAllLines(mirror); foreach (string line in mirrorContent) { Console.WriteLine(" " + line.Split(new string[] { ";;;" }, StringSplitOptions.None)[0]); } } } public static void SearchInstallablePackages(string query) { Console.Write(Config.messageStart + " Listing available packages\n"); string[] mirrors = Directory.GetFiles(Config.installFolder + @"\mirrors\"); foreach (string mirror in mirrors) { string[] mirrorContent = File.ReadAllLines(mirror); foreach (string line in mirrorContent) { if (line.Split(new string[] { ";;;" }, StringSplitOptions.None)[0] == query) { Console.WriteLine(" " + line.Split(new string[] { ";;;" }, StringSplitOptions.None)[0]); } } } } public static void UpdateAll() { string[] packages = Directory.GetDirectories(Config.installFolder + @"\packages\"); foreach (string package in packages) { UninstallPackage(package.Replace(Config.installFolder + @"\packages\", string.Empty), false); InstallPackage(package.Replace(Config.installFolder + @"\packages\", string.Empty), false); } } } }
51.953947
151
0.5126
[ "Unlicense" ]
xsucculentx/xpm
Utils/Package.cs
7,899
C#
// --------------------------------------------------------------- // Copyright (c) Coalition of the Good-Hearted Engineers // FREE TO USE TO CONNECT THE WORLD // --------------------------------------------------------------- using System; using System.Collections; using System.Net.Http; using System.Threading.Tasks; using Moq; using RESTFulSense.Exceptions; using Taarafo.Portal.Web.Models.Posts; using Taarafo.Portal.Web.Models.Posts.Exceptions; using Xunit; namespace Taarafo.Portal.Web.Tests.Unit.Services.Foundations.Posts { public partial class PostServiceTests { [Theory] [MemberData(nameof(CriticalDependencyExceptions))] public async Task ShouldThrowCriticalDependencyExceptionOnAddifCriticalErrorOccursAndLogItAsync( Exception criticalDependencyException) { // given Post somePost = CreateRandomPost(); var failedPostDependencyException = new FailedPostDependencyException(criticalDependencyException); var expectedPostDependencyException = new PostDependencyException(failedPostDependencyException); this.apiBrokerMock.Setup(broker => broker.PostPostAsync(It.IsAny<Post>())) .ThrowsAsync(criticalDependencyException); // when ValueTask<Post> addPostTask = this.postService.AddPostAsync(somePost); // then await Assert.ThrowsAsync<PostDependencyException>(() => addPostTask.AsTask()); this.apiBrokerMock.Verify(broker => broker.PostPostAsync(It.IsAny<Post>()), Times.Once); this.loggingBrokerMock.Verify(broker => broker.LogCritical(It.Is(SameExceptionAs( expectedPostDependencyException))), Times.Once); this.apiBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); } [Fact] public async Task ShouldThrowDependencyValidationExceptionOnAddIfBadRequestExceptionOccursAndLogItAsync() { // given Post somePost = CreateRandomPost(); IDictionary randomDictionary = CreateRandomDictionary(); IDictionary exceptionData = randomDictionary; string someMessage = GetRandomMessage(); var someRepsonseMessage = new HttpResponseMessage(); var httpResponseBadRequestException = new HttpResponseBadRequestException( someRepsonseMessage, someMessage); httpResponseBadRequestException.AddData(exceptionData); var invalidPostException = new InvalidPostException( httpResponseBadRequestException, exceptionData); var expectedPostDependencyValidationException = new PostDependencyValidationException(invalidPostException); this.apiBrokerMock.Setup(broker => broker.PostPostAsync(It.IsAny<Post>())) .ThrowsAsync(httpResponseBadRequestException); // when ValueTask<Post> addPostTask = this.postService.AddPostAsync(somePost); // then await Assert.ThrowsAsync<PostDependencyValidationException>(() => addPostTask.AsTask()); this.apiBrokerMock.Verify(broker => broker.PostPostAsync(It.IsAny<Post>()), Times.Once); this.loggingBrokerMock.Verify(broker => broker.LogError(It.Is(SameExceptionAs( expectedPostDependencyValidationException))), Times.Once); this.apiBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); } [Fact] public async Task ShouldThrowDependencyValidationExceptionOnAddIfConflictExceptionOccursAndLogItAsync() { // given Post somePost = CreateRandomPost(); IDictionary randomDictionary = CreateRandomDictionary(); IDictionary exceptionData = randomDictionary; string someMessage = GetRandomMessage(); var someRepsonseMessage = new HttpResponseMessage(); var httpResponseConflictException = new HttpResponseConflictException( someRepsonseMessage, someMessage); httpResponseConflictException.AddData(exceptionData); var invalidPostException = new InvalidPostException( httpResponseConflictException, exceptionData); var expectedPostDependencyValidationException = new PostDependencyValidationException(invalidPostException); this.apiBrokerMock.Setup(broker => broker.PostPostAsync(It.IsAny<Post>())) .ThrowsAsync(httpResponseConflictException); // when ValueTask<Post> addPostTask = this.postService.AddPostAsync(somePost); // then await Assert.ThrowsAsync<PostDependencyValidationException>(() => addPostTask.AsTask()); this.apiBrokerMock.Verify(broker => broker.PostPostAsync(It.IsAny<Post>()), Times.Once); this.loggingBrokerMock.Verify(broker => broker.LogError(It.Is(SameExceptionAs( expectedPostDependencyValidationException))), Times.Once); this.apiBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); } [Fact] public async Task ShouldThrowPostDependencyExceptionOnAddIfResponseExceptionOccursAndLogItAsync() { // given Post somePost = CreateRandomPost(); string someMessage = GetRandomMessage(); var httpResponseMessage = new HttpResponseMessage(); var httpResponseException = new HttpResponseException( httpResponseMessage, someMessage); var failedPostDependencyException = new FailedPostDependencyException(httpResponseException); var expectedPostDependencyException = new PostDependencyException(failedPostDependencyException); this.apiBrokerMock.Setup(broker => broker.PostPostAsync(It.IsAny<Post>())) .ThrowsAsync(httpResponseException); // when ValueTask<Post> addPostTask = this.postService.AddPostAsync(somePost); // then await Assert.ThrowsAsync<PostDependencyException>(() => addPostTask.AsTask()); this.apiBrokerMock.Verify(broker => broker.PostPostAsync(It.IsAny<Post>()), Times.Once); this.loggingBrokerMock.Verify(broker => broker.LogError(It.Is(SameExceptionAs( expectedPostDependencyException))), Times.Once); this.apiBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); } [Fact] public async Task ShouldThrowServiceExceptionOnAddIfServiceErrorOccursAndLogItAsync() { // given Post somePost = CreateRandomPost(); var serviceException = new Exception(); var failedPostServiceException = new FailedPostServiceException(serviceException); var expectedPostServiceException = new PostServiceException(failedPostServiceException); this.apiBrokerMock.Setup(broker => broker.PostPostAsync(It.IsAny<Post>())) .ThrowsAsync(serviceException); // when ValueTask<Post> addPostTask = this.postService.AddPostAsync(somePost); // then await Assert.ThrowsAsync<PostServiceException>(() => addPostTask.AsTask()); this.apiBrokerMock.Verify(broker => broker.PostPostAsync(It.IsAny<Post>()), Times.Once); this.loggingBrokerMock.Verify(broker => broker.LogError(It.Is(SameExceptionAs( expectedPostServiceException))), Times.Once); this.apiBrokerMock.VerifyNoOtherCalls(); this.loggingBrokerMock.VerifyNoOtherCalls(); } } }
36.09465
113
0.589785
[ "MIT" ]
ElbekDeveloper/Taarafo.Web
Taarafo.Portal.Web.Tests.Unit/Services/Foundations/Posts/PostServiceTests.Exceptions.Add.cs
8,773
C#
namespace commercetools.Sdk.Domain.Products.UpdateActions { public class RevertStagedVariantChangesUpdateAction : UpdateAction<Product> { public string Action => "revertStagedVariantChanges"; public int VariantId { get; set; } } }
32.375
79
0.725869
[ "Apache-2.0" ]
commercetools/commercetools-dotnet-core-sdk
commercetools.Sdk/commercetools.Sdk.Domain/Products/UpdateActions/RevertStagedVariantChangesUpdateAction.cs
261
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Collections.ObjectModel.Tests { public class CollectionTestBase { protected static readonly int[] s_intArray = new[] { -4, 5, -2, 3, 1, 2, -1, -3, 0, 4, -5, 3, 3 }; protected static readonly int[] s_excludedFromIntArray = new int[] { 100, -34, 42, int.MaxValue, int.MinValue }; [Flags] protected enum IListApi { None = 0, IndexerGet = 0x1, IndexerSet = 0x2, Count = 0x4, IsReadOnly = 0x8, Clear = 0x10, Contains = 0x20, CopyTo = 0x40, GetEnumeratorGeneric = 0x80, IndexOf = 0x100, Insert = 0x200, RemoveAt = 0x400, GetEnumerator = 0x800, End } protected class CallTrackingIList<T> : IList<T> { private IListApi _expectedApiCalls; private IListApi _calledMembers; public CallTrackingIList(IListApi expectedApiCalls) { _expectedApiCalls = expectedApiCalls; } public void AssertAllMembersCalled() { if (_expectedApiCalls != _calledMembers) { for (IListApi i = (IListApi)1; i < IListApi.End; i = (IListApi)((int)i << 1)) { Assert.Equal(_expectedApiCalls & i, _calledMembers & i); } } } public T this[int index] { get { _calledMembers |= IListApi.IndexerGet; return default(T); } set { _calledMembers |= IListApi.IndexerSet; } } public int Count { get { _calledMembers |= IListApi.Count; return 1; } } public bool IsReadOnly { get { _calledMembers |= IListApi.IsReadOnly; return false; } } public void Add(T item) { throw new NotImplementedException(); } public void Clear() { _calledMembers |= IListApi.Clear; } public bool Contains(T item) { _calledMembers |= IListApi.Contains; return false; } public void CopyTo(T[] array, int arrayIndex) { _calledMembers |= IListApi.CopyTo; } public IEnumerator<T> GetEnumerator() { _calledMembers |= IListApi.GetEnumeratorGeneric; return null; } public int IndexOf(T item) { _calledMembers |= IListApi.IndexOf; return -1; } public void Insert(int index, T item) { _calledMembers |= IListApi.Insert; } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { _calledMembers |= IListApi.RemoveAt; } IEnumerator IEnumerable.GetEnumerator() { _calledMembers |= IListApi.GetEnumerator; return null; } } } }
25.1125
97
0.422598
[ "MIT" ]
belav/runtime
src/libraries/System.Runtime/tests/System/Collections/ObjectModel/CollectionTestBase.cs
4,018
C#
namespace MadHoneyStore.Web.Controllers { using System; using System.Threading.Tasks; using MadHoneyStore.Data.Common.Repositories; using MadHoneyStore.Data.Models; using MadHoneyStore.Services.Data; using MadHoneyStore.Web.ViewModels.Settings; using Microsoft.AspNetCore.Mvc; public class SettingsController : BaseController { private readonly ISettingsService settingsService; private readonly IDeletableEntityRepository<Setting> repository; public SettingsController(ISettingsService settingsService, IDeletableEntityRepository<Setting> repository) { this.settingsService = settingsService; this.repository = repository; } public IActionResult Index() { var settings = this.settingsService.GetAll<SettingViewModel>(); var model = new SettingsListViewModel { Settings = settings }; return this.View(model); } public async Task<IActionResult> InsertSetting() { var random = new Random(); var setting = new Setting { Name = $"Name_{random.Next()}", Value = $"Value_{random.Next()}" }; await this.repository.AddAsync(setting); await this.repository.SaveChangesAsync(); return this.RedirectToAction(nameof(this.Index)); } } }
31.409091
115
0.65919
[ "MIT" ]
russeva/MadHoneyStore
src/Web/MadHoneyStore.Web/Controllers/SettingsController.cs
1,384
C#
using System; using System.IO; using System.Linq; using Abp.Reflection.Extensions; namespace InventoryControl.Web { /// <summary> /// This class is used to find root path of the web project in; /// unit tests (to find views) and entity framework core command line commands (to find conn string). /// </summary> public static class WebContentDirectoryFinder { public static string CalculateContentRootFolder() { var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(InventoryControlCoreModule).GetAssembly().Location); if (coreAssemblyDirectoryPath == null) { throw new Exception("Could not find location of InventoryControl.Core assembly!"); } var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath); while (!DirectoryContains(directoryInfo.FullName, "InventoryControl.sln")) { if (directoryInfo.Parent == null) { throw new Exception("Could not find content root folder!"); } directoryInfo = directoryInfo.Parent; } var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "InventoryControl.Web.Mvc"); if (Directory.Exists(webMvcFolder)) { return webMvcFolder; } var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "InventoryControl.Web.Host"); if (Directory.Exists(webHostFolder)) { return webHostFolder; } throw new Exception("Could not find root folder of the web project!"); } private static bool DirectoryContains(string directory, string fileName) { return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName)); } } }
35.833333
125
0.610853
[ "MIT" ]
lucaslsilva/InventoryControl
aspnet-core/src/InventoryControl.Core/Web/WebContentFolderHelper.cs
1,937
C#
using FakeItEasy; using NUnit.Framework; using Penneo; namespace PenneoTests { [TestFixture] public class SignatureLineTests { private static SignatureLine CreateSignatureLine() { var cf = new CaseFile(); var doc = new Document(cf); var s = new SignatureLine(doc, "role", 1, "conditions"); return s; } [Test] public void ConstructorTest() { var s = CreateSignatureLine(); Assert.IsNotNull(s.Document); Assert.AreEqual("role", s.Role); Assert.AreEqual(1, s.SignOrder); Assert.AreEqual("conditions", s.Conditions); Assert.AreEqual(s.Document, s.Parent); } [Test] public void PersistSuccessTest() { TestUtil.TestPersist(CreateSignatureLine); } [Test] public void PersistFailTest() { TestUtil.TestPersistFail(CreateSignatureLine); } [Test] public void DeleteTest() { TestUtil.TestDelete(CreateSignatureLine); } [Test] public void GetTest() { TestUtil.TestGet<SignatureLine>(); } [Test] public void SetSignerSuccessTest() { var sl = CreateSignatureLine(); var s = new Signer(sl.Document.CaseFile); var connector = TestUtil.CreateFakeConnector(); A.CallTo(() => connector.LinkEntity(sl, s)).Returns(true); sl.SetSigner(s); Assert.AreEqual(s, sl.Signer); A.CallTo(() => connector.LinkEntity(sl, s)).MustHaveHappened(); } [Test] public void SetSignerFailTest() { var sl = CreateSignatureLine(); var s = new Signer(sl.Document.CaseFile); var connector = TestUtil.CreateFakeConnector(); A.CallTo(() => connector.LinkEntity(sl, s)).Returns(false); try { var result = sl.SetSigner(s); Assert.IsFalse(result); } finally { A.CallTo(() => connector.LinkEntity(sl, s)).MustHaveHappened(); } } } }
25.920455
79
0.516879
[ "Apache-2.0" ]
hougaard/sdk-net
Src/PenneoTests/SignatureLineTests.cs
2,283
C#
//------------------------------------------------------------------------------ // <copyright file="Allocator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // </copyright> //------------------------------------------------------------------------------ using System; using System.Buffers; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Microsoft.Azure.Kinect.Sensor.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f54d726c53826f259c2372d3fe68e1a122f58989796aa52500b930ff33cb0e57431b25a780b0d55c45470c8835f7a335425ef6706f9dbcf7046fe6f479d723a51f6c2c9630d986b5cadb47094d5fd6c64cb144736af739fc071cb53c1296d27e38ee99a2ac2329ed141e645b4669b32568a71607c8f7e986418825f2d37c48cf")] namespace Microsoft.Azure.Kinect.Sensor { /// <summary> /// Manages buffer allocation. /// </summary> internal class Allocator { // Objects we are tracking for disposal prior to CLR shutdown private readonly HashSet<WeakReference<IDisposable>> disposables = new HashSet<WeakReference<IDisposable>>(); // Allocations made by the managed code for the native library private readonly SortedDictionary<long, AllocationContext> allocations = new SortedDictionary<long, AllocationContext>(); // A recyclable large array pool to prevent unnecessary managed allocations and clearing of memory private readonly ArrayPool<byte> pool = new LargeArrayPool(); // Managed buffers used as caches for the native memory. private readonly Dictionary<IntPtr, BufferCacheEntry> bufferCache = new Dictionary<IntPtr, BufferCacheEntry>(); // Native delegates private readonly NativeMethods.k4a_memory_allocate_cb_t allocateDelegate; private readonly NativeMethods.k4a_memory_destroy_cb_t freeDelegate; // Native allocator hook state private bool hooked = false; // This is set when the CLR is shutting down, causing an exception during // any new object registrations. private bool noMoreDisposalRegistrations = false; private Allocator() { this.allocateDelegate = new NativeMethods.k4a_memory_allocate_cb_t(this.AllocateFunction); this.freeDelegate = new NativeMethods.k4a_memory_destroy_cb_t(this.FreeFunction); // Register for ProcessExit and DomainUnload to allow us to unhook the native layer before // native to managed callbacks are no longer allowed. AppDomain.CurrentDomain.DomainUnload += this.ApplicationExit; AppDomain.CurrentDomain.ProcessExit += this.ApplicationExit; // Default to the safe and performant configuration // Use Managed Allocator will cause the native layer to allocate from managed byte[] arrays when possible // these can then be safely referenced with a Memory<T> and exposed to user code. This should have fairly // minimal performance impact, but provides strong memory safety. this.UseManagedAllocator = true; // When managed code needs to provide access to memory that didn't originate from the managed allocator // the SafeCopyNativeBuffers options causes the managed code to make a safe cache copy of the native buffer // in a managed byte[] array. This has a more significant performance impact, but generally is only needed for // media foundation (color image) or potentially custom buffers. When set to true, the Memory<T> objects are safe // copies of the native buffers. When set to false, the Memory<T> objects are direct pointers to the native buffers // and can therefore cause native memory corruption if a Memory<T> (or Span<T>) is used after the Image is disposed // or garbage collected. this.SafeCopyNativeBuffers = true; } /// <summary> /// Gets the Allocator. /// </summary> public static Allocator Singleton { get; } = new Allocator(); /// <summary> /// Gets or sets a value indicating whether to have the native library use the managed allocator. /// </summary> public bool UseManagedAllocator { get => this.hooked; set { lock (this) { if (value && !this.hooked) { try { AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_set_allocator(this.allocateDelegate, this.freeDelegate)); this.hooked = true; } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception) #pragma warning restore CA1031 // Do not catch general exception types { // Don't fail if we can't set the allocator since this code path is called during the global type // initialization. A failure to set the allocator is also not fatal, but will only cause a performance // issue. System.Diagnostics.Debug.WriteLine("Unable to hook native allocator"); } } if (!value && this.hooked) { // Disabling the hook once it has been enabled should not catch the exception AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_set_allocator(null, null)); this.hooked = false; } } } } /// <summary> /// Gets or sets a value indicating whether to make a safe copy of native buffers. /// </summary> public bool SafeCopyNativeBuffers { get; set; } = true; /// <summary> /// Register the object for disposal when the CLR shuts down. /// </summary> /// <param name="disposable">Object to dispose before native hooks are disconnected.</param> /// <remarks> /// When the CLR shuts down, native callbacks in to the CLR result in an application crash. The allocator free method /// is a native callback to the managed layer that is called whenever the hooked native API needs to free memory. /// /// To avoid this callback after the CLR shuts down, the native library must be completely cleaned up prior CLR shutdown. /// /// Any object that may hold references to the native library (and will therefore generate native to manged callbacks when it /// gets cleaned up) should register with the RegisterForDisposal method to ensure it is cleaned up in the correct order. /// during shutdown. /// </remarks> public void RegisterForDisposal(IDisposable disposable) { lock (this) { if (this.noMoreDisposalRegistrations) { throw new InvalidOperationException("New objects may not be registered during shutdown."); } // Track the object as one we may need to dispose during shutdown. // Use a weak reference to allow the object to be garbage collected earlier if possible. _ = this.disposables.Add(new WeakReference<IDisposable>(disposable)); } } /// <summary> /// Unregister the object for disposal. /// </summary> /// <param name="disposable">Object to unregister.</param> /// <remarks> /// This does not unhook the native allocator, but only unregisters the object for /// disposal. /// </remarks> public void UnregisterForDisposal(IDisposable disposable) { lock (this) { // Remove the object and clean up any dead weak references. _ = this.disposables.RemoveWhere((r) => { bool alive = r.TryGetTarget(out IDisposable target); return !alive || target == disposable; }); } } /// <summary> /// Get a Memory reference to the managed memory that was used by the hooked native /// allocator. /// </summary> /// <param name="address">Native address of the memory.</param> /// <param name="size">Size of the memory region.</param> /// <returns>Reference to the memory, or an empty memory reference.</returns> /// <remarks> /// If the address originally came from a managed array that was provided to the native /// API through the allocator hook, this function will return a Memory reference to the managed /// memory. Since this is a reference to the managed memory and not the native pointer, it /// is safe and not subject to use after free bugs. /// /// The address and size do not need to reference the exact pointer provided to the native layer /// by the allocator, but can refer to any region in the allocated memory. /// </remarks> public Memory<byte> GetManagedAllocatedMemory(IntPtr address, long size) { lock (this) { AllocationContext allocation = this.FindNearestContext(address); if (allocation == null) { return null; } long offset = (long)address - (long)allocation.BufferAddress; // Check that the beginning of the memory is in this allocation if (offset > allocation.Buffer.LongLength) { return null; } // Check that the end of the memory is in this allocation if (checked(offset + size) > allocation.Buffer.LongLength) { return null; } // Return a reference to this memory return new Memory<byte>(allocation.Buffer, checked((int)offset), checked((int)size)); } } /// <summary> /// Get a managed array to cache the contents of a native buffer. /// </summary> /// <param name="nativeAddress">Native buffer to mirror.</param> /// <param name="size">Size of the native memory.</param> /// <returns>A managed array populated with the content of the native buffer.</returns> /// <remarks>Multiple callers asking for the same address will get the same buffer. /// When done with the buffer the caller must call <seealso cref="ReturnBufferCache(IntPtr)"/>. /// </remarks> public byte[] GetBufferCache(IntPtr nativeAddress, int size) { BufferCacheEntry entry; lock (this) { if (this.bufferCache.ContainsKey(nativeAddress)) { entry = this.bufferCache[nativeAddress]; entry.ReferenceCount++; if (entry.UsedSize != size) { throw new AzureKinectException("Multiple image buffers sharing the same address cannot have the same size"); } } else { entry = new BufferCacheEntry { ManagedBufferCache = this.pool.Rent(size), UsedSize = size, ReferenceCount = 1, Initialized = false, }; this.bufferCache.Add(nativeAddress, entry); } } lock (entry) { if (!entry.Initialized) { Marshal.Copy(nativeAddress, entry.ManagedBufferCache, 0, entry.UsedSize); entry.Initialized = true; } } return entry.ManagedBufferCache; } /// <summary> /// Return the buffer cache. /// </summary> /// <param name="nativeAddress">Address of the native buffer.</param> /// <remarks>Must be called exactly once for each buffer provided by <see cref="GetBufferCache(IntPtr, int)"/>.</remarks> public void ReturnBufferCache(IntPtr nativeAddress) { lock (this) { BufferCacheEntry entry = this.bufferCache[nativeAddress]; entry.ReferenceCount--; if (entry.ReferenceCount == 0) { this.pool.Return(entry.ManagedBufferCache); _ = this.bufferCache.Remove(nativeAddress); } } } // Find the allocation context who's address is closest but not // greater than the search address private AllocationContext FindNearestContext(IntPtr address) { lock (this) { long[] keys = new long[this.allocations.Count]; this.allocations.Keys.CopyTo(keys, 0); int searchIndex = Array.BinarySearch(keys, (long)address); if (searchIndex >= 0) { return this.allocations[keys[searchIndex]]; } else { int nextLowestIndex = ~searchIndex - 1; if (nextLowestIndex < 0) { return null; } AllocationContext allocation = this.allocations[keys[nextLowestIndex]]; return allocation; } } } // This function is called by the native layer to allocate memory private IntPtr AllocateFunction(int size, out IntPtr context) { byte[] buffer = this.pool.Rent(size); AllocationContext allocationContext = new AllocationContext() { Buffer = buffer, BufferPin = GCHandle.Alloc(buffer, GCHandleType.Pinned), CallbackDelegate = this.freeDelegate, }; allocationContext.BufferAddress = allocationContext.BufferPin.AddrOfPinnedObject(); context = (IntPtr)GCHandle.Alloc(allocationContext); lock (this) { this.allocations.Add((long)allocationContext.BufferAddress, allocationContext); } return allocationContext.BufferAddress; } // This function is called by the native layer to free memory private void FreeFunction(IntPtr buffer, IntPtr context) { GCHandle contextPin = (GCHandle)context; AllocationContext allocationContext = (AllocationContext)contextPin.Target; lock (this) { System.Diagnostics.Debug.Assert(object.ReferenceEquals(this.allocations[(long)buffer], allocationContext), "Allocation context does not match expected value"); _ = this.allocations.Remove((long)buffer); } allocationContext.BufferPin.Free(); this.pool.Return(allocationContext.Buffer); contextPin.Free(); } // Called when the AppDomain is unloaded or the application exits private void ApplicationExit(object sender, EventArgs e) { lock (this) { // Disable the managed allocator hook to ensure no new allocations this.UseManagedAllocator = false; // Prevent more disposal registrations while we are cleaning up this.noMoreDisposalRegistrations = true; System.Diagnostics.Debug.WriteLine($"Disposable count {this.disposables.Count} (Allocation Count {this.allocations.Count})"); // First dispose of all the registered objects // Don't dispose of the objects during this loop since a // side effect of disposing of an object may be the object unregistering itself // and causing the collection to be modified. List<IDisposable> disposeList = new List<IDisposable>(); foreach (WeakReference<IDisposable> r in this.disposables) { if (r.TryGetTarget(out IDisposable disposable)) { disposeList.Add(disposable); } } this.disposables.Clear(); foreach (IDisposable disposable in disposeList) { System.Diagnostics.Debug.WriteLine($"Disposed {disposable.GetType().FullName} (Allocation Count {this.allocations.Count})"); disposable.Dispose(); } // If the allocation count is not zero, we will be called again with a free function // if this happens after the CLR has entered shutdown, the CLR will generate an exception. if (this.allocations.Count > 0) { throw new AzureKinectException("Not all native allocations have been freed before managed shutdown"); } } } private class AllocationContext { public byte[] Buffer { get; set; } public IntPtr BufferAddress { get; set; } public GCHandle BufferPin { get; set; } public NativeMethods.k4a_memory_destroy_cb_t CallbackDelegate { get; set; } } private class BufferCacheEntry { public byte[] ManagedBufferCache { get; set; } public int UsedSize { get; set; } public int ReferenceCount { get; set; } public bool Initialized { get; set; } } } }
43.122931
405
0.573927
[ "MIT" ]
valdperformance/Azure-Kinect-Sensor-SDK
src/csharp/SDK/Allocator.cs
18,241
C#
using BotSharp.Core.Abstractions; using BotSharp.Platform.Models; using BotSharp.Platform.Models.MachineLearning; using Microsoft.Extensions.Configuration; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace BotSharp.Core.Engines.BotSharp { public class BotSharpProvider : INlpProvider { public IConfiguration Configuration { get; set; } public PipeSettings Settings { get; set; } public async Task<bool> Load(AgentBase agent, PipeModel meta) { meta.Meta = JObject.FromObject(new { version = "0.1.0" }); return true; } } }
26.384615
70
0.702624
[ "Apache-2.0" ]
Ali-NLP-and-DeepLearning-Lab/AI-ChatBot-Builder-CSharp
BotSharp.Core/Engines/BotSharp/BotSharpProvider.cs
688
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using atriumBE; using lmDatasets; namespace lmras.Calendar { public partial class Default : System.Web.UI.Page { AtriumApp appMan; atriumManager atMng; FileManager FM; OfficeManager myOfficeMng; protected void Page_Load(object sender, EventArgs e) { //try //{ appMan = new AtriumApp("ENG", "DATABASE1"); //} //catch (Exception x) //{ // string s = x.Message; //} atMng = appMan.AtMng; FM = atMng.GetFile(); myOfficeMng = atMng.GetOffice(atMng.OfficeLoggedOn.OfficeId); myOfficeMng.GetOfficerDelegate().LoadByDelegateToId(atMng.OfficerLoggedOn.OfficerId); Session["AtriumManager"] = atMng; string url = string.Empty; url = ResolveServerUrl("~/Calendar/UserCalendar.aspx"); url = url.Replace("http://", ""); foreach (officeDB.OfficerDelegateRow odr in myOfficeMng.DB.OfficerDelegate) { string link = string.Empty; if (odr.WorkAs) { atriumDB.ContactRow cr = FM.GetPerson().Load(odr.OfficerId); link = "<a href='webcal://" + url + "?contactid=" + odr.OfficerId.ToString() + "'>"; Response.Write(link + "Atrium Calendar for " +cr.FirstName + " " + cr.LastName + "</a>"); Response.Write("<br />"); } } // create calendar link for self Response.Write("<a href='webcal://" + url + "?contactid=" + atMng.OfficerLoggedOn.ContactId.ToString() + "'>My Calendar</a>"); } //public string ResolveUrl(string originalUrl) //{ // if (originalUrl == null) // return null; // if (originalUrl.IndexOf("://") != -1) // return originalUrl; // if (originalUrl.StartsWith("~")) // { // string newUrl = ""; // if (HttpContext.Current != null) // newUrl = HttpContext.Current.Request.ApplicationPath + originalUrl.Substring(1).Replace("//", "/"); // else // throw new ArgumentException("Invalid URL: Relative URL not allowed."); // return newUrl; // } // return originalUrl; //} public string ResolveServerUrl(string serverUrl, bool forceHttps) { if (serverUrl.IndexOf("://") > -1) return serverUrl; string newUrl = ResolveUrl(serverUrl); Uri originalUri = HttpContext.Current.Request.Url; newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl; return newUrl; } public string ResolveServerUrl(string serverUrl) { return ResolveServerUrl(serverUrl, false); } } }
34.22449
140
0.501789
[ "MIT" ]
chris-weekes/atrium
lmras/Calendar/Default.aspx.cs
3,356
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.imm.Model.V20170906 { public class CreateStreamAnalyseTaskResponse : AcsResponse { private string requestId; private string taskId; private string taskType; public string RequestId { get { return requestId; } set { requestId = value; } } public string TaskId { get { return taskId; } set { taskId = value; } } public string TaskType { get { return taskType; } set { taskType = value; } } } }
20.28169
63
0.666667
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/CreateStreamAnalyseTaskResponse.cs
1,440
C#
using DataAccessLayer.ARAPReport; using DataAccessLayer.Common; using DataAccessLayer.FinanceReport; using DataAccessLayer.Interface.ARAPReport; using DataAccessLayer.Interface.FinanceReport; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace acmedesktop.FinanceReport { public partial class RptAllLedger : Form { IRptAllLedger _objRptAllLedger = new ClsRptAllLedger(); ClsCommon _objCommon = new ClsCommon(); static private PageSettings _myPageSettings = new PageSettings(); public RptAllLedger() { InitializeComponent(); this.Grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; } private void RptAllLedger_Load(object sender, EventArgs e) { this.Activated += AfterLoading; ToolTip ToolTip1 = new ToolTip(); ToolTip1.SetToolTip(this.BtnFilterOption, "Filter Option"); ToolTip1.SetToolTip(this.BtnPrint, "Print"); ToolTip1.SetToolTip(this.BtnEmail, "Email"); ToolTip1.SetToolTip(this.BtnAdvanceSearch, "Advance Search"); ToolTip1.SetToolTip(this.BtnExcel, "Export"); Grid.DefaultCellStyle.Font = new Font("Arial", 11F, GraphicsUnit.Pixel); } private void RptAllLedger_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } else if (e.KeyCode == Keys.F) { BtnFilterOption.PerformClick(); } } private void AfterLoading(object sender, EventArgs e) { this.Activated -= AfterLoading; FilterRptAllLedger frm = new FilterRptAllLedger(); frm.ShowDialog(); BindReport(frm); } private void BtnFilterOption_Click(object sender, EventArgs e) { FilterRptAllLedger frm = new FilterRptAllLedger(); frm.StartPosition = FormStartPosition.CenterScreen; frm.ShowDialog(); BindReport(frm); } private void BindReport(FilterRptAllLedger frm) { DataSet ds = new DataSet(); if (frm.ButtonAction == "OK") { DataTable NullDt = new DataTable(); Grid.DataSource = NullDt; DateTime FromDate = new DateTime(); DateTime ToDate = new DateTime(); if (ClsGlobal.DateType == "D") { FromDate = Convert.ToDateTime(frm.TxtFromDate.Text); ToDate = Convert.ToDateTime(frm.TxtToDate.Text); } else { FromDate = Convert.ToDateTime(frm.TxtFromDate.Tag.ToString()); ToDate = Convert.ToDateTime(frm.TxtToDate.Tag.ToString()); } if (frm.ChkDetails.Checked == true) //--------------- DETAILS LEDGER WISE ---------------- { bool isNarrationShow = (frm.ChkNarration.Checked == true) ? true : false; ds = _objRptAllLedger.AllLedgerDetailsLedgerWise(FromDate, ToDate, ClsGlobal.BranchId, ClsGlobal.CompanyUnitId, isNarrationShow, frm._LedgerId); Grid.DataSource = ds.Tables[0]; //Grid.Columns["Voucher No"].Width = 80; Grid.Columns["Date"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Particular/Ledger"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Dr Amount"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Cr Amount"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Balance"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Dr Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["Cr Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["Balance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; int i = 0; foreach (DataGridViewRow row in Grid.Rows) { if (row.Cells["IsBold"].Value.ToString() == "Y" || row.Cells["Particular/Ledger"].Value.ToString() == "Periodic Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "A/C Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Opening Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Periodic Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Total :" || row.Cells["Date"].Value.ToString() == "Narr :") { if (row.Cells["IsBold"].Value.ToString() == "Y") Grid.Rows[row.Index].DefaultCellStyle.Font = new Font("Arial", 8f, FontStyle.Bold); if (row.Cells["Particular/Ledger"].Value.ToString() == "Periodic Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "A/C Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Opening Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Periodic Total :" || row.Cells["Particular/Ledger"].Value.ToString() == "Grand Total :" ) Grid.Rows[row.Index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; if(row.Cells["Date"].Value.ToString() == "Narr :") { Grid.Rows[i].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Rows[row.Index].DefaultCellStyle.Font = new Font("Arial", 8f, FontStyle.Italic); } } i++; } } else //--------------- SUMMARY LEDGER WISE ---------------- { ds = _objRptAllLedger.AllLedgerSummaryLedgerWise(FromDate, ToDate, ClsGlobal.BranchId, ClsGlobal.CompanyUnitId, frm._LedgerId); Grid.DataSource = ds.Tables[0]; //Grid.Columns["Voucher No"].Width = 80; Grid.Columns["Code"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Description"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["O Dr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["O Cr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["P Dr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["P Cr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["Balance"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["C Dr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["C Cr"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Grid.Columns["O Dr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["O Cr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["P Dr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["P Cr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["Balance"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["C Dr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; Grid.Columns["C Cr"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; foreach (DataGridViewRow row in Grid.Rows) { if (row.Cells["IsBold"].Value.ToString() == "Y" || row.Cells["Description"].Value.ToString() == "Total :") { Grid.Rows[row.Index].DefaultCellStyle.Font = new Font("Arial", 8f, FontStyle.Bold); if (row.Cells["Description"].Value.ToString() == "Total :") Grid.Rows[row.Index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; } } } Grid.Columns["IsBold"].Visible = false; Grid.Columns.Cast<DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable); } frm.Dispose(); } private void BtnPrint_Click(object sender, EventArgs e) { PrintPreview("porterate", "YES"); } private void BtnPrintPreview_Click(object sender, EventArgs e) { contextMenuStrip1.Show(BtnPrintPreview, 0, BtnPrintPreview.Height); } private void BtnEmail_Click(object sender, EventArgs e) { } private void BtnAdvanceSearch_Click(object sender, EventArgs e) { } private void BtnExcel_Click(object sender, EventArgs e) { _objCommon.GridToExcel(Grid, "Sales Register"); } private void PorteratePrintPreview_Click(object sender, EventArgs e) { PrintPreview("porterate", "NO"); } private void LandscapePrintPreview_Click(object sender, EventArgs e) { PrintPreview("landscape", "NO"); } private void PrintPreview(string Mode, string IsPrint) { this.Width = Mode == "porterate" ? 763 : 1019; ////------------ PRINT PREVIEW DGVPrinter printer = new DGVPrinter(); printer.Title = LblCompanyName.Text; StringBuilder strSql = new StringBuilder(); if (!string.IsNullOrEmpty(LblCompanyAddress.Text)) strSql.Append(LblCompanyAddress.Text + "\n"); if (!string.IsNullOrEmpty(LblCompanyPhoneNo.Text)) strSql.Append(LblCompanyPhoneNo.Text + "\n"); strSql.Append("\n"); printer.SubTitle = strSql.ToString() + LblReportName.Text + "\n" + LblReportFromToDate.Text; printer.SubTitleSpacing = 5; //printer.SubTitle = string.Empty; printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip; printer.PageNumbers = true; printer.PageNumberInHeader = false; printer.PorportionalColumns = true; printer.HeaderCellAlignment = StringAlignment.Near; printer.ColumnWidth = DGVPrinter.ColumnWidthSetting.Porportional; printer.HeaderCellAlignment = StringAlignment.Near; printer.Footer = "FY :- " + ClsGlobal.CompanyFiscalYear; if (null != MyPageSettings) printer.printDocument.DefaultPageSettings = MyPageSettings; printer.PageSettings.Landscape = Mode == "porterate" ? false : true; MyPageSettings.Margins = new Margins(40, 60, 20, 60); printer.FooterSpacing = 5; printer.PreviewDialog = printPreviewDialog1; if (IsPrint == "YES") printer.PrintDataGridView(Grid); else printer.PrintPreviewDataGridView(Grid); this.Width = 1019; } private void RptAllLedger_Resize(object sender, EventArgs e) { BtnPrint.Enabled = WindowState != FormWindowState.Normal ? false : true; BtnPrintPreview.Enabled = WindowState != FormWindowState.Normal ? false : true; } static public PageSettings MyPageSettings { get { return _myPageSettings; } set { _myPageSettings = value; } } private void BtnClipboardCopy_Click(object sender, EventArgs e) { Grid.MultiSelect = true; Grid.SelectAll(); CopyToClipboardWithHeaders(Grid); //if (this.Grid.GetCellCount(DataGridViewElementStates.Selected) > 0) //{ // try // { // // Add the selection to the clipboard. // Clipboard.SetDataObject(this.Grid.GetClipboardContent()); // // Replace the text box contents with the clipboard text. // //this.TextBox1.Text = Clipboard.GetText(); // } // catch (System.Runtime.InteropServices.ExternalException) // { // MessageBox.Show("The Clipboard could not be accessed. Please try again."); // } //} } public void CopyToClipboardWithHeaders(DataGridView _dgv) { //Copy to clipboard _dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; DataObject dataObj = _dgv.GetClipboardContent(); if (dataObj != null) Clipboard.SetDataObject(dataObj); } } }
47.985866
490
0.584315
[ "MIT" ]
ajaykucse/LaraApp
acme/acmedesktop/FinanceReport/RptAllLedger.cs
13,582
C#
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - 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. * - Neither the name of the openmetaverse.co 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 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. */ using System; using System.Collections.Generic; using System.Net; using System.IO; using ComponentAce.Compression.Libs.zlib; using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; namespace OpenMetaverse.Messages.Linden { #region Teleport/Region/Movement Messages /// <summary> /// Sent to the client to indicate a teleport request has completed /// </summary> public class TeleportFinishMessage : IMessage { /// <summary>The <see cref="UUID"/> of the agent</summary> public UUID AgentID; /// <summary></summary> public int LocationID; /// <summary>The simulators handle the agent teleported to</summary> public ulong RegionHandle; /// <summary>A Uri which contains a list of Capabilities the simulator supports</summary> public Uri SeedCapability; /// <summary>Indicates the level of access required /// to access the simulator, or the content rating, or the simulators /// map status</summary> public SimAccess SimAccess; /// <summary>The IP Address of the simulator</summary> public IPAddress IP; /// <summary>The UDP Port the simulator will listen for UDP traffic on</summary> public int Port; /// <summary>Status flags indicating the state of the Agent upon arrival, Flying, etc.</summary> public TeleportFlags Flags; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); OSDArray infoArray = new OSDArray(1); OSDMap info = new OSDMap(8); info.Add("AgentID", OSD.FromUUID(AgentID)); info.Add("LocationID", OSD.FromInteger(LocationID)); // Unused by the client info.Add("RegionHandle", OSD.FromULong(RegionHandle)); info.Add("SeedCapability", OSD.FromUri(SeedCapability)); info.Add("SimAccess", OSD.FromInteger((byte)SimAccess)); info.Add("SimIP", MessageUtils.FromIP(IP)); info.Add("SimPort", OSD.FromInteger(Port)); info.Add("TeleportFlags", OSD.FromUInteger((uint)Flags)); infoArray.Add(info); map.Add("Info", infoArray); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray array = (OSDArray)map["Info"]; OSDMap blockMap = (OSDMap)array[0]; AgentID = blockMap["AgentID"].AsUUID(); LocationID = blockMap["LocationID"].AsInteger(); RegionHandle = blockMap["RegionHandle"].AsULong(); SeedCapability = blockMap["SeedCapability"].AsUri(); SimAccess = (SimAccess)blockMap["SimAccess"].AsInteger(); IP = MessageUtils.ToIP(blockMap["SimIP"]); Port = blockMap["SimPort"].AsInteger(); Flags = (TeleportFlags)blockMap["TeleportFlags"].AsUInteger(); } } /// <summary> /// Sent to the viewer when a neighboring simulator is requesting the agent make a connection to it. /// </summary> public class EstablishAgentCommunicationMessage : IMessage { public UUID AgentID; public IPAddress Address; public int Port; public Uri SeedCapability; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); map["agent-id"] = OSD.FromUUID(AgentID); map["sim-ip-and-port"] = OSD.FromString(String.Format("{0}:{1}", Address, Port)); map["seed-capability"] = OSD.FromUri(SeedCapability); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { string ipAndPort = map["sim-ip-and-port"].AsString(); int i = ipAndPort.IndexOf(':'); AgentID = map["agent-id"].AsUUID(); Address = IPAddress.Parse(ipAndPort.Substring(0, i)); Port = Int32.Parse(ipAndPort.Substring(i + 1)); SeedCapability = map["seed-capability"].AsUri(); } } public class CrossedRegionMessage : IMessage { public Vector3 LookAt; public Vector3 Position; public UUID AgentID; public UUID SessionID; public ulong RegionHandle; public Uri SeedCapability; public IPAddress IP; public int Port; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); OSDArray infoArray = new OSDArray(1); OSDMap infoMap = new OSDMap(2); infoMap["LookAt"] = OSD.FromVector3(LookAt); infoMap["Position"] = OSD.FromVector3(Position); infoArray.Add(infoMap); map["Info"] = infoArray; OSDArray agentDataArray = new OSDArray(1); OSDMap agentDataMap = new OSDMap(2); agentDataMap["AgentID"] = OSD.FromUUID(AgentID); agentDataMap["SessionID"] = OSD.FromUUID(SessionID); agentDataArray.Add(agentDataMap); map["AgentData"] = agentDataArray; OSDArray regionDataArray = new OSDArray(1); OSDMap regionDataMap = new OSDMap(4); regionDataMap["RegionHandle"] = OSD.FromULong(RegionHandle); regionDataMap["SeedCapability"] = OSD.FromUri(SeedCapability); regionDataMap["SimIP"] = MessageUtils.FromIP(IP); regionDataMap["SimPort"] = OSD.FromInteger(Port); regionDataArray.Add(regionDataMap); map["RegionData"] = regionDataArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDMap infoMap = (OSDMap)((OSDArray)map["Info"])[0]; LookAt = infoMap["LookAt"].AsVector3(); Position = infoMap["Position"].AsVector3(); OSDMap agentDataMap = (OSDMap)((OSDArray)map["AgentData"])[0]; AgentID = agentDataMap["AgentID"].AsUUID(); SessionID = agentDataMap["SessionID"].AsUUID(); OSDMap regionDataMap = (OSDMap)((OSDArray)map["RegionData"])[0]; RegionHandle = regionDataMap["RegionHandle"].AsULong(); SeedCapability = regionDataMap["SeedCapability"].AsUri(); IP = MessageUtils.ToIP(regionDataMap["SimIP"]); Port = regionDataMap["SimPort"].AsInteger(); } } public class EnableSimulatorMessage : IMessage { public class SimulatorInfoBlock { public ulong RegionHandle; public IPAddress IP; public int Port; } public SimulatorInfoBlock[] Simulators; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); OSDArray array = new OSDArray(Simulators.Length); for (int i = 0; i < Simulators.Length; i++) { SimulatorInfoBlock block = Simulators[i]; OSDMap blockMap = new OSDMap(3); blockMap["Handle"] = OSD.FromULong(block.RegionHandle); blockMap["IP"] = MessageUtils.FromIP(block.IP); blockMap["Port"] = OSD.FromInteger(block.Port); array.Add(blockMap); } map["SimulatorInfo"] = array; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray array = (OSDArray)map["SimulatorInfo"]; Simulators = new SimulatorInfoBlock[array.Count]; for (int i = 0; i < array.Count; i++) { OSDMap blockMap = (OSDMap)array[i]; SimulatorInfoBlock block = new SimulatorInfoBlock(); block.RegionHandle = blockMap["Handle"].AsULong(); block.IP = MessageUtils.ToIP(blockMap["IP"]); block.Port = blockMap["Port"].AsInteger(); Simulators[i] = block; } } } /// <summary> /// A message sent to the client which indicates a teleport request has failed /// and contains some information on why it failed /// </summary> public class TeleportFailedMessage : IMessage { /// <summary></summary> public string ExtraParams; /// <summary>A string key of the reason the teleport failed e.g. CouldntTPCloser /// Which could be used to look up a value in a dictionary or enum</summary> public string MessageKey; /// <summary>The <see cref="UUID"/> of the Agent</summary> public UUID AgentID; /// <summary>A string human readable message containing the reason </summary> /// <remarks>An example: Could not teleport closer to destination</remarks> public string Reason; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); OSDMap alertInfoMap = new OSDMap(2); alertInfoMap["ExtraParams"] = OSD.FromString(ExtraParams); alertInfoMap["Message"] = OSD.FromString(MessageKey); OSDArray alertArray = new OSDArray(); alertArray.Add(alertInfoMap); map["AlertInfo"] = alertArray; OSDMap infoMap = new OSDMap(2); infoMap["AgentID"] = OSD.FromUUID(AgentID); infoMap["Reason"] = OSD.FromString(Reason); OSDArray infoArray = new OSDArray(); infoArray.Add(infoMap); map["Info"] = infoArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray alertInfoArray = (OSDArray)map["AlertInfo"]; OSDMap alertInfoMap = (OSDMap)alertInfoArray[0]; ExtraParams = alertInfoMap["ExtraParams"].AsString(); MessageKey = alertInfoMap["Message"].AsString(); OSDArray infoArray = (OSDArray)map["Info"]; OSDMap infoMap = (OSDMap)infoArray[0]; AgentID = infoMap["AgentID"].AsUUID(); Reason = infoMap["Reason"].AsString(); } } public class LandStatReplyMessage : IMessage { public uint ReportType; public uint RequestFlags; public uint TotalObjectCount; public class ReportDataBlock { public Vector3 Location; public string OwnerName; public float Score; public UUID TaskID; public uint TaskLocalID; public string TaskName; public float MonoScore; public DateTime TimeStamp; } public ReportDataBlock[] ReportDataBlocks; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); OSDMap requestDataMap = new OSDMap(3); requestDataMap["ReportType"] = OSD.FromUInteger(this.ReportType); requestDataMap["RequestFlags"] = OSD.FromUInteger(this.RequestFlags); requestDataMap["TotalObjectCount"] = OSD.FromUInteger(this.TotalObjectCount); OSDArray requestDatArray = new OSDArray(); requestDatArray.Add(requestDataMap); map["RequestData"] = requestDatArray; OSDArray reportDataArray = new OSDArray(); OSDArray dataExtendedArray = new OSDArray(); for (int i = 0; i < ReportDataBlocks.Length; i++) { OSDMap reportMap = new OSDMap(8); reportMap["LocationX"] = OSD.FromReal(ReportDataBlocks[i].Location.X); reportMap["LocationY"] = OSD.FromReal(ReportDataBlocks[i].Location.Y); reportMap["LocationZ"] = OSD.FromReal(ReportDataBlocks[i].Location.Z); reportMap["OwnerName"] = OSD.FromString(ReportDataBlocks[i].OwnerName); reportMap["Score"] = OSD.FromReal(ReportDataBlocks[i].Score); reportMap["TaskID"] = OSD.FromUUID(ReportDataBlocks[i].TaskID); reportMap["TaskLocalID"] = OSD.FromReal(ReportDataBlocks[i].TaskLocalID); reportMap["TaskName"] = OSD.FromString(ReportDataBlocks[i].TaskName); reportDataArray.Add(reportMap); OSDMap extendedMap = new OSDMap(2); extendedMap["MonoScore"] = OSD.FromReal(ReportDataBlocks[i].MonoScore); extendedMap["TimeStamp"] = OSD.FromDate(ReportDataBlocks[i].TimeStamp); dataExtendedArray.Add(extendedMap); } map["ReportData"] = reportDataArray; map["DataExtended"] = dataExtendedArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray requestDataArray = (OSDArray)map["RequestData"]; OSDMap requestMap = (OSDMap)requestDataArray[0]; this.ReportType = requestMap["ReportType"].AsUInteger(); this.RequestFlags = requestMap["RequestFlags"].AsUInteger(); this.TotalObjectCount = requestMap["TotalObjectCount"].AsUInteger(); if (TotalObjectCount < 1) { ReportDataBlocks = new ReportDataBlock[0]; return; } OSDArray dataArray = (OSDArray)map["ReportData"]; OSDArray dataExtendedArray = (OSDArray)map["DataExtended"]; ReportDataBlocks = new ReportDataBlock[dataArray.Count]; for (int i = 0; i < dataArray.Count; i++) { OSDMap blockMap = (OSDMap)dataArray[i]; OSDMap extMap = (OSDMap)dataExtendedArray[i]; ReportDataBlock block = new ReportDataBlock(); block.Location = new Vector3( (float)blockMap["LocationX"].AsReal(), (float)blockMap["LocationY"].AsReal(), (float)blockMap["LocationZ"].AsReal()); block.OwnerName = blockMap["OwnerName"].AsString(); block.Score = (float)blockMap["Score"].AsReal(); block.TaskID = blockMap["TaskID"].AsUUID(); block.TaskLocalID = blockMap["TaskLocalID"].AsUInteger(); block.TaskName = blockMap["TaskName"].AsString(); block.MonoScore = (float)extMap["MonoScore"].AsReal(); block.TimeStamp = Utils.UnixTimeToDateTime(extMap["TimeStamp"].AsUInteger()); ReportDataBlocks[i] = block; } } } #endregion #region Parcel Messages /// <summary> /// Contains a list of prim owner information for a specific parcel in a simulator /// </summary> /// <remarks> /// A Simulator will always return at least 1 entry /// If agent does not have proper permission the OwnerID will be UUID.Zero /// If agent does not have proper permission OR there are no primitives on parcel /// the DataBlocksExtended map will not be sent from the simulator /// </remarks> public class ParcelObjectOwnersReplyMessage : IMessage { /// <summary> /// Prim ownership information for a specified owner on a single parcel /// </summary> public class PrimOwner { /// <summary>The <see cref="UUID"/> of the prim owner, /// UUID.Zero if agent has no permission to view prim owner information</summary> public UUID OwnerID; /// <summary>The total number of prims</summary> public int Count; /// <summary>True if the OwnerID is a <see cref="Group"/></summary> public bool IsGroupOwned; /// <summary>True if the owner is online /// <remarks>This is no longer used by the LL Simulators</remarks></summary> public bool OnlineStatus; /// <summary>The date the most recent prim was rezzed</summary> public DateTime TimeStamp; } /// <summary>An Array of <see cref="PrimOwner"/> objects</summary> public PrimOwner[] PrimOwnersBlock; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDArray dataArray = new OSDArray(PrimOwnersBlock.Length); OSDArray dataExtendedArray = new OSDArray(); for (int i = 0; i < PrimOwnersBlock.Length; i++) { OSDMap dataMap = new OSDMap(4); dataMap["OwnerID"] = OSD.FromUUID(PrimOwnersBlock[i].OwnerID); dataMap["Count"] = OSD.FromInteger(PrimOwnersBlock[i].Count); dataMap["IsGroupOwned"] = OSD.FromBoolean(PrimOwnersBlock[i].IsGroupOwned); dataMap["OnlineStatus"] = OSD.FromBoolean(PrimOwnersBlock[i].OnlineStatus); dataArray.Add(dataMap); OSDMap dataExtendedMap = new OSDMap(1); dataExtendedMap["TimeStamp"] = OSD.FromDate(PrimOwnersBlock[i].TimeStamp); dataExtendedArray.Add(dataExtendedMap); } OSDMap map = new OSDMap(); map.Add("Data", dataArray); if (dataExtendedArray.Count > 0) map.Add("DataExtended", dataExtendedArray); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray dataArray = (OSDArray)map["Data"]; // DataExtended is optional, will not exist of parcel contains zero prims OSDArray dataExtendedArray; if (map.ContainsKey("DataExtended")) { dataExtendedArray = (OSDArray)map["DataExtended"]; } else { dataExtendedArray = new OSDArray(); } PrimOwnersBlock = new PrimOwner[dataArray.Count]; for (int i = 0; i < dataArray.Count; i++) { OSDMap dataMap = (OSDMap)dataArray[i]; PrimOwner block = new PrimOwner(); block.OwnerID = dataMap["OwnerID"].AsUUID(); block.Count = dataMap["Count"].AsInteger(); block.IsGroupOwned = dataMap["IsGroupOwned"].AsBoolean(); block.OnlineStatus = dataMap["OnlineStatus"].AsBoolean(); // deprecated /* if the agent has no permissions, or there are no prims, the counts * should not match up, so we don't decode the DataExtended map */ if (dataExtendedArray.Count == dataArray.Count) { OSDMap dataExtendedMap = (OSDMap)dataExtendedArray[i]; block.TimeStamp = Utils.UnixTimeToDateTime(dataExtendedMap["TimeStamp"].AsUInteger()); } PrimOwnersBlock[i] = block; } } } /// <summary> /// The details of a single parcel in a region, also contains some regionwide globals /// </summary> [Serializable] public class ParcelPropertiesMessage : IMessage { /// <summary>Simulator-local ID of this parcel</summary> public int LocalID; /// <summary>Maximum corner of the axis-aligned bounding box for this /// parcel</summary> public Vector3 AABBMax; /// <summary>Minimum corner of the axis-aligned bounding box for this /// parcel</summary> public Vector3 AABBMin; /// <summary>Total parcel land area</summary> public int Area; /// <summary></summary> public uint AuctionID; /// <summary>Key of authorized buyer</summary> public UUID AuthBuyerID; /// <summary>Bitmap describing land layout in 4x4m squares across the /// entire region</summary> public byte[] Bitmap; /// <summary></summary> public ParcelCategory Category; /// <summary>Date land was claimed</summary> public DateTime ClaimDate; /// <summary>Appears to always be zero</summary> public int ClaimPrice; /// <summary>Parcel Description</summary> public string Desc; /// <summary></summary> public ParcelFlags ParcelFlags; /// <summary></summary> public UUID GroupID; /// <summary>Total number of primitives owned by the parcel group on /// this parcel</summary> public int GroupPrims; /// <summary>Whether the land is deeded to a group or not</summary> public bool IsGroupOwned; /// <summary></summary> public LandingType LandingType; /// <summary>Maximum number of primitives this parcel supports</summary> public int MaxPrims; /// <summary>The Asset UUID of the Texture which when applied to a /// primitive will display the media</summary> public UUID MediaID; /// <summary>A URL which points to any Quicktime supported media type</summary> public string MediaURL; /// <summary>A byte, if 0x1 viewer should auto scale media to fit object</summary> public bool MediaAutoScale; /// <summary>URL For Music Stream</summary> public string MusicURL; /// <summary>Parcel Name</summary> public string Name; /// <summary>Autoreturn value in minutes for others' objects</summary> public int OtherCleanTime; /// <summary></summary> public int OtherCount; /// <summary>Total number of other primitives on this parcel</summary> public int OtherPrims; /// <summary>UUID of the owner of this parcel</summary> public UUID OwnerID; /// <summary>Total number of primitives owned by the parcel owner on /// this parcel</summary> public int OwnerPrims; /// <summary></summary> public float ParcelPrimBonus; /// <summary>How long is pass valid for</summary> public float PassHours; /// <summary>Price for a temporary pass</summary> public int PassPrice; /// <summary></summary> public int PublicCount; /// <summary>Disallows people outside the parcel from being able to see in</summary> public bool Privacy; /// <summary></summary> public bool RegionDenyAnonymous; /// <summary></summary> public bool RegionDenyIdentified; /// <summary></summary> public bool RegionDenyTransacted; /// <summary>True if the region denies access to age unverified users</summary> public bool RegionDenyAgeUnverified; /// <summary></summary> public bool RegionPushOverride; /// <summary>This field is no longer used</summary> public int RentPrice; /// The result of a request for parcel properties public ParcelResult RequestResult; /// <summary>Sale price of the parcel, only useful if ForSale is set</summary> /// <remarks>The SalePrice will remain the same after an ownership /// transfer (sale), so it can be used to see the purchase price after /// a sale if the new owner has not changed it</remarks> public int SalePrice; /// <summary> /// Number of primitives your avatar is currently /// selecting and sitting on in this parcel /// </summary> public int SelectedPrims; /// <summary></summary> public int SelfCount; /// <summary> /// A number which increments by 1, starting at 0 for each ParcelProperties request. /// Can be overriden by specifying the sequenceID with the ParcelPropertiesRequest being sent. /// a Negative number indicates the action in <seealso cref="ParcelPropertiesStatus"/> has occurred. /// </summary> public int SequenceID; /// <summary>Maximum primitives across the entire simulator</summary> public int SimWideMaxPrims; /// <summary>Total primitives across the entire simulator</summary> public int SimWideTotalPrims; /// <summary></summary> public bool SnapSelection; /// <summary>Key of parcel snapshot</summary> public UUID SnapshotID; /// <summary>Parcel ownership status</summary> public ParcelStatus Status; /// <summary>Total number of primitives on this parcel</summary> public int TotalPrims; /// <summary></summary> public Vector3 UserLocation; /// <summary></summary> public Vector3 UserLookAt; /// <summary>A description of the media</summary> public string MediaDesc; /// <summary>An Integer which represents the height of the media</summary> public int MediaHeight; /// <summary>An integer which represents the width of the media</summary> public int MediaWidth; /// <summary>A boolean, if true the viewer should loop the media</summary> public bool MediaLoop; /// <summary>A string which contains the mime type of the media</summary> public string MediaType; /// <summary>true to obscure (hide) media url</summary> public bool ObscureMedia; /// <summary>true to obscure (hide) music url</summary> public bool ObscureMusic; /// <summary> true if avatars in this parcel should be invisible to people outside</summary> public bool SeeAVs; /// <summary> true if avatars outside can hear any sounds avatars inside play</summary> public bool AnyAVSounds; /// <summary> true if group members outside can hear any sounds avatars inside play</summary> public bool GroupAVSounds; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); OSDArray dataArray = new OSDArray(1); OSDMap parcelDataMap = new OSDMap(47); parcelDataMap["LocalID"] = OSD.FromInteger(LocalID); parcelDataMap["AABBMax"] = OSD.FromVector3(AABBMax); parcelDataMap["AABBMin"] = OSD.FromVector3(AABBMin); parcelDataMap["Area"] = OSD.FromInteger(Area); parcelDataMap["AuctionID"] = OSD.FromInteger(AuctionID); parcelDataMap["AuthBuyerID"] = OSD.FromUUID(AuthBuyerID); parcelDataMap["Bitmap"] = OSD.FromBinary(Bitmap); parcelDataMap["Category"] = OSD.FromInteger((int)Category); parcelDataMap["ClaimDate"] = OSD.FromDate(ClaimDate); parcelDataMap["ClaimPrice"] = OSD.FromInteger(ClaimPrice); parcelDataMap["Desc"] = OSD.FromString(Desc); parcelDataMap["ParcelFlags"] = OSD.FromUInteger((uint)ParcelFlags); parcelDataMap["GroupID"] = OSD.FromUUID(GroupID); parcelDataMap["GroupPrims"] = OSD.FromInteger(GroupPrims); parcelDataMap["IsGroupOwned"] = OSD.FromBoolean(IsGroupOwned); parcelDataMap["LandingType"] = OSD.FromInteger((int)LandingType); parcelDataMap["MaxPrims"] = OSD.FromInteger(MaxPrims); parcelDataMap["MediaID"] = OSD.FromUUID(MediaID); parcelDataMap["MediaURL"] = OSD.FromString(MediaURL); parcelDataMap["MediaAutoScale"] = OSD.FromBoolean(MediaAutoScale); parcelDataMap["MusicURL"] = OSD.FromString(MusicURL); parcelDataMap["Name"] = OSD.FromString(Name); parcelDataMap["OtherCleanTime"] = OSD.FromInteger(OtherCleanTime); parcelDataMap["OtherCount"] = OSD.FromInteger(OtherCount); parcelDataMap["OtherPrims"] = OSD.FromInteger(OtherPrims); parcelDataMap["OwnerID"] = OSD.FromUUID(OwnerID); parcelDataMap["OwnerPrims"] = OSD.FromInteger(OwnerPrims); parcelDataMap["ParcelPrimBonus"] = OSD.FromReal((float)ParcelPrimBonus); parcelDataMap["PassHours"] = OSD.FromReal((float)PassHours); parcelDataMap["PassPrice"] = OSD.FromInteger(PassPrice); parcelDataMap["PublicCount"] = OSD.FromInteger(PublicCount); parcelDataMap["Privacy"] = OSD.FromBoolean(Privacy); parcelDataMap["RegionDenyAnonymous"] = OSD.FromBoolean(RegionDenyAnonymous); parcelDataMap["RegionDenyIdentified"] = OSD.FromBoolean(RegionDenyIdentified); parcelDataMap["RegionDenyTransacted"] = OSD.FromBoolean(RegionDenyTransacted); parcelDataMap["RegionPushOverride"] = OSD.FromBoolean(RegionPushOverride); parcelDataMap["RentPrice"] = OSD.FromInteger(RentPrice); parcelDataMap["RequestResult"] = OSD.FromInteger((int)RequestResult); parcelDataMap["SalePrice"] = OSD.FromInteger(SalePrice); parcelDataMap["SelectedPrims"] = OSD.FromInteger(SelectedPrims); parcelDataMap["SelfCount"] = OSD.FromInteger(SelfCount); parcelDataMap["SequenceID"] = OSD.FromInteger(SequenceID); parcelDataMap["SimWideMaxPrims"] = OSD.FromInteger(SimWideMaxPrims); parcelDataMap["SimWideTotalPrims"] = OSD.FromInteger(SimWideTotalPrims); parcelDataMap["SnapSelection"] = OSD.FromBoolean(SnapSelection); parcelDataMap["SnapshotID"] = OSD.FromUUID(SnapshotID); parcelDataMap["Status"] = OSD.FromInteger((int)Status); parcelDataMap["TotalPrims"] = OSD.FromInteger(TotalPrims); parcelDataMap["UserLocation"] = OSD.FromVector3(UserLocation); parcelDataMap["UserLookAt"] = OSD.FromVector3(UserLookAt); parcelDataMap["SeeAVs"] = OSD.FromBoolean(SeeAVs); parcelDataMap["AnyAVSounds"] = OSD.FromBoolean(AnyAVSounds); parcelDataMap["GroupAVSounds"] = OSD.FromBoolean(GroupAVSounds); dataArray.Add(parcelDataMap); map["ParcelData"] = dataArray; OSDArray mediaDataArray = new OSDArray(1); OSDMap mediaDataMap = new OSDMap(7); mediaDataMap["MediaDesc"] = OSD.FromString(MediaDesc); mediaDataMap["MediaHeight"] = OSD.FromInteger(MediaHeight); mediaDataMap["MediaWidth"] = OSD.FromInteger(MediaWidth); mediaDataMap["MediaLoop"] = OSD.FromBoolean(MediaLoop); mediaDataMap["MediaType"] = OSD.FromString(MediaType); mediaDataMap["ObscureMedia"] = OSD.FromBoolean(ObscureMedia); mediaDataMap["ObscureMusic"] = OSD.FromBoolean(ObscureMusic); mediaDataArray.Add(mediaDataMap); map["MediaData"] = mediaDataArray; OSDArray ageVerificationBlockArray = new OSDArray(1); OSDMap ageVerificationBlockMap = new OSDMap(1); ageVerificationBlockMap["RegionDenyAgeUnverified"] = OSD.FromBoolean(RegionDenyAgeUnverified); ageVerificationBlockArray.Add(ageVerificationBlockMap); map["AgeVerificationBlock"] = ageVerificationBlockArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDMap parcelDataMap = (OSDMap)((OSDArray)map["ParcelData"])[0]; LocalID = parcelDataMap["LocalID"].AsInteger(); AABBMax = parcelDataMap["AABBMax"].AsVector3(); AABBMin = parcelDataMap["AABBMin"].AsVector3(); Area = parcelDataMap["Area"].AsInteger(); AuctionID = (uint)parcelDataMap["AuctionID"].AsInteger(); AuthBuyerID = parcelDataMap["AuthBuyerID"].AsUUID(); Bitmap = parcelDataMap["Bitmap"].AsBinary(); Category = (ParcelCategory)parcelDataMap["Category"].AsInteger(); ClaimDate = Utils.UnixTimeToDateTime((uint)parcelDataMap["ClaimDate"].AsInteger()); ClaimPrice = parcelDataMap["ClaimPrice"].AsInteger(); Desc = parcelDataMap["Desc"].AsString(); // LL sends this as binary, we'll convert it here if (parcelDataMap["ParcelFlags"].Type == OSDType.Binary) { byte[] bytes = parcelDataMap["ParcelFlags"].AsBinary(); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); ParcelFlags = (ParcelFlags)BitConverter.ToUInt32(bytes, 0); } else { ParcelFlags = (ParcelFlags)parcelDataMap["ParcelFlags"].AsUInteger(); } GroupID = parcelDataMap["GroupID"].AsUUID(); GroupPrims = parcelDataMap["GroupPrims"].AsInteger(); IsGroupOwned = parcelDataMap["IsGroupOwned"].AsBoolean(); LandingType = (LandingType)parcelDataMap["LandingType"].AsInteger(); MaxPrims = parcelDataMap["MaxPrims"].AsInteger(); MediaID = parcelDataMap["MediaID"].AsUUID(); MediaURL = parcelDataMap["MediaURL"].AsString(); MediaAutoScale = parcelDataMap["MediaAutoScale"].AsBoolean(); // 0x1 = yes MusicURL = parcelDataMap["MusicURL"].AsString(); Name = parcelDataMap["Name"].AsString(); OtherCleanTime = parcelDataMap["OtherCleanTime"].AsInteger(); OtherCount = parcelDataMap["OtherCount"].AsInteger(); OtherPrims = parcelDataMap["OtherPrims"].AsInteger(); OwnerID = parcelDataMap["OwnerID"].AsUUID(); OwnerPrims = parcelDataMap["OwnerPrims"].AsInteger(); ParcelPrimBonus = (float)parcelDataMap["ParcelPrimBonus"].AsReal(); PassHours = (float)parcelDataMap["PassHours"].AsReal(); PassPrice = parcelDataMap["PassPrice"].AsInteger(); PublicCount = parcelDataMap["PublicCount"].AsInteger(); Privacy = parcelDataMap["Privacy"].AsBoolean(); RegionDenyAnonymous = parcelDataMap["RegionDenyAnonymous"].AsBoolean(); RegionDenyIdentified = parcelDataMap["RegionDenyIdentified"].AsBoolean(); RegionDenyTransacted = parcelDataMap["RegionDenyTransacted"].AsBoolean(); RegionPushOverride = parcelDataMap["RegionPushOverride"].AsBoolean(); RentPrice = parcelDataMap["RentPrice"].AsInteger(); RequestResult = (ParcelResult)parcelDataMap["RequestResult"].AsInteger(); SalePrice = parcelDataMap["SalePrice"].AsInteger(); SelectedPrims = parcelDataMap["SelectedPrims"].AsInteger(); SelfCount = parcelDataMap["SelfCount"].AsInteger(); SequenceID = parcelDataMap["SequenceID"].AsInteger(); SimWideMaxPrims = parcelDataMap["SimWideMaxPrims"].AsInteger(); SimWideTotalPrims = parcelDataMap["SimWideTotalPrims"].AsInteger(); SnapSelection = parcelDataMap["SnapSelection"].AsBoolean(); SnapshotID = parcelDataMap["SnapshotID"].AsUUID(); Status = (ParcelStatus)parcelDataMap["Status"].AsInteger(); TotalPrims = parcelDataMap["TotalPrims"].AsInteger(); UserLocation = parcelDataMap["UserLocation"].AsVector3(); UserLookAt = parcelDataMap["UserLookAt"].AsVector3(); SeeAVs = parcelDataMap["SeeAVs"].AsBoolean(); AnyAVSounds = parcelDataMap["AnyAVSounds"].AsBoolean(); GroupAVSounds = parcelDataMap["GroupAVSounds"].AsBoolean(); if (map.ContainsKey("MediaData")) // temporary, OpenSim doesn't send this block { OSDMap mediaDataMap = (OSDMap)((OSDArray)map["MediaData"])[0]; MediaDesc = mediaDataMap["MediaDesc"].AsString(); MediaHeight = mediaDataMap["MediaHeight"].AsInteger(); MediaWidth = mediaDataMap["MediaWidth"].AsInteger(); MediaLoop = mediaDataMap["MediaLoop"].AsBoolean(); MediaType = mediaDataMap["MediaType"].AsString(); ObscureMedia = mediaDataMap["ObscureMedia"].AsBoolean(); ObscureMusic = mediaDataMap["ObscureMusic"].AsBoolean(); } OSDMap ageVerificationBlockMap = (OSDMap)((OSDArray)map["AgeVerificationBlock"])[0]; RegionDenyAgeUnverified = ageVerificationBlockMap["RegionDenyAgeUnverified"].AsBoolean(); } } /// <summary>A message sent from the viewer to the simulator to updated a specific parcels settings</summary> public class ParcelPropertiesUpdateMessage : IMessage { /// <summary>The <seealso cref="UUID"/> of the agent authorized to purchase this /// parcel of land or a NULL <seealso cref="UUID"/> if the sale is authorized to anyone</summary> public UUID AuthBuyerID; /// <summary>true to enable auto scaling of the parcel media</summary> public bool MediaAutoScale; /// <summary>The category of this parcel used when search is enabled to restrict /// search results</summary> public ParcelCategory Category; /// <summary>A string containing the description to set</summary> public string Desc; /// <summary>The <seealso cref="UUID"/> of the <seealso cref="Group"/> which allows for additional /// powers and restrictions.</summary> public UUID GroupID; /// <summary>The <seealso cref="LandingType"/> which specifies how avatars which teleport /// to this parcel are handled</summary> public LandingType Landing; /// <summary>The LocalID of the parcel to update settings on</summary> public int LocalID; /// <summary>A string containing the description of the media which can be played /// to visitors</summary> public string MediaDesc; /// <summary></summary> public int MediaHeight; /// <summary></summary> public bool MediaLoop; /// <summary></summary> public UUID MediaID; /// <summary></summary> public string MediaType; /// <summary></summary> public string MediaURL; /// <summary></summary> public int MediaWidth; /// <summary></summary> public string MusicURL; /// <summary></summary> public string Name; /// <summary></summary> public bool ObscureMedia; /// <summary></summary> public bool ObscureMusic; /// <summary></summary> public ParcelFlags ParcelFlags; /// <summary></summary> public float PassHours; /// <summary></summary> public uint PassPrice; /// <summary></summary> public bool Privacy; /// <summary></summary> public uint SalePrice; /// <summary></summary> public UUID SnapshotID; /// <summary></summary> public Vector3 UserLocation; /// <summary></summary> public Vector3 UserLookAt; /// <summary> true if avatars in this parcel should be invisible to people outside</summary> public bool SeeAVs; /// <summary> true if avatars outside can hear any sounds avatars inside play</summary> public bool AnyAVSounds; /// <summary> true if group members outside can hear any sounds avatars inside play</summary> public bool GroupAVSounds; /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { AuthBuyerID = map["auth_buyer_id"].AsUUID(); MediaAutoScale = map["auto_scale"].AsBoolean(); Category = (ParcelCategory)map["category"].AsInteger(); Desc = map["description"].AsString(); GroupID = map["group_id"].AsUUID(); Landing = (LandingType)map["landing_type"].AsUInteger(); LocalID = map["local_id"].AsInteger(); MediaDesc = map["media_desc"].AsString(); MediaHeight = map["media_height"].AsInteger(); MediaLoop = map["media_loop"].AsBoolean(); MediaID = map["media_id"].AsUUID(); MediaType = map["media_type"].AsString(); MediaURL = map["media_url"].AsString(); MediaWidth = map["media_width"].AsInteger(); MusicURL = map["music_url"].AsString(); Name = map["name"].AsString(); ObscureMedia = map["obscure_media"].AsBoolean(); ObscureMusic = map["obscure_music"].AsBoolean(); ParcelFlags = (ParcelFlags)map["parcel_flags"].AsUInteger(); PassHours = (float)map["pass_hours"].AsReal(); PassPrice = map["pass_price"].AsUInteger(); Privacy = map["privacy"].AsBoolean(); SalePrice = map["sale_price"].AsUInteger(); SnapshotID = map["snapshot_id"].AsUUID(); UserLocation = map["user_location"].AsVector3(); UserLookAt = map["user_look_at"].AsVector3(); if (map.ContainsKey("see_avs")) { SeeAVs = map["see_avs"].AsBoolean(); AnyAVSounds = map["any_av_sounds"].AsBoolean(); GroupAVSounds = map["group_av_sounds"].AsBoolean(); } else { SeeAVs = true; AnyAVSounds = true; GroupAVSounds = true; } } /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(); map["auth_buyer_id"] = OSD.FromUUID(AuthBuyerID); map["auto_scale"] = OSD.FromBoolean(MediaAutoScale); map["category"] = OSD.FromInteger((byte)Category); map["description"] = OSD.FromString(Desc); map["flags"] = OSD.FromBinary(Utils.EmptyBytes); map["group_id"] = OSD.FromUUID(GroupID); map["landing_type"] = OSD.FromInteger((byte)Landing); map["local_id"] = OSD.FromInteger(LocalID); map["media_desc"] = OSD.FromString(MediaDesc); map["media_height"] = OSD.FromInteger(MediaHeight); map["media_id"] = OSD.FromUUID(MediaID); map["media_loop"] = OSD.FromBoolean(MediaLoop); map["media_type"] = OSD.FromString(MediaType); map["media_url"] = OSD.FromString(MediaURL); map["media_width"] = OSD.FromInteger(MediaWidth); map["music_url"] = OSD.FromString(MusicURL); map["name"] = OSD.FromString(Name); map["obscure_media"] = OSD.FromBoolean(ObscureMedia); map["obscure_music"] = OSD.FromBoolean(ObscureMusic); map["parcel_flags"] = OSD.FromUInteger((uint)ParcelFlags); map["pass_hours"] = OSD.FromReal(PassHours); map["privacy"] = OSD.FromBoolean(Privacy); map["pass_price"] = OSD.FromInteger(PassPrice); map["sale_price"] = OSD.FromInteger(SalePrice); map["snapshot_id"] = OSD.FromUUID(SnapshotID); map["user_location"] = OSD.FromVector3(UserLocation); map["user_look_at"] = OSD.FromVector3(UserLookAt); map["see_avs"] = OSD.FromBoolean(SeeAVs); map["any_av_sounds"] = OSD.FromBoolean(AnyAVSounds); map["group_av_sounds"] = OSD.FromBoolean(GroupAVSounds); return map; } } /// <summary>Base class used for the RemoteParcelRequest message</summary> [Serializable] public abstract class RemoteParcelRequestBlock { public abstract OSDMap Serialize(); public abstract void Deserialize(OSDMap map); } /// <summary> /// A message sent from the viewer to the simulator to request information /// on a remote parcel /// </summary> public class RemoteParcelRequestRequest : RemoteParcelRequestBlock { /// <summary>Local sim position of the parcel we are looking up</summary> public Vector3 Location; /// <summary>Region handle of the parcel we are looking up</summary> public ulong RegionHandle; /// <summary>Region <see cref="UUID"/> of the parcel we are looking up</summary> public UUID RegionID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(3); map["location"] = OSD.FromVector3(Location); map["region_handle"] = OSD.FromULong(RegionHandle); map["region_id"] = OSD.FromUUID(RegionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { Location = map["location"].AsVector3(); RegionHandle = map["region_handle"].AsULong(); RegionID = map["region_id"].AsUUID(); } } /// <summary> /// A message sent from the simulator to the viewer in response to a <see cref="RemoteParcelRequestRequest"/> /// which will contain parcel information /// </summary> [Serializable] public class RemoteParcelRequestReply : RemoteParcelRequestBlock { /// <summary>The grid-wide unique parcel ID</summary> public UUID ParcelID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(1); map["parcel_id"] = OSD.FromUUID(ParcelID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { if (map == null || !map.ContainsKey("parcel_id")) ParcelID = UUID.Zero; else ParcelID = map["parcel_id"].AsUUID(); } } /// <summary> /// A message containing a request for a remote parcel from a viewer, or a response /// from the simulator to that request /// </summary> [Serializable] public class RemoteParcelRequestMessage : IMessage { /// <summary>The request or response details block</summary> public RemoteParcelRequestBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("parcel_id")) Request = new RemoteParcelRequestReply(); else if (map.ContainsKey("location")) Request = new RemoteParcelRequestRequest(); else Logger.Log("Unable to deserialize RemoteParcelRequest: No message handler exists for method: " + map.AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } #endregion #region Inventory Messages public class NewFileAgentInventoryMessage : IMessage { public UUID FolderID; public AssetType AssetType; public InventoryType InventoryType; public string Name; public string Description; public PermissionMask EveryoneMask; public PermissionMask GroupMask; public PermissionMask NextOwnerMask; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(5); map["folder_id"] = OSD.FromUUID(FolderID); map["asset_type"] = OSD.FromString(Utils.AssetTypeToString(AssetType)); map["inventory_type"] = OSD.FromString(Utils.InventoryTypeToString(InventoryType)); map["name"] = OSD.FromString(Name); map["description"] = OSD.FromString(Description); map["everyone_mask"] = OSD.FromInteger((int)EveryoneMask); map["group_mask"] = OSD.FromInteger((int)GroupMask); map["next_owner_mask"] = OSD.FromInteger((int)NextOwnerMask); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { FolderID = map["folder_id"].AsUUID(); AssetType = Utils.StringToAssetType(map["asset_type"].AsString()); InventoryType = Utils.StringToInventoryType(map["inventory_type"].AsString()); Name = map["name"].AsString(); Description = map["description"].AsString(); EveryoneMask = (PermissionMask)map["everyone_mask"].AsInteger(); GroupMask = (PermissionMask)map["group_mask"].AsInteger(); NextOwnerMask = (PermissionMask)map["next_owner_mask"].AsInteger(); } } public class NewFileAgentInventoryReplyMessage : IMessage { public string State; public Uri Uploader; public NewFileAgentInventoryReplyMessage() { State = "upload"; } public OSDMap Serialize() { OSDMap map = new OSDMap(); map["state"] = OSD.FromString(State); map["uploader"] = OSD.FromUri(Uploader); return map; } public void Deserialize(OSDMap map) { State = map["state"].AsString(); Uploader = map["uploader"].AsUri(); } } public class NewFileAgentInventoryVariablePriceMessage : IMessage { public UUID FolderID; public AssetType AssetType; public InventoryType InventoryType; public string Name; public string Description; public PermissionMask EveryoneMask; public PermissionMask GroupMask; public PermissionMask NextOwnerMask; // TODO: asset_resources? /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(); map["folder_id"] = OSD.FromUUID(FolderID); map["asset_type"] = OSD.FromString(Utils.AssetTypeToString(AssetType)); map["inventory_type"] = OSD.FromString(Utils.InventoryTypeToString(InventoryType)); map["name"] = OSD.FromString(Name); map["description"] = OSD.FromString(Description); map["everyone_mask"] = OSD.FromInteger((int)EveryoneMask); map["group_mask"] = OSD.FromInteger((int)GroupMask); map["next_owner_mask"] = OSD.FromInteger((int)NextOwnerMask); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { FolderID = map["folder_id"].AsUUID(); AssetType = Utils.StringToAssetType(map["asset_type"].AsString()); InventoryType = Utils.StringToInventoryType(map["inventory_type"].AsString()); Name = map["name"].AsString(); Description = map["description"].AsString(); EveryoneMask = (PermissionMask)map["everyone_mask"].AsInteger(); GroupMask = (PermissionMask)map["group_mask"].AsInteger(); NextOwnerMask = (PermissionMask)map["next_owner_mask"].AsInteger(); } } public class NewFileAgentInventoryVariablePriceReplyMessage : IMessage { public int ResourceCost; public string State; public int UploadPrice; public Uri Rsvp; public NewFileAgentInventoryVariablePriceReplyMessage() { State = "confirm_upload"; } public OSDMap Serialize() { OSDMap map = new OSDMap(); map["resource_cost"] = OSD.FromInteger(ResourceCost); map["state"] = OSD.FromString(State); map["upload_price"] = OSD.FromInteger(UploadPrice); map["rsvp"] = OSD.FromUri(Rsvp); return map; } public void Deserialize(OSDMap map) { ResourceCost = map["resource_cost"].AsInteger(); State = map["state"].AsString(); UploadPrice = map["upload_price"].AsInteger(); Rsvp = map["rsvp"].AsUri(); } } public class NewFileAgentInventoryUploadReplyMessage : IMessage { public UUID NewInventoryItem; public UUID NewAsset; public string State; public PermissionMask NewBaseMask; public PermissionMask NewEveryoneMask; public PermissionMask NewOwnerMask; public PermissionMask NewNextOwnerMask; public NewFileAgentInventoryUploadReplyMessage() { State = "complete"; } public OSDMap Serialize() { OSDMap map = new OSDMap(); map["new_inventory_item"] = OSD.FromUUID(NewInventoryItem); map["new_asset"] = OSD.FromUUID(NewAsset); map["state"] = OSD.FromString(State); map["new_base_mask"] = OSD.FromInteger((int)NewBaseMask); map["new_everyone_mask"] = OSD.FromInteger((int)NewEveryoneMask); map["new_owner_mask"] = OSD.FromInteger((int)NewOwnerMask); map["new_next_owner_mask"] = OSD.FromInteger((int)NewNextOwnerMask); return map; } public void Deserialize(OSDMap map) { NewInventoryItem = map["new_inventory_item"].AsUUID(); NewAsset = map["new_asset"].AsUUID(); State = map["state"].AsString(); NewBaseMask = (PermissionMask)map["new_base_mask"].AsInteger(); NewEveryoneMask = (PermissionMask)map["new_everyone_mask"].AsInteger(); NewOwnerMask = (PermissionMask)map["new_owner_mask"].AsInteger(); NewNextOwnerMask = (PermissionMask)map["new_next_owner_mask"].AsInteger(); } } public class BulkUpdateInventoryMessage : IMessage { public class FolderDataInfo { public UUID FolderID; public UUID ParentID; public string Name; public FolderType Type; public static FolderDataInfo FromOSD(OSD data) { FolderDataInfo ret = new FolderDataInfo(); if (!(data is OSDMap)) return ret; OSDMap map = (OSDMap)data; ret.FolderID = map["FolderID"]; ret.ParentID = map["ParentID"]; ret.Name = map["Name"]; ret.Type = (FolderType)map["Type"].AsInteger(); return ret; } } public class ItemDataInfo { public UUID ItemID; public uint CallbackID; public UUID FolderID; public UUID CreatorID; public UUID OwnerID; public UUID GroupID; public PermissionMask BaseMask; public PermissionMask OwnerMask; public PermissionMask GroupMask; public PermissionMask EveryoneMask; public PermissionMask NextOwnerMask; public bool GroupOwned; public UUID AssetID; public AssetType Type; public InventoryType InvType; public uint Flags; public SaleType SaleType; public int SalePrice; public string Name; public string Description; public DateTime CreationDate; public uint CRC; public static ItemDataInfo FromOSD(OSD data) { ItemDataInfo ret = new ItemDataInfo(); if (!(data is OSDMap)) return ret; OSDMap map = (OSDMap)data; ret.ItemID = map["ItemID"]; ret.CallbackID = map["CallbackID"]; ret.FolderID = map["FolderID"]; ret.CreatorID = map["CreatorID"]; ret.OwnerID = map["OwnerID"]; ret.GroupID = map["GroupID"]; ret.BaseMask = (PermissionMask)map["BaseMask"].AsUInteger(); ret.OwnerMask = (PermissionMask)map["OwnerMask"].AsUInteger(); ret.GroupMask = (PermissionMask)map["GroupMask"].AsUInteger(); ret.EveryoneMask = (PermissionMask)map["EveryoneMask"].AsUInteger(); ret.NextOwnerMask = (PermissionMask)map["NextOwnerMask"].AsUInteger(); ret.GroupOwned = map["GroupOwned"]; ret.AssetID = map["AssetID"]; ret.Type = (AssetType)map["Type"].AsInteger(); ret.InvType = (InventoryType)map["InvType"].AsInteger(); ret.Flags = map["Flags"]; ret.SaleType = (SaleType)map["SaleType"].AsInteger(); ret.SalePrice = map["SaleType"]; ret.Name = map["Name"]; ret.Description = map["Description"]; ret.CreationDate = Utils.UnixTimeToDateTime(map["CreationDate"]); ret.CRC = map["CRC"]; return ret; } } public UUID AgentID; public UUID TransactionID; public FolderDataInfo[] FolderData; public ItemDataInfo[] ItemData; public OSDMap Serialize() { throw new NotImplementedException(); } public void Deserialize(OSDMap map) { if (map["AgentData"] is OSDArray) { OSDArray array = (OSDArray)map["AgentData"]; if (array.Count > 0) { OSDMap adata = (OSDMap)array[0]; AgentID = adata["AgentID"]; TransactionID = adata["TransactionID"]; } } if (map["FolderData"] is OSDArray) { OSDArray array = (OSDArray)map["FolderData"]; FolderData = new FolderDataInfo[array.Count]; for (int i = 0; i < array.Count; i++) { FolderData[i] = FolderDataInfo.FromOSD(array[i]); } } else { FolderData = new FolderDataInfo[0]; } if (map["ItemData"] is OSDArray) { OSDArray array = (OSDArray)map["ItemData"]; ItemData = new ItemDataInfo[array.Count]; for (int i = 0; i < array.Count; i++) { ItemData[i] = ItemDataInfo.FromOSD(array[i]); } } else { ItemData = new ItemDataInfo[0]; } } } #endregion #region Agent Messages /// <summary> /// A message sent from the simulator to an agent which contains /// the groups the agent is in /// </summary> public class AgentGroupDataUpdateMessage : IMessage { /// <summary>The Agent receiving the message</summary> public UUID AgentID; /// <summary>Group Details specific to the agent</summary> public class GroupData { /// <summary>true of the agent accepts group notices</summary> public bool AcceptNotices; /// <summary>The agents tier contribution to the group</summary> public int Contribution; /// <summary>The Groups <seealso cref="UUID"/></summary> public UUID GroupID; /// <summary>The <seealso cref="UUID"/> of the groups insignia</summary> public UUID GroupInsigniaID; /// <summary>The name of the group</summary> public string GroupName; /// <summary>The aggregate permissions the agent has in the group for all roles the agent /// is assigned</summary> public GroupPowers GroupPowers; } /// <summary>An optional block containing additional agent specific information</summary> public class NewGroupData { /// <summary>true of the agent allows this group to be /// listed in their profile</summary> public bool ListInProfile; } /// <summary>An array containing <seealso cref="GroupData"/> information /// for each <see cref="Group"/> the agent is a member of</summary> public GroupData[] GroupDataBlock; /// <summary>An array containing <seealso cref="NewGroupData"/> information /// for each <see cref="Group"/> the agent is a member of</summary> public NewGroupData[] NewGroupDataBlock; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); OSDMap agent = new OSDMap(1); agent["AgentID"] = OSD.FromUUID(AgentID); OSDArray agentArray = new OSDArray(); agentArray.Add(agent); map["AgentData"] = agentArray; OSDArray groupDataArray = new OSDArray(GroupDataBlock.Length); for (int i = 0; i < GroupDataBlock.Length; i++) { OSDMap group = new OSDMap(6); group["AcceptNotices"] = OSD.FromBoolean(GroupDataBlock[i].AcceptNotices); group["Contribution"] = OSD.FromInteger(GroupDataBlock[i].Contribution); group["GroupID"] = OSD.FromUUID(GroupDataBlock[i].GroupID); group["GroupInsigniaID"] = OSD.FromUUID(GroupDataBlock[i].GroupInsigniaID); group["GroupName"] = OSD.FromString(GroupDataBlock[i].GroupName); group["GroupPowers"] = OSD.FromLong((long)GroupDataBlock[i].GroupPowers); groupDataArray.Add(group); } map["GroupData"] = groupDataArray; OSDArray newGroupDataArray = new OSDArray(NewGroupDataBlock.Length); for (int i = 0; i < NewGroupDataBlock.Length; i++) { OSDMap group = new OSDMap(1); group["ListInProfile"] = OSD.FromBoolean(NewGroupDataBlock[i].ListInProfile); newGroupDataArray.Add(group); } map["NewGroupData"] = newGroupDataArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray agentArray = (OSDArray)map["AgentData"]; OSDMap agentMap = (OSDMap)agentArray[0]; AgentID = agentMap["AgentID"].AsUUID(); OSDArray groupArray = (OSDArray)map["GroupData"]; GroupDataBlock = new GroupData[groupArray.Count]; for (int i = 0; i < groupArray.Count; i++) { OSDMap groupMap = (OSDMap)groupArray[i]; GroupData groupData = new GroupData(); groupData.GroupID = groupMap["GroupID"].AsUUID(); groupData.Contribution = groupMap["Contribution"].AsInteger(); groupData.GroupInsigniaID = groupMap["GroupInsigniaID"].AsUUID(); groupData.GroupName = groupMap["GroupName"].AsString(); groupData.GroupPowers = (GroupPowers)groupMap["GroupPowers"].AsLong(); groupData.AcceptNotices = groupMap["AcceptNotices"].AsBoolean(); GroupDataBlock[i] = groupData; } // If request for current groups came very close to login // the Linden sim will not include the NewGroupData block, but // it will instead set all ListInProfile fields to false if (map.ContainsKey("NewGroupData")) { OSDArray newGroupArray = (OSDArray)map["NewGroupData"]; NewGroupDataBlock = new NewGroupData[newGroupArray.Count]; for (int i = 0; i < newGroupArray.Count; i++) { OSDMap newGroupMap = (OSDMap)newGroupArray[i]; NewGroupData newGroupData = new NewGroupData(); newGroupData.ListInProfile = newGroupMap["ListInProfile"].AsBoolean(); NewGroupDataBlock[i] = newGroupData; } } else { NewGroupDataBlock = new NewGroupData[GroupDataBlock.Length]; for (int i = 0; i < NewGroupDataBlock.Length; i++) { NewGroupData newGroupData = new NewGroupData(); newGroupData.ListInProfile = false; NewGroupDataBlock[i] = newGroupData; } } } } /// <summary> /// A message sent from the viewer to the simulator which /// specifies the language and permissions for others to detect /// the language specified /// </summary> public class UpdateAgentLanguageMessage : IMessage { /// <summary>A string containng the default language /// to use for the agent</summary> public string Language; /// <summary>true of others are allowed to /// know the language setting</summary> public bool LanguagePublic; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); map["language"] = OSD.FromString(Language); map["language_is_public"] = OSD.FromBoolean(LanguagePublic); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { LanguagePublic = map["language_is_public"].AsBoolean(); Language = map["language"].AsString(); } } /// <summary> /// An EventQueue message sent from the simulator to an agent when the agent /// leaves a group /// </summary> public class AgentDropGroupMessage : IMessage { /// <summary>An object containing the Agents UUID, and the Groups UUID</summary> public class AgentData { /// <summary>The ID of the Agent leaving the group</summary> public UUID AgentID; /// <summary>The GroupID the Agent is leaving</summary> public UUID GroupID; } /// <summary> /// An Array containing the AgentID and GroupID /// </summary> public AgentData[] AgentDataBlock; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); OSDArray agentDataArray = new OSDArray(AgentDataBlock.Length); for (int i = 0; i < AgentDataBlock.Length; i++) { OSDMap agentMap = new OSDMap(2); agentMap["AgentID"] = OSD.FromUUID(AgentDataBlock[i].AgentID); agentMap["GroupID"] = OSD.FromUUID(AgentDataBlock[i].GroupID); agentDataArray.Add(agentMap); } map["AgentData"] = agentDataArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray agentDataArray = (OSDArray)map["AgentData"]; AgentDataBlock = new AgentData[agentDataArray.Count]; for (int i = 0; i < agentDataArray.Count; i++) { OSDMap agentMap = (OSDMap)agentDataArray[i]; AgentData agentData = new AgentData(); agentData.AgentID = agentMap["AgentID"].AsUUID(); agentData.GroupID = agentMap["GroupID"].AsUUID(); AgentDataBlock[i] = agentData; } } } public class AgentStateUpdateMessage : IMessage { public OSDMap RawData; public bool CanModifyNavmesh; public bool HasModifiedNavmesh; public string MaxAccess; // PG, M, A public bool AlterNavmeshObjects; public bool AlterPermanentObjects; public int GodLevel; public string Language; public bool LanguageIsPublic; public void Deserialize(OSDMap map) { RawData = map; CanModifyNavmesh = map["can_modify_navmesh"]; HasModifiedNavmesh = map["has_modified_navmesh"]; if (map["preferences"] is OSDMap) { OSDMap prefs = (OSDMap)map["preferences"]; AlterNavmeshObjects = prefs["alter_navmesh_objects"]; AlterPermanentObjects = prefs["alter_permanent_objects"]; GodLevel = prefs["god_level"]; Language = prefs["language"]; LanguageIsPublic = prefs["language_is_public"]; if (prefs["access_prefs"] is OSDMap) { OSDMap access = (OSDMap)prefs["access_prefs"]; MaxAccess = access["max"]; } } } public OSDMap Serialize() { RawData = new OSDMap(); RawData["can_modify_navmesh"] = CanModifyNavmesh; RawData["has_modified_navmesh"] = HasModifiedNavmesh; OSDMap prefs = new OSDMap(); { OSDMap access = new OSDMap(); { access["max"] = MaxAccess; } prefs["access_prefs"] = access; prefs["alter_navmesh_objects"] = AlterNavmeshObjects; prefs["alter_permanent_objects"] = AlterPermanentObjects; prefs["god_level"] = GodLevel; prefs["language"] = Language; prefs["language_is_public"] = LanguageIsPublic; } RawData["preferences"] = prefs; return RawData; } } /// <summary>Base class for Asset uploads/results via Capabilities</summary> public abstract class AssetUploaderBlock { /// <summary> /// The request state /// </summary> public string State; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public abstract OSDMap Serialize(); /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public abstract void Deserialize(OSDMap map); } /// <summary> /// A message sent from the viewer to the simulator to request a temporary upload capability /// which allows an asset to be uploaded /// </summary> public class UploaderRequestUpload : AssetUploaderBlock { /// <summary>The Capability URL sent by the simulator to upload the baked texture to</summary> public Uri Url; public UploaderRequestUpload() { State = "upload"; } public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["state"] = OSD.FromString(State); map["uploader"] = OSD.FromUri(Url); return map; } public override void Deserialize(OSDMap map) { Url = map["uploader"].AsUri(); State = map["state"].AsString(); } } /// <summary> /// A message sent from the simulator that will inform the agent the upload is complete, /// and the UUID of the uploaded asset /// </summary> public class UploaderRequestComplete : AssetUploaderBlock { /// <summary>The uploaded texture asset ID</summary> public UUID AssetID; public UploaderRequestComplete() { State = "complete"; } public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["state"] = OSD.FromString(State); map["new_asset"] = OSD.FromUUID(AssetID); return map; } public override void Deserialize(OSDMap map) { AssetID = map["new_asset"].AsUUID(); State = map["state"].AsString(); } } /// <summary> /// A message sent from the viewer to the simulator to request a temporary /// capability URI which is used to upload an agents baked appearance textures /// </summary> public class UploadBakedTextureMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("state") && map["state"].AsString().Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete")) Request = new UploaderRequestComplete(); else Logger.Log("Unable to deserialize UploadBakedTexture: No message handler exists for state " + map["state"].AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } #endregion #region Voice Messages /// <summary> /// A message sent from the simulator which indicates the minimum version required for /// using voice chat /// </summary> public class RequiredVoiceVersionMessage : IMessage { /// <summary>Major Version Required</summary> public int MajorVersion; /// <summary>Minor version required</summary> public int MinorVersion; /// <summary>The name of the region sending the version requrements</summary> public string RegionName; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(4); map["major_version"] = OSD.FromInteger(MajorVersion); map["minor_version"] = OSD.FromInteger(MinorVersion); map["region_name"] = OSD.FromString(RegionName); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { MajorVersion = map["major_version"].AsInteger(); MinorVersion = map["minor_version"].AsInteger(); RegionName = map["region_name"].AsString(); } } /// <summary> /// A message sent from the simulator to the viewer containing the /// voice server URI /// </summary> public class ParcelVoiceInfoRequestMessage : IMessage { /// <summary>The Parcel ID which the voice server URI applies</summary> public int ParcelID; /// <summary>The name of the region</summary> public string RegionName; /// <summary>A uri containing the server/channel information /// which the viewer can utilize to participate in voice conversations</summary> public Uri SipChannelUri; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); map["parcel_local_id"] = OSD.FromInteger(ParcelID); map["region_name"] = OSD.FromString(RegionName); OSDMap vcMap = new OSDMap(1); vcMap["channel_uri"] = OSD.FromUri(SipChannelUri); map["voice_credentials"] = vcMap; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { ParcelID = map["parcel_local_id"].AsInteger(); RegionName = map["region_name"].AsString(); OSDMap vcMap = (OSDMap)map["voice_credentials"]; SipChannelUri = vcMap["channel_uri"].AsUri(); } } /// <summary> /// /// </summary> public class ProvisionVoiceAccountRequestMessage : IMessage { /// <summary></summary> public string Password; /// <summary></summary> public string Username; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); map["username"] = OSD.FromString(Username); map["password"] = OSD.FromString(Password); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { Username = map["username"].AsString(); Password = map["password"].AsString(); } } #endregion #region Script/Notecards Messages /// <summary> /// A message sent by the viewer to the simulator to request a temporary /// capability for a script contained with in a Tasks inventory to be updated /// </summary> public class UploadScriptTaskMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("state") && map["state"].Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].Equals("complete")) Request = new UploaderRequestComplete(); else Logger.Log("Unable to deserialize UploadScriptTask: No message handler exists for state " + map["state"].AsString(), Helpers.LogLevel.Warning); Request.Deserialize(map); } } /// <summary> /// A message sent from the simulator to the viewer to indicate /// a Tasks scripts status. /// </summary> public class ScriptRunningReplyMessage : IMessage { /// <summary>The Asset ID of the script</summary> public UUID ItemID; /// <summary>True of the script is compiled/ran using the mono interpreter, false indicates it /// uses the older less efficient lsl2 interprter</summary> public bool Mono; /// <summary>The Task containing the scripts <seealso cref="UUID"/></summary> public UUID ObjectID; /// <summary>true of the script is in a running state</summary> public bool Running; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); OSDMap scriptMap = new OSDMap(4); scriptMap["ItemID"] = OSD.FromUUID(ItemID); scriptMap["Mono"] = OSD.FromBoolean(Mono); scriptMap["ObjectID"] = OSD.FromUUID(ObjectID); scriptMap["Running"] = OSD.FromBoolean(Running); OSDArray scriptArray = new OSDArray(1); scriptArray.Add((OSD)scriptMap); map["Script"] = scriptArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray scriptArray = (OSDArray)map["Script"]; OSDMap scriptMap = (OSDMap)scriptArray[0]; ItemID = scriptMap["ItemID"].AsUUID(); Mono = scriptMap["Mono"].AsBoolean(); ObjectID = scriptMap["ObjectID"].AsUUID(); Running = scriptMap["Running"].AsBoolean(); } } /// <summary> /// A message containing the request/response used for updating a gesture /// contained with an agents inventory /// </summary> public class UpdateGestureAgentInventoryMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("item_id")) Request = new UpdateAgentInventoryRequestMessage(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete")) Request = new UploaderRequestComplete(); else Logger.Log("Unable to deserialize UpdateGestureAgentInventory: No message handler exists: " + map.AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } /// <summary> /// A message request/response which is used to update a notecard contained within /// a tasks inventory /// </summary> public class UpdateNotecardTaskInventoryMessage : IMessage { /// <summary>The <seealso cref="UUID"/> of the Task containing the notecard asset to update</summary> public UUID TaskID; /// <summary>The notecard assets <seealso cref="UUID"/> contained in the tasks inventory</summary> public UUID ItemID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); map["task_id"] = OSD.FromUUID(TaskID); map["item_id"] = OSD.FromUUID(ItemID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { TaskID = map["task_id"].AsUUID(); ItemID = map["item_id"].AsUUID(); } } // TODO: Add Test /// <summary> /// A reusable class containing a message sent from the viewer to the simulator to request a temporary uploader capability /// which is used to update an asset in an agents inventory /// </summary> public class UpdateAgentInventoryRequestMessage : AssetUploaderBlock { /// <summary> /// The Notecard AssetID to replace /// </summary> public UUID ItemID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(1); map["item_id"] = OSD.FromUUID(ItemID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { ItemID = map["item_id"].AsUUID(); } } /// <summary> /// A message containing the request/response used for updating a notecard /// contained with an agents inventory /// </summary> public class UpdateNotecardAgentInventoryMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("item_id")) Request = new UpdateAgentInventoryRequestMessage(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete")) Request = new UploaderRequestComplete(); else Logger.Log("Unable to deserialize UpdateNotecardAgentInventory: No message handler exists for state " + map["state"].AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } public class CopyInventoryFromNotecardMessage : IMessage { public int CallbackID; public UUID FolderID; public UUID ItemID; public UUID NotecardID; public UUID ObjectID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(5); map["callback-id"] = OSD.FromInteger(CallbackID); map["folder-id"] = OSD.FromUUID(FolderID); map["item-id"] = OSD.FromUUID(ItemID); map["notecard-id"] = OSD.FromUUID(NotecardID); map["object-id"] = OSD.FromUUID(ObjectID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { CallbackID = map["callback-id"].AsInteger(); FolderID = map["folder-id"].AsUUID(); ItemID = map["item-id"].AsUUID(); NotecardID = map["notecard-id"].AsUUID(); ObjectID = map["object-id"].AsUUID(); } } /// <summary> /// A message sent from the simulator to the viewer which indicates /// an error occurred while attempting to update a script in an agents or tasks /// inventory /// </summary> public class UploaderScriptRequestError : AssetUploaderBlock { /// <summary>true of the script was successfully compiled by the simulator</summary> public bool Compiled; /// <summary>A string containing the error which occured while trying /// to update the script</summary> public string Error; /// <summary>A new AssetID assigned to the script</summary> public UUID AssetID; public override OSDMap Serialize() { OSDMap map = new OSDMap(4); map["state"] = OSD.FromString(State); map["new_asset"] = OSD.FromUUID(AssetID); map["compiled"] = OSD.FromBoolean(Compiled); OSDArray errorsArray = new OSDArray(); errorsArray.Add(Error); map["errors"] = errorsArray; return map; } public override void Deserialize(OSDMap map) { AssetID = map["new_asset"].AsUUID(); Compiled = map["compiled"].AsBoolean(); State = map["state"].AsString(); OSDArray errorsArray = (OSDArray)map["errors"]; Error = errorsArray[0].AsString(); } } /// <summary> /// A message sent from the viewer to the simulator /// requesting the update of an existing script contained /// within a tasks inventory /// </summary> public class UpdateScriptTaskUpdateMessage : AssetUploaderBlock { /// <summary>if true, set the script mode to running</summary> public bool ScriptRunning; /// <summary>The scripts InventoryItem ItemID to update</summary> public UUID ItemID; /// <summary>A lowercase string containing either "mono" or "lsl2" which /// specifies the script is compiled and ran on the mono runtime, or the older /// lsl runtime</summary> public string Target; // mono or lsl2 /// <summary>The tasks <see cref="UUID"/> which contains the script to update</summary> public UUID TaskID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(4); map["is_script_running"] = OSD.FromBoolean(ScriptRunning); map["item_id"] = OSD.FromUUID(ItemID); map["target"] = OSD.FromString(Target); map["task_id"] = OSD.FromUUID(TaskID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { ScriptRunning = map["is_script_running"].AsBoolean(); ItemID = map["item_id"].AsUUID(); Target = map["target"].AsString(); TaskID = map["task_id"].AsUUID(); } } /// <summary> /// A message containing either the request or response used in updating a script inside /// a tasks inventory /// </summary> public class UpdateScriptTaskMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("task_id")) Request = new UpdateScriptTaskUpdateMessage(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete") && map.ContainsKey("errors")) Request = new UploaderScriptRequestError(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete")) Request = new UploaderRequestScriptComplete(); else Logger.Log("Unable to deserialize UpdateScriptTaskMessage: No message handler exists for state " + map["state"].AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } /// <summary> /// Response from the simulator to notify the viewer the upload is completed, and /// the UUID of the script asset and its compiled status /// </summary> public class UploaderRequestScriptComplete : AssetUploaderBlock { /// <summary>The uploaded texture asset ID</summary> public UUID AssetID; /// <summary>true of the script was compiled successfully</summary> public bool Compiled; public UploaderRequestScriptComplete() { State = "complete"; } public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["state"] = OSD.FromString(State); map["new_asset"] = OSD.FromUUID(AssetID); map["compiled"] = OSD.FromBoolean(Compiled); return map; } public override void Deserialize(OSDMap map) { AssetID = map["new_asset"].AsUUID(); Compiled = map["compiled"].AsBoolean(); } } /// <summary> /// A message sent from a viewer to the simulator requesting a temporary uploader capability /// used to update a script contained in an agents inventory /// </summary> public class UpdateScriptAgentRequestMessage : AssetUploaderBlock { /// <summary>The existing asset if of the script in the agents inventory to replace</summary> public UUID ItemID; /// <summary>The language of the script</summary> /// <remarks>Defaults to lsl version 2, "mono" might be another possible option</remarks> public string Target = "lsl2"; // lsl2 /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["item_id"] = OSD.FromUUID(ItemID); map["target"] = OSD.FromString(Target); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { ItemID = map["item_id"].AsUUID(); Target = map["target"].AsString(); } } /// <summary> /// A message containing either the request or response used in updating a script inside /// an agents inventory /// </summary> public class UpdateScriptAgentMessage : IMessage { /// <summary>Object containing request or response</summary> public AssetUploaderBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("item_id")) Request = new UpdateScriptAgentRequestMessage(); else if (map.ContainsKey("errors")) Request = new UploaderScriptRequestError(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("upload")) Request = new UploaderRequestUpload(); else if (map.ContainsKey("state") && map["state"].AsString().Equals("complete")) Request = new UploaderRequestScriptComplete(); else Logger.Log("Unable to deserialize UpdateScriptAgent: No message handler exists for state " + map["state"].AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } public class SendPostcardMessage : IMessage { public string FromEmail; public string Message; public string FromName; public Vector3 GlobalPosition; public string Subject; public string ToEmail; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(6); map["from"] = OSD.FromString(FromEmail); map["msg"] = OSD.FromString(Message); map["name"] = OSD.FromString(FromName); map["pos-global"] = OSD.FromVector3(GlobalPosition); map["subject"] = OSD.FromString(Subject); map["to"] = OSD.FromString(ToEmail); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { FromEmail = map["from"].AsString(); Message = map["msg"].AsString(); FromName = map["name"].AsString(); GlobalPosition = map["pos-global"].AsVector3(); Subject = map["subject"].AsString(); ToEmail = map["to"].AsString(); } } #endregion #region Grid/Maps /// <summary>Base class for Map Layers via Capabilities</summary> public abstract class MapLayerMessageBase { /// <summary></summary> public int Flags; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public abstract OSDMap Serialize(); /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public abstract void Deserialize(OSDMap map); } /// <summary> /// Sent by an agent to the capabilities server to request map layers /// </summary> public class MapLayerRequestVariant : MapLayerMessageBase { public override OSDMap Serialize() { OSDMap map = new OSDMap(1); map["Flags"] = OSD.FromInteger(Flags); return map; } public override void Deserialize(OSDMap map) { Flags = map["Flags"].AsInteger(); } } /// <summary> /// A message sent from the simulator to the viewer which contains an array of map images and their grid coordinates /// </summary> public class MapLayerReplyVariant : MapLayerMessageBase { /// <summary> /// An object containing map location details /// </summary> public class LayerData { /// <summary>The Asset ID of the regions tile overlay</summary> public UUID ImageID; /// <summary>The grid location of the southern border of the map tile</summary> public int Bottom; /// <summary>The grid location of the western border of the map tile</summary> public int Left; /// <summary>The grid location of the eastern border of the map tile</summary> public int Right; /// <summary>The grid location of the northern border of the map tile</summary> public int Top; } /// <summary>An array containing LayerData items</summary> public LayerData[] LayerDataBlocks; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); OSDMap agentMap = new OSDMap(1); agentMap["Flags"] = OSD.FromInteger(Flags); map["AgentData"] = agentMap; OSDArray layerArray = new OSDArray(LayerDataBlocks.Length); for (int i = 0; i < LayerDataBlocks.Length; i++) { OSDMap layerMap = new OSDMap(5); layerMap["ImageID"] = OSD.FromUUID(LayerDataBlocks[i].ImageID); layerMap["Bottom"] = OSD.FromInteger(LayerDataBlocks[i].Bottom); layerMap["Left"] = OSD.FromInteger(LayerDataBlocks[i].Left); layerMap["Top"] = OSD.FromInteger(LayerDataBlocks[i].Top); layerMap["Right"] = OSD.FromInteger(LayerDataBlocks[i].Right); layerArray.Add(layerMap); } map["LayerData"] = layerArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { OSDMap agentMap = (OSDMap)map["AgentData"]; Flags = agentMap["Flags"].AsInteger(); OSDArray layerArray = (OSDArray)map["LayerData"]; LayerDataBlocks = new LayerData[layerArray.Count]; for (int i = 0; i < LayerDataBlocks.Length; i++) { OSDMap layerMap = (OSDMap)layerArray[i]; LayerData layer = new LayerData(); layer.ImageID = layerMap["ImageID"].AsUUID(); layer.Top = layerMap["Top"].AsInteger(); layer.Right = layerMap["Right"].AsInteger(); layer.Left = layerMap["Left"].AsInteger(); layer.Bottom = layerMap["Bottom"].AsInteger(); LayerDataBlocks[i] = layer; } } } public class MapLayerMessage : IMessage { /// <summary>Object containing request or response</summary> public MapLayerMessageBase Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("LayerData")) Request = new MapLayerReplyVariant(); else if (map.ContainsKey("Flags")) Request = new MapLayerRequestVariant(); else Logger.Log("Unable to deserialize MapLayerMessage: No message handler exists", Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } #endregion #region Session/Communication /// <summary> /// New as of 1.23 RC1, no details yet. /// </summary> public class ProductInfoRequestMessage : IMessage { /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { throw new NotImplementedException(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { throw new NotImplementedException(); } } #region ChatSessionRequestMessage public abstract class SearchStatRequestBlock { public abstract OSDMap Serialize(); public abstract void Deserialize(OSDMap map); } // variant A - the request to the simulator public class SearchStatRequestRequest : SearchStatRequestBlock { public UUID ClassifiedID; public override OSDMap Serialize() { OSDMap map = new OSDMap(1); map["classified_id"] = OSD.FromUUID(ClassifiedID); return map; } public override void Deserialize(OSDMap map) { ClassifiedID = map["classified_id"].AsUUID(); } } public class SearchStatRequestReply : SearchStatRequestBlock { public int MapClicks; public int ProfileClicks; public int SearchMapClicks; public int SearchProfileClicks; public int SearchTeleportClicks; public int TeleportClicks; public override OSDMap Serialize() { OSDMap map = new OSDMap(6); map["map_clicks"] = OSD.FromInteger(MapClicks); map["profile_clicks"] = OSD.FromInteger(ProfileClicks); map["search_map_clicks"] = OSD.FromInteger(SearchMapClicks); map["search_profile_clicks"] = OSD.FromInteger(SearchProfileClicks); map["search_teleport_clicks"] = OSD.FromInteger(SearchTeleportClicks); map["teleport_clicks"] = OSD.FromInteger(TeleportClicks); return map; } public override void Deserialize(OSDMap map) { MapClicks = map["map_clicks"].AsInteger(); ProfileClicks = map["profile_clicks"].AsInteger(); SearchMapClicks = map["search_map_clicks"].AsInteger(); SearchProfileClicks = map["search_profile_clicks"].AsInteger(); SearchTeleportClicks = map["search_teleport_clicks"].AsInteger(); TeleportClicks = map["teleport_clicks"].AsInteger(); } } public class SearchStatRequestMessage : IMessage { public SearchStatRequestBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("map_clicks")) Request = new SearchStatRequestReply(); else if (map.ContainsKey("classified_id")) Request = new SearchStatRequestRequest(); else Logger.Log("Unable to deserialize SearchStatRequest: No message handler exists for method " + map["method"].AsString(), Helpers.LogLevel.Warning); Request.Deserialize(map); } } public abstract class ChatSessionRequestBlock { /// <summary>A string containing the method used</summary> public string Method; public abstract OSDMap Serialize(); public abstract void Deserialize(OSDMap map); } /// <summary> /// A request sent from an agent to the Simulator to begin a new conference. /// Contains a list of Agents which will be included in the conference /// </summary> public class ChatSessionRequestStartConference : ChatSessionRequestBlock { /// <summary>An array containing the <see cref="UUID"/> of the agents invited to this conference</summary> public UUID[] AgentsBlock; /// <summary>The conferences Session ID</summary> public UUID SessionID; public ChatSessionRequestStartConference() { Method = "start conference"; } /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(3); map["method"] = OSD.FromString(Method); OSDArray agentsArray = new OSDArray(); for (int i = 0; i < AgentsBlock.Length; i++) { agentsArray.Add(OSD.FromUUID(AgentsBlock[i])); } map["params"] = agentsArray; map["session-id"] = OSD.FromUUID(SessionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { Method = map["method"].AsString(); OSDArray agentsArray = (OSDArray)map["params"]; AgentsBlock = new UUID[agentsArray.Count]; for (int i = 0; i < agentsArray.Count; i++) { AgentsBlock[i] = agentsArray[i].AsUUID(); } SessionID = map["session-id"].AsUUID(); } } /// <summary> /// A moderation request sent from a conference moderator /// Contains an agent and an optional action to take /// </summary> public class ChatSessionRequestMuteUpdate : ChatSessionRequestBlock { /// <summary>The Session ID</summary> public UUID SessionID; /// <summary></summary> public UUID AgentID; /// <summary>A list containing Key/Value pairs, known valid values: /// key: text value: true/false - allow/disallow specified agents ability to use text in session /// key: voice value: true/false - allow/disallow specified agents ability to use voice in session /// </summary> /// <remarks>"text" or "voice"</remarks> public string RequestKey; /// <summary></summary> public bool RequestValue; public ChatSessionRequestMuteUpdate() { Method = "mute update"; } /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(3); map["method"] = OSD.FromString(Method); OSDMap muteMap = new OSDMap(1); muteMap[RequestKey] = OSD.FromBoolean(RequestValue); OSDMap paramMap = new OSDMap(2); paramMap["agent_id"] = OSD.FromUUID(AgentID); paramMap["mute_info"] = muteMap; map["params"] = paramMap; map["session-id"] = OSD.FromUUID(SessionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { Method = map["method"].AsString(); SessionID = map["session-id"].AsUUID(); OSDMap paramsMap = (OSDMap)map["params"]; OSDMap muteMap = (OSDMap)paramsMap["mute_info"]; AgentID = paramsMap["agent_id"].AsUUID(); if (muteMap.ContainsKey("text")) RequestKey = "text"; else if (muteMap.ContainsKey("voice")) RequestKey = "voice"; RequestValue = muteMap[RequestKey].AsBoolean(); } } /// <summary> /// A message sent from the agent to the simulator which tells the /// simulator we've accepted a conference invitation /// </summary> public class ChatSessionAcceptInvitation : ChatSessionRequestBlock { /// <summary>The conference SessionID</summary> public UUID SessionID; public ChatSessionAcceptInvitation() { Method = "accept invitation"; } /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["method"] = OSD.FromString(Method); map["session-id"] = OSD.FromUUID(SessionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { Method = map["method"].AsString(); SessionID = map["session-id"].AsUUID(); } } public class ChatSessionRequestMessage : IMessage { public ChatSessionRequestBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("method") && map["method"].AsString().Equals("start conference")) Request = new ChatSessionRequestStartConference(); else if (map.ContainsKey("method") && map["method"].AsString().Equals("mute update")) Request = new ChatSessionRequestMuteUpdate(); else if (map.ContainsKey("method") && map["method"].AsString().Equals("accept invitation")) Request = new ChatSessionAcceptInvitation(); else Logger.Log("Unable to deserialize ChatSessionRequest: No message handler exists for method " + map["method"].AsString(), Helpers.LogLevel.Warning); Request.Deserialize(map); } } #endregion public class ChatterboxSessionEventReplyMessage : IMessage { public UUID SessionID; public bool Success; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); map["success"] = OSD.FromBoolean(Success); map["session_id"] = OSD.FromUUID(SessionID); // FIXME: Verify this is correct map name return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { Success = map["success"].AsBoolean(); SessionID = map["session_id"].AsUUID(); } } public class ChatterBoxSessionStartReplyMessage : IMessage { public UUID SessionID; public UUID TempSessionID; public bool Success; public string SessionName; // FIXME: Replace int with an enum public int Type; public bool VoiceEnabled; public bool ModeratedVoice; /* Is Text moderation possible? */ /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap moderatedMap = new OSDMap(1); moderatedMap["voice"] = OSD.FromBoolean(ModeratedVoice); OSDMap sessionMap = new OSDMap(4); sessionMap["type"] = OSD.FromInteger(Type); sessionMap["session_name"] = OSD.FromString(SessionName); sessionMap["voice_enabled"] = OSD.FromBoolean(VoiceEnabled); sessionMap["moderated_mode"] = moderatedMap; OSDMap map = new OSDMap(4); map["session_id"] = OSD.FromUUID(SessionID); map["temp_session_id"] = OSD.FromUUID(TempSessionID); map["success"] = OSD.FromBoolean(Success); map["session_info"] = sessionMap; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { SessionID = map["session_id"].AsUUID(); TempSessionID = map["temp_session_id"].AsUUID(); Success = map["success"].AsBoolean(); if (Success) { OSDMap sessionMap = (OSDMap)map["session_info"]; SessionName = sessionMap["session_name"].AsString(); Type = sessionMap["type"].AsInteger(); VoiceEnabled = sessionMap["voice_enabled"].AsBoolean(); OSDMap moderatedModeMap = (OSDMap)sessionMap["moderated_mode"]; ModeratedVoice = moderatedModeMap["voice"].AsBoolean(); } } } public class ChatterBoxInvitationMessage : IMessage { /// <summary>Key of sender</summary> public UUID FromAgentID; /// <summary>Name of sender</summary> public string FromAgentName; /// <summary>Key of destination avatar</summary> public UUID ToAgentID; /// <summary>ID of originating estate</summary> public uint ParentEstateID; /// <summary>Key of originating region</summary> public UUID RegionID; /// <summary>Coordinates in originating region</summary> public Vector3 Position; /// <summary>Instant message type</summary> public InstantMessageDialog Dialog; /// <summary>Group IM session toggle</summary> public bool GroupIM; /// <summary>Key of IM session, for Group Messages, the groups UUID</summary> public UUID IMSessionID; /// <summary>Timestamp of the instant message</summary> public DateTime Timestamp; /// <summary>Instant message text</summary> public string Message; /// <summary>Whether this message is held for offline avatars</summary> public InstantMessageOnline Offline; /// <summary>Context specific packed data</summary> public byte[] BinaryBucket; /// <summary>Is this invitation for voice group/conference chat</summary> public bool Voice; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap dataMap = new OSDMap(3); dataMap["timestamp"] = OSD.FromDate(Timestamp); dataMap["type"] = OSD.FromInteger((uint)Dialog); dataMap["binary_bucket"] = OSD.FromBinary(BinaryBucket); OSDMap paramsMap = new OSDMap(11); paramsMap["from_id"] = OSD.FromUUID(FromAgentID); paramsMap["from_name"] = OSD.FromString(FromAgentName); paramsMap["to_id"] = OSD.FromUUID(ToAgentID); paramsMap["parent_estate_id"] = OSD.FromInteger(ParentEstateID); paramsMap["region_id"] = OSD.FromUUID(RegionID); paramsMap["position"] = OSD.FromVector3(Position); paramsMap["from_group"] = OSD.FromBoolean(GroupIM); paramsMap["id"] = OSD.FromUUID(IMSessionID); paramsMap["message"] = OSD.FromString(Message); paramsMap["offline"] = OSD.FromInteger((uint)Offline); paramsMap["data"] = dataMap; OSDMap imMap = new OSDMap(1); imMap["message_params"] = paramsMap; OSDMap map = new OSDMap(1); map["instantmessage"] = imMap; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("voice")) { FromAgentID = map["from_id"].AsUUID(); FromAgentName = map["from_name"].AsString(); IMSessionID = map["session_id"].AsUUID(); BinaryBucket = Utils.StringToBytes(map["session_name"].AsString()); Voice = true; } else { OSDMap im = (OSDMap)map["instantmessage"]; OSDMap msg = (OSDMap)im["message_params"]; OSDMap msgdata = (OSDMap)msg["data"]; FromAgentID = msg["from_id"].AsUUID(); FromAgentName = msg["from_name"].AsString(); ToAgentID = msg["to_id"].AsUUID(); ParentEstateID = (uint)msg["parent_estate_id"].AsInteger(); RegionID = msg["region_id"].AsUUID(); Position = msg["position"].AsVector3(); GroupIM = msg["from_group"].AsBoolean(); IMSessionID = msg["id"].AsUUID(); Message = msg["message"].AsString(); Offline = (InstantMessageOnline)msg["offline"].AsInteger(); Dialog = (InstantMessageDialog)msgdata["type"].AsInteger(); BinaryBucket = msgdata["binary_bucket"].AsBinary(); Timestamp = msgdata["timestamp"].AsDate(); Voice = false; } } } public class RegionInfoMessage : IMessage { public int ParcelLocalID; public string RegionName; public string ChannelUri; #region IMessage Members public OSDMap Serialize() { OSDMap map = new OSDMap(3); map["parcel_local_id"] = OSD.FromInteger(ParcelLocalID); map["region_name"] = OSD.FromString(RegionName); OSDMap voiceMap = new OSDMap(1); voiceMap["channel_uri"] = OSD.FromString(ChannelUri); map["voice_credentials"] = voiceMap; return map; } public void Deserialize(OSDMap map) { this.ParcelLocalID = map["parcel_local_id"].AsInteger(); this.RegionName = map["region_name"].AsString(); OSDMap voiceMap = (OSDMap)map["voice_credentials"]; this.ChannelUri = voiceMap["channel_uri"].AsString(); } #endregion } /// <summary> /// Sent from the simulator to the viewer. /// /// When an agent initially joins a session the AgentUpdatesBlock object will contain a list of session members including /// a boolean indicating they can use voice chat in this session, a boolean indicating they are allowed to moderate /// this session, and lastly a string which indicates another agent is entering the session with the Transition set to "ENTER" /// /// During the session lifetime updates on individuals are sent. During the update the booleans sent during the initial join are /// excluded with the exception of the Transition field. This indicates a new user entering or exiting the session with /// the string "ENTER" or "LEAVE" respectively. /// </summary> public class ChatterBoxSessionAgentListUpdatesMessage : IMessage { // initial when agent joins session // <llsd><map><key>events</key><array><map><key>body</key><map><key>agent_updates</key><map><key>32939971-a520-4b52-8ca5-6085d0e39933</key><map><key>info</key><map><key>can_voice_chat</key><boolean>1</boolean><key>is_moderator</key><boolean>1</boolean></map><key>transition</key><string>ENTER</string></map><key>ca00e3e1-0fdb-4136-8ed4-0aab739b29e8</key><map><key>info</key><map><key>can_voice_chat</key><boolean>1</boolean><key>is_moderator</key><boolean>0</boolean></map><key>transition</key><string>ENTER</string></map></map><key>session_id</key><string>be7a1def-bd8a-5043-5d5b-49e3805adf6b</string><key>updates</key><map><key>32939971-a520-4b52-8ca5-6085d0e39933</key><string>ENTER</string><key>ca00e3e1-0fdb-4136-8ed4-0aab739b29e8</key><string>ENTER</string></map></map><key>message</key><string>ChatterBoxSessionAgentListUpdates</string></map><map><key>body</key><map><key>agent_updates</key><map><key>32939971-a520-4b52-8ca5-6085d0e39933</key><map><key>info</key><map><key>can_voice_chat</key><boolean>1</boolean><key>is_moderator</key><boolean>1</boolean></map></map></map><key>session_id</key><string>be7a1def-bd8a-5043-5d5b-49e3805adf6b</string><key>updates</key><map /></map><key>message</key><string>ChatterBoxSessionAgentListUpdates</string></map></array><key>id</key><integer>5</integer></map></llsd> // a message containing only moderator updates // <llsd><map><key>events</key><array><map><key>body</key><map><key>agent_updates</key><map><key>ca00e3e1-0fdb-4136-8ed4-0aab739b29e8</key><map><key>info</key><map><key>mutes</key><map><key>text</key><boolean>1</boolean></map></map></map></map><key>session_id</key><string>be7a1def-bd8a-5043-5d5b-49e3805adf6b</string><key>updates</key><map /></map><key>message</key><string>ChatterBoxSessionAgentListUpdates</string></map></array><key>id</key><integer>7</integer></map></llsd> public UUID SessionID; public class AgentUpdatesBlock { public UUID AgentID; public bool CanVoiceChat; public bool IsModerator; // transition "transition" = "ENTER" or "LEAVE" public string Transition; // TODO: switch to an enum "ENTER" or "LEAVE" public bool MuteText; public bool MuteVoice; } public AgentUpdatesBlock[] Updates; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(); OSDMap agent_updatesMap = new OSDMap(1); for (int i = 0; i < Updates.Length; i++) { OSDMap mutesMap = new OSDMap(2); mutesMap["text"] = OSD.FromBoolean(Updates[i].MuteText); mutesMap["voice"] = OSD.FromBoolean(Updates[i].MuteVoice); OSDMap infoMap = new OSDMap(4); infoMap["can_voice_chat"] = OSD.FromBoolean((bool)Updates[i].CanVoiceChat); infoMap["is_moderator"] = OSD.FromBoolean((bool)Updates[i].IsModerator); infoMap["mutes"] = mutesMap; OSDMap imap = new OSDMap(1); imap["info"] = infoMap; imap["transition"] = OSD.FromString(Updates[i].Transition); agent_updatesMap.Add(Updates[i].AgentID.ToString(), imap); } map.Add("agent_updates", agent_updatesMap); map["session_id"] = OSD.FromUUID(SessionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDMap agent_updates = (OSDMap)map["agent_updates"]; SessionID = map["session_id"].AsUUID(); List<AgentUpdatesBlock> updatesList = new List<AgentUpdatesBlock>(); foreach (KeyValuePair<string, OSD> kvp in agent_updates) { if (kvp.Key == "updates") { // This appears to be redundant and duplicated by the info block, more dumps will confirm this /* <key>32939971-a520-4b52-8ca5-6085d0e39933</key> <string>ENTER</string> */ } else if (kvp.Key == "session_id") { // I am making the assumption that each osdmap will contain the information for a // single session. This is how the map appears to read however more dumps should be taken // to confirm this. /* <key>session_id</key> <string>984f6a1e-4ceb-6366-8d5e-a18c6819c6f7</string> */ } else // key is an agent uuid (we hope!) { // should be the agents uuid as the key, and "info" as the datablock /* <key>32939971-a520-4b52-8ca5-6085d0e39933</key> <map> <key>info</key> <map> <key>can_voice_chat</key> <boolean>1</boolean> <key>is_moderator</key> <boolean>1</boolean> </map> <key>transition</key> <string>ENTER</string> </map>*/ AgentUpdatesBlock block = new AgentUpdatesBlock(); block.AgentID = UUID.Parse(kvp.Key); OSDMap infoMap = (OSDMap)agent_updates[kvp.Key]; OSDMap agentPermsMap = (OSDMap)infoMap["info"]; block.CanVoiceChat = agentPermsMap["can_voice_chat"].AsBoolean(); block.IsModerator = agentPermsMap["is_moderator"].AsBoolean(); block.Transition = infoMap["transition"].AsString(); if (agentPermsMap.ContainsKey("mutes")) { OSDMap mutesMap = (OSDMap)agentPermsMap["mutes"]; block.MuteText = mutesMap["text"].AsBoolean(); block.MuteVoice = mutesMap["voice"].AsBoolean(); } updatesList.Add(block); } } Updates = new AgentUpdatesBlock[updatesList.Count]; for (int i = 0; i < updatesList.Count; i++) { AgentUpdatesBlock block = new AgentUpdatesBlock(); block.AgentID = updatesList[i].AgentID; block.CanVoiceChat = updatesList[i].CanVoiceChat; block.IsModerator = updatesList[i].IsModerator; block.MuteText = updatesList[i].MuteText; block.MuteVoice = updatesList[i].MuteVoice; block.Transition = updatesList[i].Transition; Updates[i] = block; } } } /// <summary> /// An EventQueue message sent when the agent is forcibly removed from a chatterbox session /// </summary> public class ForceCloseChatterBoxSessionMessage : IMessage { /// <summary> /// A string containing the reason the agent was removed /// </summary> public string Reason; /// <summary> /// The ChatterBoxSession's SessionID /// </summary> public UUID SessionID; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(2); map["reason"] = OSD.FromString(Reason); map["session_id"] = OSD.FromUUID(SessionID); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { Reason = map["reason"].AsString(); SessionID = map["session_id"].AsUUID(); } } #endregion #region EventQueue public abstract class EventMessageBlock { public abstract OSDMap Serialize(); public abstract void Deserialize(OSDMap map); } public class EventQueueAck : EventMessageBlock { public int AckID; public bool Done; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(); map["ack"] = OSD.FromInteger(AckID); map["done"] = OSD.FromBoolean(Done); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { AckID = map["ack"].AsInteger(); Done = map["done"].AsBoolean(); } } public class EventQueueEvent : EventMessageBlock { public class QueueEvent { public IMessage EventMessage; public string MessageKey; } public int Sequence; public QueueEvent[] MessageEvents; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(1); OSDArray eventsArray = new OSDArray(); for (int i = 0; i < MessageEvents.Length; i++) { OSDMap eventMap = new OSDMap(2); eventMap["body"] = MessageEvents[i].EventMessage.Serialize(); eventMap["message"] = OSD.FromString(MessageEvents[i].MessageKey); eventsArray.Add(eventMap); } map["events"] = eventsArray; map["id"] = OSD.FromInteger(Sequence); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { Sequence = map["id"].AsInteger(); OSDArray arrayEvents = (OSDArray)map["events"]; MessageEvents = new QueueEvent[arrayEvents.Count]; for (int i = 0; i < arrayEvents.Count; i++) { OSDMap eventMap = (OSDMap)arrayEvents[i]; QueueEvent ev = new QueueEvent(); ev.MessageKey = eventMap["message"].AsString(); ev.EventMessage = MessageUtils.DecodeEvent(ev.MessageKey, (OSDMap)eventMap["body"]); MessageEvents[i] = ev; } } } public class EventQueueGetMessage : IMessage { public EventMessageBlock Messages; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Messages.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("ack")) Messages = new EventQueueAck(); else if (map.ContainsKey("events")) Messages = new EventQueueEvent(); else Logger.Log("Unable to deserialize EventQueueGetMessage: No message handler exists for event", Helpers.LogLevel.Warning); Messages.Deserialize(map); } } #endregion #region Stats Messages public class ViewerStatsMessage : IMessage { public int AgentsInView; public float AgentFPS; public string AgentLanguage; public float AgentMemoryUsed; public float MetersTraveled; public float AgentPing; public int RegionsVisited; public float AgentRuntime; public float SimulatorFPS; public DateTime AgentStartTime; public string AgentVersion; public float object_kbytes; public float texture_kbytes; public float world_kbytes; public float MiscVersion; public bool VertexBuffersEnabled; public UUID SessionID; public int StatsDropped; public int StatsFailedResends; public int FailuresInvalid; public int FailuresOffCircuit; public int FailuresResent; public int FailuresSendPacket; public int MiscInt1; public int MiscInt2; public string MiscString1; public int InCompressedPackets; public float InKbytes; public float InPackets; public float InSavings; public int OutCompressedPackets; public float OutKbytes; public float OutPackets; public float OutSavings; public string SystemCPU; public string SystemGPU; public int SystemGPUClass; public string SystemGPUVendor; public string SystemGPUVersion; public string SystemOS; public int SystemInstalledRam; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(5); map["session_id"] = OSD.FromUUID(SessionID); OSDMap agentMap = new OSDMap(11); agentMap["agents_in_view"] = OSD.FromInteger(AgentsInView); agentMap["fps"] = OSD.FromReal(AgentFPS); agentMap["language"] = OSD.FromString(AgentLanguage); agentMap["mem_use"] = OSD.FromReal(AgentMemoryUsed); agentMap["meters_traveled"] = OSD.FromReal(MetersTraveled); agentMap["ping"] = OSD.FromReal(AgentPing); agentMap["regions_visited"] = OSD.FromInteger(RegionsVisited); agentMap["run_time"] = OSD.FromReal(AgentRuntime); agentMap["sim_fps"] = OSD.FromReal(SimulatorFPS); agentMap["start_time"] = OSD.FromUInteger(Utils.DateTimeToUnixTime(AgentStartTime)); agentMap["version"] = OSD.FromString(AgentVersion); map["agent"] = agentMap; OSDMap downloadsMap = new OSDMap(3); // downloads downloadsMap["object_kbytes"] = OSD.FromReal(object_kbytes); downloadsMap["texture_kbytes"] = OSD.FromReal(texture_kbytes); downloadsMap["world_kbytes"] = OSD.FromReal(world_kbytes); map["downloads"] = downloadsMap; OSDMap miscMap = new OSDMap(2); miscMap["Version"] = OSD.FromReal(MiscVersion); miscMap["Vertex Buffers Enabled"] = OSD.FromBoolean(VertexBuffersEnabled); map["misc"] = miscMap; OSDMap statsMap = new OSDMap(2); OSDMap failuresMap = new OSDMap(6); failuresMap["dropped"] = OSD.FromInteger(StatsDropped); failuresMap["failed_resends"] = OSD.FromInteger(StatsFailedResends); failuresMap["invalid"] = OSD.FromInteger(FailuresInvalid); failuresMap["off_circuit"] = OSD.FromInteger(FailuresOffCircuit); failuresMap["resent"] = OSD.FromInteger(FailuresResent); failuresMap["send_packet"] = OSD.FromInteger(FailuresSendPacket); statsMap["failures"] = failuresMap; OSDMap statsMiscMap = new OSDMap(3); statsMiscMap["int_1"] = OSD.FromInteger(MiscInt1); statsMiscMap["int_2"] = OSD.FromInteger(MiscInt2); statsMiscMap["string_1"] = OSD.FromString(MiscString1); statsMap["misc"] = statsMiscMap; OSDMap netMap = new OSDMap(3); // in OSDMap netInMap = new OSDMap(4); netInMap["compressed_packets"] = OSD.FromInteger(InCompressedPackets); netInMap["kbytes"] = OSD.FromReal(InKbytes); netInMap["packets"] = OSD.FromReal(InPackets); netInMap["savings"] = OSD.FromReal(InSavings); netMap["in"] = netInMap; // out OSDMap netOutMap = new OSDMap(4); netOutMap["compressed_packets"] = OSD.FromInteger(OutCompressedPackets); netOutMap["kbytes"] = OSD.FromReal(OutKbytes); netOutMap["packets"] = OSD.FromReal(OutPackets); netOutMap["savings"] = OSD.FromReal(OutSavings); netMap["out"] = netOutMap; statsMap["net"] = netMap; //system OSDMap systemStatsMap = new OSDMap(7); systemStatsMap["cpu"] = OSD.FromString(SystemCPU); systemStatsMap["gpu"] = OSD.FromString(SystemGPU); systemStatsMap["gpu_class"] = OSD.FromInteger(SystemGPUClass); systemStatsMap["gpu_vendor"] = OSD.FromString(SystemGPUVendor); systemStatsMap["gpu_version"] = OSD.FromString(SystemGPUVersion); systemStatsMap["os"] = OSD.FromString(SystemOS); systemStatsMap["ram"] = OSD.FromInteger(SystemInstalledRam); map["system"] = systemStatsMap; map["stats"] = statsMap; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { SessionID = map["session_id"].AsUUID(); OSDMap agentMap = (OSDMap)map["agent"]; AgentsInView = agentMap["agents_in_view"].AsInteger(); AgentFPS = (float)agentMap["fps"].AsReal(); AgentLanguage = agentMap["language"].AsString(); AgentMemoryUsed = (float)agentMap["mem_use"].AsReal(); MetersTraveled = agentMap["meters_traveled"].AsInteger(); AgentPing = (float)agentMap["ping"].AsReal(); RegionsVisited = agentMap["regions_visited"].AsInteger(); AgentRuntime = (float)agentMap["run_time"].AsReal(); SimulatorFPS = (float)agentMap["sim_fps"].AsReal(); AgentStartTime = Utils.UnixTimeToDateTime(agentMap["start_time"].AsUInteger()); AgentVersion = agentMap["version"].AsString(); OSDMap downloadsMap = (OSDMap)map["downloads"]; object_kbytes = (float)downloadsMap["object_kbytes"].AsReal(); texture_kbytes = (float)downloadsMap["texture_kbytes"].AsReal(); world_kbytes = (float)downloadsMap["world_kbytes"].AsReal(); OSDMap miscMap = (OSDMap)map["misc"]; MiscVersion = (float)miscMap["Version"].AsReal(); VertexBuffersEnabled = miscMap["Vertex Buffers Enabled"].AsBoolean(); OSDMap statsMap = (OSDMap)map["stats"]; OSDMap failuresMap = (OSDMap)statsMap["failures"]; StatsDropped = failuresMap["dropped"].AsInteger(); StatsFailedResends = failuresMap["failed_resends"].AsInteger(); FailuresInvalid = failuresMap["invalid"].AsInteger(); FailuresOffCircuit = failuresMap["off_circuit"].AsInteger(); FailuresResent = failuresMap["resent"].AsInteger(); FailuresSendPacket = failuresMap["send_packet"].AsInteger(); OSDMap statsMiscMap = (OSDMap)statsMap["misc"]; MiscInt1 = statsMiscMap["int_1"].AsInteger(); MiscInt2 = statsMiscMap["int_2"].AsInteger(); MiscString1 = statsMiscMap["string_1"].AsString(); OSDMap netMap = (OSDMap)statsMap["net"]; // in OSDMap netInMap = (OSDMap)netMap["in"]; InCompressedPackets = netInMap["compressed_packets"].AsInteger(); InKbytes = netInMap["kbytes"].AsInteger(); InPackets = netInMap["packets"].AsInteger(); InSavings = netInMap["savings"].AsInteger(); // out OSDMap netOutMap = (OSDMap)netMap["out"]; OutCompressedPackets = netOutMap["compressed_packets"].AsInteger(); OutKbytes = netOutMap["kbytes"].AsInteger(); OutPackets = netOutMap["packets"].AsInteger(); OutSavings = netOutMap["savings"].AsInteger(); //system OSDMap systemStatsMap = (OSDMap)map["system"]; SystemCPU = systemStatsMap["cpu"].AsString(); SystemGPU = systemStatsMap["gpu"].AsString(); SystemGPUClass = systemStatsMap["gpu_class"].AsInteger(); SystemGPUVendor = systemStatsMap["gpu_vendor"].AsString(); SystemGPUVersion = systemStatsMap["gpu_version"].AsString(); SystemOS = systemStatsMap["os"].AsString(); SystemInstalledRam = systemStatsMap["ram"].AsInteger(); } } /// <summary> /// /// </summary> public class PlacesReplyMessage : IMessage { public UUID AgentID; public UUID QueryID; public UUID TransactionID; public class QueryData { public int ActualArea; public int BillableArea; public string Description; public float Dwell; public int Flags; public float GlobalX; public float GlobalY; public float GlobalZ; public string Name; public UUID OwnerID; public string SimName; public UUID SnapShotID; public string ProductSku; public int Price; } public QueryData[] QueryDataBlocks; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); // add the AgentData map OSDMap agentIDmap = new OSDMap(2); agentIDmap["AgentID"] = OSD.FromUUID(AgentID); agentIDmap["QueryID"] = OSD.FromUUID(QueryID); OSDArray agentDataArray = new OSDArray(); agentDataArray.Add(agentIDmap); map["AgentData"] = agentDataArray; // add the QueryData map OSDArray dataBlocksArray = new OSDArray(QueryDataBlocks.Length); for (int i = 0; i < QueryDataBlocks.Length; i++) { OSDMap queryDataMap = new OSDMap(14); queryDataMap["ActualArea"] = OSD.FromInteger(QueryDataBlocks[i].ActualArea); queryDataMap["BillableArea"] = OSD.FromInteger(QueryDataBlocks[i].BillableArea); queryDataMap["Desc"] = OSD.FromString(QueryDataBlocks[i].Description); queryDataMap["Dwell"] = OSD.FromReal(QueryDataBlocks[i].Dwell); queryDataMap["Flags"] = OSD.FromInteger(QueryDataBlocks[i].Flags); queryDataMap["GlobalX"] = OSD.FromReal(QueryDataBlocks[i].GlobalX); queryDataMap["GlobalY"] = OSD.FromReal(QueryDataBlocks[i].GlobalY); queryDataMap["GlobalZ"] = OSD.FromReal(QueryDataBlocks[i].GlobalZ); queryDataMap["Name"] = OSD.FromString(QueryDataBlocks[i].Name); queryDataMap["OwnerID"] = OSD.FromUUID(QueryDataBlocks[i].OwnerID); queryDataMap["Price"] = OSD.FromInteger(QueryDataBlocks[i].Price); queryDataMap["SimName"] = OSD.FromString(QueryDataBlocks[i].SimName); queryDataMap["SnapshotID"] = OSD.FromUUID(QueryDataBlocks[i].SnapShotID); queryDataMap["ProductSKU"] = OSD.FromString(QueryDataBlocks[i].ProductSku); dataBlocksArray.Add(queryDataMap); } map["QueryData"] = dataBlocksArray; // add the TransactionData map OSDMap transMap = new OSDMap(1); transMap["TransactionID"] = OSD.FromUUID(TransactionID); OSDArray transArray = new OSDArray(); transArray.Add(transMap); map["TransactionData"] = transArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray agentDataArray = (OSDArray)map["AgentData"]; OSDMap agentDataMap = (OSDMap)agentDataArray[0]; AgentID = agentDataMap["AgentID"].AsUUID(); QueryID = agentDataMap["QueryID"].AsUUID(); OSDArray dataBlocksArray = (OSDArray)map["QueryData"]; QueryDataBlocks = new QueryData[dataBlocksArray.Count]; for (int i = 0; i < dataBlocksArray.Count; i++) { OSDMap dataMap = (OSDMap)dataBlocksArray[i]; QueryData data = new QueryData(); data.ActualArea = dataMap["ActualArea"].AsInteger(); data.BillableArea = dataMap["BillableArea"].AsInteger(); data.Description = dataMap["Desc"].AsString(); data.Dwell = (float)dataMap["Dwell"].AsReal(); data.Flags = dataMap["Flags"].AsInteger(); data.GlobalX = (float)dataMap["GlobalX"].AsReal(); data.GlobalY = (float)dataMap["GlobalY"].AsReal(); data.GlobalZ = (float)dataMap["GlobalZ"].AsReal(); data.Name = dataMap["Name"].AsString(); data.OwnerID = dataMap["OwnerID"].AsUUID(); data.Price = dataMap["Price"].AsInteger(); data.SimName = dataMap["SimName"].AsString(); data.SnapShotID = dataMap["SnapshotID"].AsUUID(); data.ProductSku = dataMap["ProductSKU"].AsString(); QueryDataBlocks[i] = data; } OSDArray transactionArray = (OSDArray)map["TransactionData"]; OSDMap transactionDataMap = (OSDMap)transactionArray[0]; TransactionID = transactionDataMap["TransactionID"].AsUUID(); } } public class UpdateAgentInformationMessage : IMessage { public string MaxAccess; // PG, A, or M /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); OSDMap prefsMap = new OSDMap(1); prefsMap["max"] = OSD.FromString(MaxAccess); map["access_prefs"] = prefsMap; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDMap prefsMap = (OSDMap)map["access_prefs"]; MaxAccess = prefsMap["max"].AsString(); } } [Serializable] public class DirLandReplyMessage : IMessage { public UUID AgentID; public UUID QueryID; [Serializable] public class QueryReply { public int ActualArea; public bool Auction; public bool ForSale; public string Name; public UUID ParcelID; public string ProductSku; public int SalePrice; } public QueryReply[] QueryReplies; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); OSDMap agentMap = new OSDMap(1); agentMap["AgentID"] = OSD.FromUUID(AgentID); OSDArray agentDataArray = new OSDArray(1); agentDataArray.Add(agentMap); map["AgentData"] = agentDataArray; OSDMap queryMap = new OSDMap(1); queryMap["QueryID"] = OSD.FromUUID(QueryID); OSDArray queryDataArray = new OSDArray(1); queryDataArray.Add(queryMap); map["QueryData"] = queryDataArray; OSDArray queryReplyArray = new OSDArray(); for (int i = 0; i < QueryReplies.Length; i++) { OSDMap queryReply = new OSDMap(100); queryReply["ActualArea"] = OSD.FromInteger(QueryReplies[i].ActualArea); queryReply["Auction"] = OSD.FromBoolean(QueryReplies[i].Auction); queryReply["ForSale"] = OSD.FromBoolean(QueryReplies[i].ForSale); queryReply["Name"] = OSD.FromString(QueryReplies[i].Name); queryReply["ParcelID"] = OSD.FromUUID(QueryReplies[i].ParcelID); queryReply["ProductSKU"] = OSD.FromString(QueryReplies[i].ProductSku); queryReply["SalePrice"] = OSD.FromInteger(QueryReplies[i].SalePrice); queryReplyArray.Add(queryReply); } map["QueryReplies"] = queryReplyArray; return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { OSDArray agentDataArray = (OSDArray)map["AgentData"]; OSDMap agentDataMap = (OSDMap)agentDataArray[0]; AgentID = agentDataMap["AgentID"].AsUUID(); OSDArray queryDataArray = (OSDArray)map["QueryData"]; OSDMap queryDataMap = (OSDMap)queryDataArray[0]; QueryID = queryDataMap["QueryID"].AsUUID(); OSDArray queryRepliesArray = (OSDArray)map["QueryReplies"]; QueryReplies = new QueryReply[queryRepliesArray.Count]; for (int i = 0; i < queryRepliesArray.Count; i++) { QueryReply reply = new QueryReply(); OSDMap replyMap = (OSDMap)queryRepliesArray[i]; reply.ActualArea = replyMap["ActualArea"].AsInteger(); reply.Auction = replyMap["Auction"].AsBoolean(); reply.ForSale = replyMap["ForSale"].AsBoolean(); reply.Name = replyMap["Name"].AsString(); reply.ParcelID = replyMap["ParcelID"].AsUUID(); reply.ProductSku = replyMap["ProductSKU"].AsString(); reply.SalePrice = replyMap["SalePrice"].AsInteger(); QueryReplies[i] = reply; } } } #endregion #region Object Messages public class UploadObjectAssetMessage : IMessage { public class Object { public class Face { public Bumpiness Bump; public Color4 Color; public bool Fullbright; public float Glow; public UUID ImageID; public float ImageRot; public int MediaFlags; public float OffsetS; public float OffsetT; public float ScaleS; public float ScaleT; public OSDMap Serialize() { OSDMap map = new OSDMap(); map["bump"] = OSD.FromInteger((int)Bump); map["colors"] = OSD.FromColor4(Color); map["fullbright"] = OSD.FromBoolean(Fullbright); map["glow"] = OSD.FromReal(Glow); map["imageid"] = OSD.FromUUID(ImageID); map["imagerot"] = OSD.FromReal(ImageRot); map["media_flags"] = OSD.FromInteger(MediaFlags); map["offsets"] = OSD.FromReal(OffsetS); map["offsett"] = OSD.FromReal(OffsetT); map["scales"] = OSD.FromReal(ScaleS); map["scalet"] = OSD.FromReal(ScaleT); return map; } public void Deserialize(OSDMap map) { Bump = (Bumpiness)map["bump"].AsInteger(); Color = map["colors"].AsColor4(); Fullbright = map["fullbright"].AsBoolean(); Glow = (float)map["glow"].AsReal(); ImageID = map["imageid"].AsUUID(); ImageRot = (float)map["imagerot"].AsReal(); MediaFlags = map["media_flags"].AsInteger(); OffsetS = (float)map["offsets"].AsReal(); OffsetT = (float)map["offsett"].AsReal(); ScaleS = (float)map["scales"].AsReal(); ScaleT = (float)map["scalet"].AsReal(); } } public class ExtraParam { public ExtraParamType Type; public byte[] ExtraParamData; public OSDMap Serialize() { OSDMap map = new OSDMap(); map["extra_parameter"] = OSD.FromInteger((int)Type); map["param_data"] = OSD.FromBinary(ExtraParamData); return map; } public void Deserialize(OSDMap map) { Type = (ExtraParamType)map["extra_parameter"].AsInteger(); ExtraParamData = map["param_data"].AsBinary(); } } public Face[] Faces; public ExtraParam[] ExtraParams; public UUID GroupID; public Material Material; public string Name; public Vector3 Position; public Quaternion Rotation; public Vector3 Scale; public float PathBegin; public int PathCurve; public float PathEnd; public float RadiusOffset; public float Revolutions; public float ScaleX; public float ScaleY; public float ShearX; public float ShearY; public float Skew; public float TaperX; public float TaperY; public float Twist; public float TwistBegin; public float ProfileBegin; public int ProfileCurve; public float ProfileEnd; public float ProfileHollow; public UUID SculptID; public SculptType SculptType; public OSDMap Serialize() { OSDMap map = new OSDMap(); map["group-id"] = OSD.FromUUID(GroupID); map["material"] = OSD.FromInteger((int)Material); map["name"] = OSD.FromString(Name); map["pos"] = OSD.FromVector3(Position); map["rotation"] = OSD.FromQuaternion(Rotation); map["scale"] = OSD.FromVector3(Scale); // Extra params OSDArray extraParams = new OSDArray(); if (ExtraParams != null) { for (int i = 0; i < ExtraParams.Length; i++) extraParams.Add(ExtraParams[i].Serialize()); } map["extra_parameters"] = extraParams; // Faces OSDArray faces = new OSDArray(); if (Faces != null) { for (int i = 0; i < Faces.Length; i++) faces.Add(Faces[i].Serialize()); } map["facelist"] = faces; // Shape OSDMap shape = new OSDMap(); OSDMap path = new OSDMap(); path["begin"] = OSD.FromReal(PathBegin); path["curve"] = OSD.FromInteger(PathCurve); path["end"] = OSD.FromReal(PathEnd); path["radius_offset"] = OSD.FromReal(RadiusOffset); path["revolutions"] = OSD.FromReal(Revolutions); path["scale_x"] = OSD.FromReal(ScaleX); path["scale_y"] = OSD.FromReal(ScaleY); path["shear_x"] = OSD.FromReal(ShearX); path["shear_y"] = OSD.FromReal(ShearY); path["skew"] = OSD.FromReal(Skew); path["taper_x"] = OSD.FromReal(TaperX); path["taper_y"] = OSD.FromReal(TaperY); path["twist"] = OSD.FromReal(Twist); path["twist_begin"] = OSD.FromReal(TwistBegin); shape["path"] = path; OSDMap profile = new OSDMap(); profile["begin"] = OSD.FromReal(ProfileBegin); profile["curve"] = OSD.FromInteger(ProfileCurve); profile["end"] = OSD.FromReal(ProfileEnd); profile["hollow"] = OSD.FromReal(ProfileHollow); shape["profile"] = profile; OSDMap sculpt = new OSDMap(); sculpt["id"] = OSD.FromUUID(SculptID); sculpt["type"] = OSD.FromInteger((int)SculptType); shape["sculpt"] = sculpt; map["shape"] = shape; return map; } public void Deserialize(OSDMap map) { GroupID = map["group-id"].AsUUID(); Material = (Material)map["material"].AsInteger(); Name = map["name"].AsString(); Position = map["pos"].AsVector3(); Rotation = map["rotation"].AsQuaternion(); Scale = map["scale"].AsVector3(); // Extra params OSDArray extraParams = map["extra_parameters"] as OSDArray; if (extraParams != null) { ExtraParams = new ExtraParam[extraParams.Count]; for (int i = 0; i < extraParams.Count; i++) { ExtraParam extraParam = new ExtraParam(); extraParam.Deserialize(extraParams[i] as OSDMap); ExtraParams[i] = extraParam; } } else { ExtraParams = new ExtraParam[0]; } // Faces OSDArray faces = map["facelist"] as OSDArray; if (faces != null) { Faces = new Face[faces.Count]; for (int i = 0; i < faces.Count; i++) { Face face = new Face(); face.Deserialize(faces[i] as OSDMap); Faces[i] = face; } } else { Faces = new Face[0]; } // Shape OSDMap shape = map["shape"] as OSDMap; OSDMap path = shape["path"] as OSDMap; PathBegin = (float)path["begin"].AsReal(); PathCurve = path["curve"].AsInteger(); PathEnd = (float)path["end"].AsReal(); RadiusOffset = (float)path["radius_offset"].AsReal(); Revolutions = (float)path["revolutions"].AsReal(); ScaleX = (float)path["scale_x"].AsReal(); ScaleY = (float)path["scale_y"].AsReal(); ShearX = (float)path["shear_x"].AsReal(); ShearY = (float)path["shear_y"].AsReal(); Skew = (float)path["skew"].AsReal(); TaperX = (float)path["taper_x"].AsReal(); TaperY = (float)path["taper_y"].AsReal(); Twist = (float)path["twist"].AsReal(); TwistBegin = (float)path["twist_begin"].AsReal(); OSDMap profile = shape["profile"] as OSDMap; ProfileBegin = (float)profile["begin"].AsReal(); ProfileCurve = profile["curve"].AsInteger(); ProfileEnd = (float)profile["end"].AsReal(); ProfileHollow = (float)profile["hollow"].AsReal(); OSDMap sculpt = shape["sculpt"] as OSDMap; if (sculpt != null) { SculptID = sculpt["id"].AsUUID(); SculptType = (SculptType)sculpt["type"].AsInteger(); } else { SculptID = UUID.Zero; SculptType = 0; } } } public Object[] Objects; public OSDMap Serialize() { OSDMap map = new OSDMap(); OSDArray array = new OSDArray(); if (Objects != null) { for (int i = 0; i < Objects.Length; i++) array.Add(Objects[i].Serialize()); } map["objects"] = array; return map; } public void Deserialize(OSDMap map) { OSDArray array = map["objects"] as OSDArray; if (array != null) { Objects = new Object[array.Count]; for (int i = 0; i < array.Count; i++) { Object obj = new Object(); OSDMap objMap = array[i] as OSDMap; if (objMap != null) obj.Deserialize(objMap); Objects[i] = obj; } } else { Objects = new Object[0]; } } } /// <summary> /// Event Queue message describing physics engine attributes of a list of objects /// Sim sends these when object is selected /// </summary> public class ObjectPhysicsPropertiesMessage : IMessage { /// <summary> Array with the list of physics properties</summary> public Primitive.PhysicsProperties[] ObjectPhysicsProperties; /// <summary> /// Serializes the message /// </summary> /// <returns>Serialized OSD</returns> public OSDMap Serialize() { OSDMap ret = new OSDMap(); OSDArray array = new OSDArray(); for (int i = 0; i < ObjectPhysicsProperties.Length; i++) { array.Add(ObjectPhysicsProperties[i].GetOSD()); } ret["ObjectData"] = array; return ret; } /// <summary> /// Deserializes the message /// </summary> /// <param name="map">Incoming data to deserialize</param> public void Deserialize(OSDMap map) { OSDArray array = map["ObjectData"] as OSDArray; if (array != null) { ObjectPhysicsProperties = new Primitive.PhysicsProperties[array.Count]; for (int i = 0; i < array.Count; i++) { ObjectPhysicsProperties[i] = Primitive.PhysicsProperties.FromOSD(array[i]); } } else { ObjectPhysicsProperties = new Primitive.PhysicsProperties[0]; } } } public class RenderMaterialsMessage : IMessage { public OSD MaterialData; /// <summary> /// Deserializes the message /// </summary> /// <param name="map">Incoming data to deserialize</param> public void Deserialize(OSDMap map) { try { using (MemoryStream input = new MemoryStream(map["Zipped"].AsBinary())) { using (MemoryStream output = new MemoryStream()) { using (ZOutputStream zout = new ZOutputStream(output)) { byte[] buffer = new byte[2048]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { zout.Write(buffer, 0, len); } zout.Flush(); output.Seek(0, SeekOrigin.Begin); MaterialData = OSDParser.DeserializeLLSDBinary(output); } } } } catch (Exception ex) { Logger.Log("Failed to decode RenderMaterials message:", Helpers.LogLevel.Warning, ex); MaterialData = new OSDMap(); } } /// <summary> /// Serializes the message /// </summary> /// <returns>Serialized OSD</returns> public OSDMap Serialize() { return new OSDMap(); } } public class GetObjectCostRequest : IMessage { /// <summary> Object IDs for which to request cost information public UUID[] ObjectIDs; /// <summary> /// Deserializes the message /// </summary> /// <param name="map">Incoming data to deserialize</param> public void Deserialize(OSDMap map) { OSDArray array = map["object_ids"] as OSDArray; if (array != null) { ObjectIDs = new UUID[array.Count]; for (int i = 0; i < array.Count; i++) { ObjectIDs[i] = array[i].AsUUID(); } } else { ObjectIDs = new UUID[0]; } } /// <summary> /// Serializes the message /// </summary> /// <returns>Serialized OSD</returns> public OSDMap Serialize() { OSDMap ret = new OSDMap(); OSDArray array = new OSDArray(); for (int i = 0; i < ObjectIDs.Length; i++) { array.Add(OSD.FromUUID(ObjectIDs[i])); } ret["object_ids"] = array; return ret; } } public class GetObjectCostMessage : IMessage { public UUID object_id; public double link_cost; public double object_cost; public double physics_cost; public double link_physics_cost; /// <summary> /// Deserializes the message /// </summary> /// <param name="map">Incoming data to deserialize</param> public void Deserialize(OSDMap map) { if (map.Count != 1) Logger.Log("GetObjectCostMessage returned values for more than one object! Function needs to be fixed for that!", Helpers.LogLevel.Error); foreach (string key in map.Keys) { UUID.TryParse(key, out object_id); OSDMap values = (OSDMap)map[key]; link_cost = values["linked_set_resource_cost"].AsReal(); object_cost = values["resource_cost"].AsReal(); physics_cost = values["physics_cost"].AsReal(); link_physics_cost = values["linked_set_physics_cost"].AsReal(); // value["resource_limiting_type"].AsString(); return; } } /// <summary> /// Serializes the message /// </summary> /// <returns>Serialized OSD</returns> public OSDMap Serialize() { OSDMap values = new OSDMap(4); values.Add("linked_set_resource_cost", OSD.FromReal(link_cost)); values.Add("resource_cost", OSD.FromReal(object_cost)); values.Add("physics_cost", OSD.FromReal(physics_cost)); values.Add("linked_set_physics_cost", OSD.FromReal(link_physics_cost)); OSDMap map = new OSDMap(1); map.Add(OSD.FromUUID(object_id), values); return map; } /// <summary> /// Detects which class handles deserialization of this message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> /// <returns>Object capable of decoding this message</returns> public static IMessage GetMessageHandler(OSDMap map) { if (map == null) { return null; } else if (map.ContainsKey("object_ids")) { return new GetObjectCostRequest(); } else { return new GetObjectCostMessage(); } } } #endregion Object Messages #region Object Media Messages /// <summary> /// A message sent from the viewer to the simulator which /// specifies that the user has changed current URL /// of the specific media on a prim face /// </summary> public class ObjectMediaNavigateMessage : IMessage { /// <summary> /// New URL /// </summary> public string URL; /// <summary> /// Prim UUID where navigation occured /// </summary> public UUID PrimID; /// <summary> /// Face index /// </summary> public int Face; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(3); map["current_url"] = OSD.FromString(URL); map["object_id"] = OSD.FromUUID(PrimID); map["texture_index"] = OSD.FromInteger(Face); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { URL = map["current_url"].AsString(); PrimID = map["object_id"].AsUUID(); Face = map["texture_index"].AsInteger(); } } /// <summary>Base class used for the ObjectMedia message</summary> [Serializable] public abstract class ObjectMediaBlock { public abstract OSDMap Serialize(); public abstract void Deserialize(OSDMap map); } /// <summary> /// Message used to retrive prim media data /// </summary> public class ObjectMediaRequest : ObjectMediaBlock { /// <summary> /// Prim UUID /// </summary> public UUID PrimID; /// <summary> /// Requested operation, either GET or UPDATE /// </summary> public string Verb = "GET"; // "GET" or "UPDATE" /// <summary> /// Serialize object /// </summary> /// <returns>Serialized object as OSDMap</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["object_id"] = OSD.FromUUID(PrimID); map["verb"] = OSD.FromString(Verb); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { PrimID = map["object_id"].AsUUID(); Verb = map["verb"].AsString(); } } /// <summary> /// Message used to update prim media data /// </summary> public class ObjectMediaResponse : ObjectMediaBlock { /// <summary> /// Prim UUID /// </summary> public UUID PrimID; /// <summary> /// Array of media entries indexed by face number /// </summary> public MediaEntry[] FaceMedia; /// <summary> /// Media version string /// </summary> public string Version; // String in this format: x-mv:0000000016/00000000-0000-0000-0000-000000000000 /// <summary> /// Serialize object /// </summary> /// <returns>Serialized object as OSDMap</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["object_id"] = OSD.FromUUID(PrimID); if (FaceMedia == null) { map["object_media_data"] = new OSDArray(); } else { OSDArray mediaData = new OSDArray(FaceMedia.Length); for (int i = 0; i < FaceMedia.Length; i++) { if (FaceMedia[i] == null) mediaData.Add(new OSD()); else mediaData.Add(FaceMedia[i].GetOSD()); } map["object_media_data"] = mediaData; } map["object_media_version"] = OSD.FromString(Version); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { PrimID = map["object_id"].AsUUID(); if (map["object_media_data"].Type == OSDType.Array) { OSDArray mediaData = (OSDArray)map["object_media_data"]; if (mediaData.Count > 0) { FaceMedia = new MediaEntry[mediaData.Count]; for (int i = 0; i < mediaData.Count; i++) { if (mediaData[i].Type == OSDType.Map) { FaceMedia[i] = MediaEntry.FromOSD(mediaData[i]); } } } } Version = map["object_media_version"].AsString(); } } /// <summary> /// Message used to update prim media data /// </summary> public class ObjectMediaUpdate : ObjectMediaBlock { /// <summary> /// Prim UUID /// </summary> public UUID PrimID; /// <summary> /// Array of media entries indexed by face number /// </summary> public MediaEntry[] FaceMedia; /// <summary> /// Requested operation, either GET or UPDATE /// </summary> public string Verb = "UPDATE"; // "GET" or "UPDATE" /// <summary> /// Serialize object /// </summary> /// <returns>Serialized object as OSDMap</returns> public override OSDMap Serialize() { OSDMap map = new OSDMap(2); map["object_id"] = OSD.FromUUID(PrimID); if (FaceMedia == null) { map["object_media_data"] = new OSDArray(); } else { OSDArray mediaData = new OSDArray(FaceMedia.Length); for (int i = 0; i < FaceMedia.Length; i++) { if (FaceMedia[i] == null) mediaData.Add(new OSD()); else mediaData.Add(FaceMedia[i].GetOSD()); } map["object_media_data"] = mediaData; } map["verb"] = OSD.FromString(Verb); return map; } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { PrimID = map["object_id"].AsUUID(); if (map["object_media_data"].Type == OSDType.Array) { OSDArray mediaData = (OSDArray)map["object_media_data"]; if (mediaData.Count > 0) { FaceMedia = new MediaEntry[mediaData.Count]; for (int i = 0; i < mediaData.Count; i++) { if (mediaData[i].Type == OSDType.Map) { FaceMedia[i] = MediaEntry.FromOSD(mediaData[i]); } } } } Verb = map["verb"].AsString(); } } /// <summary> /// Message for setting or getting per face MediaEntry /// </summary> [Serializable] public class ObjectMediaMessage : IMessage { /// <summary>The request or response details block</summary> public ObjectMediaBlock Request; /// <summary> /// Serialize the object /// </summary> /// <returns>An <see cref="OSDMap"/> containing the objects data</returns> public OSDMap Serialize() { return Request.Serialize(); } /// <summary> /// Deserialize the message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("verb")) { if (map["verb"].AsString() == "GET") Request = new ObjectMediaRequest(); else if (map["verb"].AsString() == "UPDATE") Request = new ObjectMediaUpdate(); } else if (map.ContainsKey("object_media_version")) Request = new ObjectMediaResponse(); else Logger.Log("Unable to deserialize ObjectMedia: No message handler exists for method: " + map.AsString(), Helpers.LogLevel.Warning); if (Request != null) Request.Deserialize(map); } } #endregion Object Media Messages #region Resource usage /// <summary>Details about object resource usage</summary> public class ObjectResourcesDetail { /// <summary>Object UUID</summary> public UUID ID; /// <summary>Object name</summary> public string Name; /// <summary>Indicates if object is group owned</summary> public bool GroupOwned; /// <summary>Locatio of the object</summary> public Vector3d Location; /// <summary>Object owner</summary> public UUID OwnerID; /// <summary>Resource usage, keys are resource names, values are resource usage for that specific resource</summary> public Dictionary<string, int> Resources; /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="obj">An <see cref="OSDMap"/> containing the data</param> public virtual void Deserialize(OSDMap obj) { ID = obj["id"].AsUUID(); Name = obj["name"].AsString(); Location = obj["location"].AsVector3d(); GroupOwned = obj["is_group_owned"].AsBoolean(); OwnerID = obj["owner_id"].AsUUID(); OSDMap resources = (OSDMap)obj["resources"]; Resources = new Dictionary<string, int>(resources.Keys.Count); foreach (KeyValuePair<string, OSD> kvp in resources) { Resources.Add(kvp.Key, kvp.Value.AsInteger()); } } /// <summary> /// Makes an instance based on deserialized data /// </summary> /// <param name="osd"><see cref="OSD"/> serialized data</param> /// <returns>Instance containg deserialized data</returns> public static ObjectResourcesDetail FromOSD(OSD osd) { ObjectResourcesDetail res = new ObjectResourcesDetail(); res.Deserialize((OSDMap)osd); return res; } } /// <summary>Details about parcel resource usage</summary> public class ParcelResourcesDetail { /// <summary>Parcel UUID</summary> public UUID ID; /// <summary>Parcel local ID</summary> public int LocalID; /// <summary>Parcel name</summary> public string Name; /// <summary>Indicates if parcel is group owned</summary> public bool GroupOwned; /// <summary>Parcel owner</summary> public UUID OwnerID; /// <summary>Array of <see cref="ObjectResourcesDetail"/> containing per object resource usage</summary> public ObjectResourcesDetail[] Objects; /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public virtual void Deserialize(OSDMap map) { ID = map["id"].AsUUID(); LocalID = map["local_id"].AsInteger(); Name = map["name"].AsString(); GroupOwned = map["is_group_owned"].AsBoolean(); OwnerID = map["owner_id"].AsUUID(); OSDArray objectsOSD = (OSDArray)map["objects"]; Objects = new ObjectResourcesDetail[objectsOSD.Count]; for (int i = 0; i < objectsOSD.Count; i++) { Objects[i] = ObjectResourcesDetail.FromOSD(objectsOSD[i]); } } /// <summary> /// Makes an instance based on deserialized data /// </summary> /// <param name="osd"><see cref="OSD"/> serialized data</param> /// <returns>Instance containg deserialized data</returns> public static ParcelResourcesDetail FromOSD(OSD osd) { ParcelResourcesDetail res = new ParcelResourcesDetail(); res.Deserialize((OSDMap)osd); return res; } } /// <summary>Resource usage base class, both agent and parcel resource /// usage contains summary information</summary> public abstract class BaseResourcesInfo : IMessage { /// <summary>Summary of available resources, keys are resource names, /// values are resource usage for that specific resource</summary> public Dictionary<string, int> SummaryAvailable; /// <summary>Summary resource usage, keys are resource names, /// values are resource usage for that specific resource</summary> public Dictionary<string, int> SummaryUsed; /// <summary> /// Serializes object /// </summary> /// <returns><see cref="OSDMap"/> serialized data</returns> public virtual OSDMap Serialize() { throw new NotImplementedException(); } /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public virtual void Deserialize(OSDMap map) { SummaryAvailable = new Dictionary<string, int>(); SummaryUsed = new Dictionary<string, int>(); OSDMap summary = (OSDMap)map["summary"]; OSDArray available = (OSDArray)summary["available"]; OSDArray used = (OSDArray)summary["used"]; for (int i = 0; i < available.Count; i++) { OSDMap limit = (OSDMap)available[i]; SummaryAvailable.Add(limit["type"].AsString(), limit["amount"].AsInteger()); } for (int i = 0; i < used.Count; i++) { OSDMap limit = (OSDMap)used[i]; SummaryUsed.Add(limit["type"].AsString(), limit["amount"].AsInteger()); } } } /// <summary>Agent resource usage</summary> public class AttachmentResourcesMessage : BaseResourcesInfo { /// <summary>Per attachment point object resource usage</summary> public Dictionary<AttachmentPoint, ObjectResourcesDetail[]> Attachments; /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="osd">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap osd) { base.Deserialize(osd); OSDArray attachments = (OSDArray)((OSDMap)osd)["attachments"]; Attachments = new Dictionary<AttachmentPoint, ObjectResourcesDetail[]>(); for (int i = 0; i < attachments.Count; i++) { OSDMap attachment = (OSDMap)attachments[i]; AttachmentPoint pt = Utils.StringToAttachmentPoint(attachment["location"].AsString()); OSDArray objectsOSD = (OSDArray)attachment["objects"]; ObjectResourcesDetail[] objects = new ObjectResourcesDetail[objectsOSD.Count]; for (int j = 0; j < objects.Length; j++) { objects[j] = ObjectResourcesDetail.FromOSD(objectsOSD[j]); } Attachments.Add(pt, objects); } } /// <summary> /// Makes an instance based on deserialized data /// </summary> /// <param name="osd"><see cref="OSD"/> serialized data</param> /// <returns>Instance containg deserialized data</returns> public static AttachmentResourcesMessage FromOSD(OSD osd) { AttachmentResourcesMessage res = new AttachmentResourcesMessage(); res.Deserialize((OSDMap)osd); return res; } /// <summary> /// Detects which class handles deserialization of this message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> /// <returns>Object capable of decoding this message</returns> public static IMessage GetMessageHandler(OSDMap map) { if (map == null) { return null; } else { return new AttachmentResourcesMessage(); } } } /// <summary>Request message for parcel resource usage</summary> public class LandResourcesRequest : IMessage { /// <summary>UUID of the parel to request resource usage info</summary> public UUID ParcelID; /// <summary> /// Serializes object /// </summary> /// <returns><see cref="OSDMap"/> serialized data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); map["parcel_id"] = OSD.FromUUID(ParcelID); return map; } /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { ParcelID = map["parcel_id"].AsUUID(); } } /// <summary>Response message for parcel resource usage</summary> public class LandResourcesMessage : IMessage { /// <summary>URL where parcel resource usage details can be retrieved</summary> public Uri ScriptResourceDetails; /// <summary>URL where parcel resource usage summary can be retrieved</summary> public Uri ScriptResourceSummary; /// <summary> /// Serializes object /// </summary> /// <returns><see cref="OSDMap"/> serialized data</returns> public OSDMap Serialize() { OSDMap map = new OSDMap(1); if (ScriptResourceSummary != null) { map["ScriptResourceSummary"] = OSD.FromString(ScriptResourceSummary.ToString()); } if (ScriptResourceDetails != null) { map["ScriptResourceDetails"] = OSD.FromString(ScriptResourceDetails.ToString()); } return map; } /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public void Deserialize(OSDMap map) { if (map.ContainsKey("ScriptResourceSummary")) { ScriptResourceSummary = new Uri(map["ScriptResourceSummary"].AsString()); } if (map.ContainsKey("ScriptResourceDetails")) { ScriptResourceDetails = new Uri(map["ScriptResourceDetails"].AsString()); } } /// <summary> /// Detects which class handles deserialization of this message /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> /// <returns>Object capable of decoding this message</returns> public static IMessage GetMessageHandler(OSDMap map) { if (map.ContainsKey("parcel_id")) { return new LandResourcesRequest(); } else if (map.ContainsKey("ScriptResourceSummary")) { return new LandResourcesMessage(); } return null; } } /// <summary>Parcel resource usage</summary> public class LandResourcesInfo : BaseResourcesInfo { /// <summary>Array of <see cref="ParcelResourcesDetail"/> containing per percal resource usage</summary> public ParcelResourcesDetail[] Parcels; /// <summary> /// Deserializes object from OSD /// </summary> /// <param name="map">An <see cref="OSDMap"/> containing the data</param> public override void Deserialize(OSDMap map) { if (map.ContainsKey("summary")) { base.Deserialize(map); } else if (map.ContainsKey("parcels")) { OSDArray parcelsOSD = (OSDArray)map["parcels"]; Parcels = new ParcelResourcesDetail[parcelsOSD.Count]; for (int i = 0; i < parcelsOSD.Count; i++) { Parcels[i] = ParcelResourcesDetail.FromOSD(parcelsOSD[i]); } } } } #endregion Resource usage #region Display names /// <summary> /// Reply to request for bunch if display names /// </summary> public class GetDisplayNamesMessage : IMessage { /// <summary> Current display name </summary> public AgentDisplayName[] Agents = new AgentDisplayName[0]; /// <summary> Following UUIDs failed to return a valid display name </summary> public UUID[] BadIDs = new UUID[0]; /// <summary> /// Serializes the message /// </summary> /// <returns>OSD containting the messaage</returns> public OSDMap Serialize() { OSDArray agents = new OSDArray(); if (Agents != null && Agents.Length > 0) { for (int i = 0; i < Agents.Length; i++) { agents.Add(Agents[i].GetOSD()); } } OSDArray badIDs = new OSDArray(); if (BadIDs != null && BadIDs.Length > 0) { for (int i = 0; i < BadIDs.Length; i++) { badIDs.Add(new OSDUUID(BadIDs[i])); } } OSDMap ret = new OSDMap(); ret["agents"] = agents; ret["bad_ids"] = badIDs; return ret; } public void Deserialize(OSDMap map) { if (map["agents"].Type == OSDType.Array) { OSDArray osdAgents = (OSDArray)map["agents"]; if (osdAgents.Count > 0) { Agents = new AgentDisplayName[osdAgents.Count]; for (int i = 0; i < osdAgents.Count; i++) { Agents[i] = AgentDisplayName.FromOSD(osdAgents[i]); } } } if (map["bad_ids"].Type == OSDType.Array) { OSDArray osdBadIDs = (OSDArray)map["bad_ids"]; if (osdBadIDs.Count > 0) { BadIDs = new UUID[osdBadIDs.Count]; for (int i = 0; i < osdBadIDs.Count; i++) { BadIDs[i] = osdBadIDs[i]; } } } } } /// <summary> /// Message sent when requesting change of the display name /// </summary> public class SetDisplayNameMessage : IMessage { /// <summary> Current display name </summary> public string OldDisplayName; /// <summary> Desired new display name </summary> public string NewDisplayName; /// <summary> /// Serializes the message /// </summary> /// <returns>OSD containting the messaage</returns> public OSDMap Serialize() { OSDArray names = new OSDArray(2); names.Add(OldDisplayName); names.Add(NewDisplayName); OSDMap name = new OSDMap(); name["display_name"] = names; return name; } public void Deserialize(OSDMap map) { OSDArray names = (OSDArray)map["display_name"]; OldDisplayName = names[0]; NewDisplayName = names[1]; } } /// <summary> /// Message recieved in response to request to change display name /// </summary> public class SetDisplayNameReplyMessage : IMessage { /// <summary> New display name </summary> public AgentDisplayName DisplayName; /// <summary> String message indicating the result of the operation </summary> public string Reason; /// <summary> Numerical code of the result, 200 indicates success </summary> public int Status; /// <summary> /// Serializes the message /// </summary> /// <returns>OSD containting the messaage</returns> public OSDMap Serialize() { OSDMap agent = (OSDMap)DisplayName.GetOSD(); OSDMap ret = new OSDMap(); ret["content"] = agent; ret["reason"] = Reason; ret["status"] = Status; return ret; } public void Deserialize(OSDMap map) { OSDMap agent = (OSDMap)map["content"]; DisplayName = AgentDisplayName.FromOSD(agent); Reason = map["reason"]; Status = map["status"]; } } /// <summary> /// Message recieved when someone nearby changes their display name /// </summary> public class DisplayNameUpdateMessage : IMessage { /// <summary> Previous display name, empty string if default </summary> public string OldDisplayName; /// <summary> New display name </summary> public AgentDisplayName DisplayName; /// <summary> /// Serializes the message /// </summary> /// <returns>OSD containting the messaage</returns> public OSDMap Serialize() { OSDMap agent = (OSDMap)DisplayName.GetOSD(); agent["old_display_name"] = OldDisplayName; OSDMap ret = new OSDMap(); ret["agent"] = agent; return ret; } public void Deserialize(OSDMap map) { OSDMap agent = (OSDMap)map["agent"]; DisplayName = AgentDisplayName.FromOSD(agent); OldDisplayName = agent["old_display_name"]; } } #endregion Display names }
38.922633
1,323
0.546006
[ "BSD-3-Clause" ]
BigManzai/libopenmetaverse
OpenMetaverse/Messages/LindenMessages.cs
209,289
C#
using System; using System.Linq; namespace _04.AddVAT { public class AddVAT { public static void Main() { Console.ReadLine() .Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .Select(x => double.Parse(x) * 1.2) .ToList() .ForEach(x => Console.WriteLine($"{x:F2}")); } } }
22.111111
77
0.487437
[ "MIT" ]
George221b/SoftUni-Taks
C#Advanced/07.FunctionalProgrammingLab/04.AddVAT/AddVAT.cs
400
C#
namespace AlmOps.AzureDevOpsComponent.Infrastructure.RestApi.Dto { public class LogsDto { public int Id { get; set; } public string Type { get; set; } public string Url { get; set; } } }
22.4
65
0.611607
[ "Apache-2.0" ]
JamiePed/almops
src/AzureDevOpsComponent.Infrastructure.RestApi/Dto/LogsDto.cs
226
C#
using UnityEngine; using System.Collections.Generic; using PF; using Mathf = UnityEngine.Mathf; // Empty namespace declaration to avoid errors in the free version // Which does not have any classes in the RVO namespace namespace Pathfinding.RVO {} namespace Pathfinding { using Pathfinding.Util; #if UNITY_5_0 /** Used in Unity 5.0 since the HelpURLAttribute was first added in Unity 5.1 */ public class HelpURLAttribute : Attribute { } #endif [System.Serializable] /** Stores editor colors */ public class AstarColor { public Color _NodeConnection; public Color _UnwalkableNode; public Color _BoundsHandles; public Color _ConnectionLowLerp; public Color _ConnectionHighLerp; public Color _MeshEdgeColor; /** Holds user set area colors. * Use GetAreaColor to get an area color */ public Color[] _AreaColors; public static Color NodeConnection = new Color(1, 1, 1, 0.9F); public static Color UnwalkableNode = new Color(1, 0, 0, 0.5F); public static Color BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F); public static Color ConnectionLowLerp = new Color(0, 1, 0, 0.5F); public static Color ConnectionHighLerp = new Color(1, 0, 0, 0.5F); public static Color MeshEdgeColor = new Color(0, 0, 0, 0.5F); /** Holds user set area colors. * Use GetAreaColor to get an area color */ private static Color[] AreaColors; /** Returns an color for an area, uses both user set ones and calculated. * If the user has set a color for the area, it is used, but otherwise the color is calculated using Mathfx.IntToColor * \see #AreaColors */ public static Color GetAreaColor (uint area) { if (AreaColors == null || area >= AreaColors.Length) { return UnityHelper.IntToColor((int)area, 1F); } return AreaColors[(int)area]; } /** Pushes all local variables out to static ones. * This is done because that makes it so much easier to access the colors during Gizmo rendering * and it has a positive performance impact as well (gizmo rendering is hot code). */ public void OnEnable () { NodeConnection = _NodeConnection; UnwalkableNode = _UnwalkableNode; BoundsHandles = _BoundsHandles; ConnectionLowLerp = _ConnectionLowLerp; ConnectionHighLerp = _ConnectionHighLerp; MeshEdgeColor = _MeshEdgeColor; AreaColors = _AreaColors; } public AstarColor () { // Set default colors _NodeConnection = new Color(1, 1, 1, 0.9F); _UnwalkableNode = new Color(1, 0, 0, 0.5F); _BoundsHandles = new Color(0.29F, 0.454F, 0.741F, 0.9F); _ConnectionLowLerp = new Color(0, 1, 0, 0.5F); _ConnectionHighLerp = new Color(1, 0, 0, 0.5F); _MeshEdgeColor = new Color(0, 0, 0, 0.5F); } } /** Progress info for e.g a progressbar. * Used by the scan functions in the project * \see #AstarPath.ScanAsync */ public struct Progress { /** Current progress as a value between 0 and 1 */ public readonly float progress; /** Description of what is currently being done */ public readonly string description; public Progress (float progress, string description) { this.progress = progress; this.description = description; } public Progress MapTo (float min, float max, string prefix = null) { return new Progress(Mathf.Lerp(min, max, progress), prefix + description); } public override string ToString () { return progress.ToString("0.0") + " " + description; } } /** Represents a collection of settings used to update nodes in a specific region of a graph. * \see AstarPath.UpdateGraphs * \see \ref graph-updates */ public class GraphUpdateObject { /** The bounds to update nodes within. * Defined in world space. */ public Bounds bounds; /** Controlls if a flood fill will be carried out after this GUO has been applied. * Disabling this can be used to gain a performance boost, but use with care. * If you are sure that a GUO will not modify walkability or connections. You can set this to false. * For example when only updating penalty values it can save processing power when setting this to false. Especially on large graphs. * \note If you set this to false, even though it does change e.g walkability, it can lead to paths returning that they failed even though there is a path, * or the try to search the whole graph for a path even though there is none, and will in the processes use wast amounts of processing power. * * If using the basic GraphUpdateObject (not a derived class), a quick way to check if it is going to need a flood fill is to check if #modifyWalkability is true or #updatePhysics is true. * */ public bool requiresFloodFill = true; /** Use physics checks to update nodes. * When updating a grid graph and this is true, the nodes' position and walkability will be updated using physics checks * with settings from "Collision Testing" and "Height Testing". * * When updating a PointGraph, setting this to true will make it re-evaluate all connections in the graph which passes through the #bounds. * This has no effect when updating GridGraphs if #modifyWalkability is turned on. * * On RecastGraphs, having this enabled will trigger a complete recalculation of all tiles intersecting the bounds. * This is quite slow (but powerful). If you only want to update e.g penalty on existing nodes, leave it disabled. */ public bool updatePhysics = true; /** Reset penalties to their initial values when updating grid graphs and #updatePhysics is true. * If you want to keep old penalties even when you update the graph you may want to disable this option. * * The images below shows two overlapping graph update objects, the right one happened to be applied before the left one. They both have updatePhysics = true and are * set to increase the penalty of the nodes by some amount. * * The first image shows the result when resetPenaltyOnPhysics is false. Both penalties are added correctly. * \shadowimage{resetPenaltyOnPhysics_False.png} * * This second image shows when resetPenaltyOnPhysics is set to true. The first GUO is applied correctly, but then the second one (the left one) is applied * and during its updating, it resets the penalties first and then adds penalty to the nodes. The result is that the penalties from both GUOs are not added together. * The green patch in at the border is there because physics recalculation (recalculation of the position of the node, checking for obstacles etc.) affects a slightly larger * area than the original GUO bounds because of the Grid Graph -> Collision Testing -> Diameter setting (it is enlarged by that value). So some extra nodes have their penalties reset. * * \shadowimage{resetPenaltyOnPhysics_True.png} */ public bool resetPenaltyOnPhysics = true; /** Update Erosion for GridGraphs. * When enabled, erosion will be recalculated for grid graphs * after the GUO has been applied. * * In the below image you can see the different effects you can get with the different values.\n * The first image shows the graph when no GUO has been applied. The blue box is not identified as an obstacle by the graph, the reason * there are unwalkable nodes around it is because there is a height difference (nodes are placed on top of the box) so erosion will be applied (an erosion value of 2 is used in this graph). * The orange box is identified as an obstacle, so the area of unwalkable nodes around it is a bit larger since both erosion and collision has made * nodes unwalkable.\n * The GUO used simply sets walkability to true, i.e making all nodes walkable. * * \shadowimage{updateErosion.png} * * When updateErosion=True, the reason the blue box still has unwalkable nodes around it is because there is still a height difference * so erosion will still be applied. The orange box on the other hand has no height difference and all nodes are set to walkable.\n * \n * When updateErosion=False, all nodes walkability are simply set to be walkable in this example. * * \see Pathfinding.GridGraph */ public bool updateErosion = true; /** NNConstraint to use. * The Pathfinding.NNConstraint.SuitableGraph function will be called on the NNConstraint to enable filtering of which graphs to update.\n * \note As the Pathfinding.NNConstraint.SuitableGraph function is A* Pathfinding Project Pro only, this variable doesn't really affect anything in the free version. * * * \astarpro */ public NNConstraint nnConstraint = NNConstraint.None; /** Penalty to add to the nodes. * A penalty of 1000 is equivalent to the cost of moving 1 world unit. */ public int addPenalty; /** If true, all nodes' \a walkable variable will be set to #setWalkability */ public bool modifyWalkability; /** If #modifyWalkability is true, the nodes' \a walkable variable will be set to this value */ public bool setWalkability; /** If true, all nodes' \a tag will be set to #setTag */ public bool modifyTag; /** If #modifyTag is true, all nodes' \a tag will be set to this value */ public int setTag; /** Track which nodes are changed and save backup data. * Used internally to revert changes if needed. */ public bool trackChangedNodes; /** Nodes which were updated by this GraphUpdateObject. * Will only be filled if #trackChangedNodes is true. * \note It might take a few frames for graph update objects to be applied. * If you need this info immediately, use #AstarPath.FlushGraphUpdates. */ public List<GraphNode> changedNodes; private List<uint> backupData; private List<Int3> backupPositionData; /** A shape can be specified if a bounds object does not give enough precision. * Note that if you set this, you should set the bounds so that it encloses the shape * because the bounds will be used as an initial fast check for which nodes that should * be updated. */ public GraphUpdateShape shape; /** Should be called on every node which is updated with this GUO before it is updated. * \param node The node to save fields for. If null, nothing will be done * \see #trackChangedNodes */ public virtual void WillUpdateNode (GraphNode node) { if (trackChangedNodes && node != null) { if (changedNodes == null) { changedNodes = ListPool<GraphNode>.Claim(); backupData = ListPool<uint>.Claim(); backupPositionData = ListPool<Int3>.Claim(); } changedNodes.Add(node); backupPositionData.Add(node.position); backupData.Add(node.Penalty); backupData.Add(node.Flags); } } /** Reverts penalties and flags (which includes walkability) on every node which was updated using this GUO. * Data for reversion is only saved if #trackChangedNodes is true. * * \note Not all data is saved. The saved data includes: penalties, walkability, tags, area, position and for grid graphs (not layered) it also includes connection data. */ public virtual void RevertFromBackup () { if (trackChangedNodes) { if (changedNodes == null) return; int counter = 0; for (int i = 0; i < changedNodes.Count; i++) { changedNodes[i].Penalty = backupData[counter]; counter++; changedNodes[i].Flags = backupData[counter]; counter++; changedNodes[i].position = backupPositionData[i]; } ListPool<GraphNode>.Release(ref changedNodes); ListPool<uint>.Release(ref backupData); ListPool<Int3>.Release(ref backupPositionData); } else { throw new System.InvalidOperationException("Changed nodes have not been tracked, cannot revert from backup. Please set trackChangedNodes to true before applying the update."); } } /** Updates the specified node using this GUO's settings */ public virtual void Apply (GraphNode node) { if (shape == null || shape.Contains(node)) { //Update penalty and walkability node.Penalty = (uint)(node.Penalty+addPenalty); if (modifyWalkability) { node.Walkable = setWalkability; } //Update tags if (modifyTag) node.Tag = (uint)setTag; } } public GraphUpdateObject () { } /** Creates a new GUO with the specified bounds */ public GraphUpdateObject (Bounds b) { bounds = b; } } public delegate void OnGraphDelegate (NavGraph graph); public delegate void OnScanDelegate (AstarPath script); /** \deprecated */ public delegate void OnScanStatus (Progress progress); }
42.66443
193
0.707095
[ "MIT" ]
naivetang/2019MiniGame22
Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Core/astarclasses.cs
12,714
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ExamOnline { public partial class SiteMaster { /// <summary> /// HeadContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent; /// <summary> /// FeaturedContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent; /// <summary> /// MainContent control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent; } }
33.767442
87
0.519972
[ "MIT" ]
SensitiveMix/EXAM-ONLINE
Site.Master.designer.cs
1,454
C#